Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #43 from gugarn/master

Bug Fix in between clause and @PartKey and @ClusteringOrder annotation
  • Loading branch information...
commit a4fa4087a3d02e60fbe165ef6cf019a287e1cea9 2 parents 2b53da5 + dae17ae
Otávio Santana authored
35 src/main/java/org/easycassandra/ClusteringOrder.java
View
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2014 Gustavo.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.easycassandra;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * The field with this annotation is used to ordering in clusters. The field need to be part of primary key and not part
+ * of partition key.
+ *
+ * @author Gustavo Leitão
+ */
+@Target(ElementType.FIELD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface ClusteringOrder {
+
+ Order order() default Order.ASC;
+
+}
833 src/main/java/org/easycassandra/ColumnUtil.java 100755 → 100644
View
@@ -1,401 +1,434 @@
-/*
- * Copyright 2012 Otávio Gonçalves de Santana (otaviojava)
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.easycassandra;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-
-import javax.persistence.Column;
-import javax.persistence.ElementCollection;
-import javax.persistence.Embedded;
-import javax.persistence.EmbeddedId;
-import javax.persistence.Entity;
-import javax.persistence.Enumerated;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.MappedSuperclass;
-import javax.persistence.Table;
-import javax.persistence.Version;
-
-import org.easycassandra.util.ReflectionUtil;
-
-/**
- * Class Util for Column.
- * @author otavio
- */
-enum ColumnUtil {
- INTANCE;
-
- /**
- * list contains the annotations to map a bean.
- */
- private List<String> annotations;
- {
- annotations = new ArrayList<String>();
- annotations.add(Id.class.getName());
- annotations.add(ElementCollection.class.getName());
- annotations.add(SetData.class.getName());
- annotations.add(ListData.class.getName());
- annotations.add(MapData.class.getName());
- annotations.add(Column.class.getName());
- annotations.add(Embedded.class.getName());
- annotations.add(EmbeddedId.class.getName());
- annotations.add(Enumerated.class.getName());
- annotations.add(Index.class.getName());
- annotations.add(CustomData.class.getName());
- Collections.sort(annotations);
- }
-
-
- /**
- * Get The Column name from an Object.
- * @param object
- * - Class of the object viewed
- * @return The name of Column name if there are not will be return null
- */
- public String getColumnFamilyNameSchema(Class<?> object) {
- String schema = getSchemaConcat(object);
- return schema.concat(getColumnFamily(object));
- }
-
- public String getColumnFamily(Class<?> object) {
- Entity columnFamily = (Entity) object.getAnnotation(Entity.class);
- Table columnFamilyTable = (Table) object.getAnnotation(Table.class);
- if (columnFamily != null) {
- return columnFamily.name().equals("") ? object.getSimpleName()
- : columnFamily.name();
- } else if (columnFamilyTable != null) {
- return columnFamilyTable.name().equals("") ? object.getSimpleName()
- : columnFamilyTable.name();
- }
- return object.getSimpleName();
- }
-
- private String getSchemaConcat(Class<?> class1) {
- String schema = getSchema(class1);
- if (!"".equals(schema)) {
- return schema.concat(".");
- }
- return "";
- }
-
- /**
- * return the chema looking to class.
- * @param class1 the class
- * @return the schema
- */
- public String getSchema(Class<?> class1) {
- Table columnFamily = (Table) class1.getAnnotation(Table.class);
- if (columnFamily != null) {
- return columnFamily.schema();
- }
- return "";
- }
-
- /**
- * verifies that the name of the annotation is empty if you take the field
- * name.
- * @param field
- * - field for viewd
- * @return The name inside annotations or the field's name
- */
- public String getColumnName(Field field) {
- if (field.getAnnotation(javax.persistence.Column.class) == null) {
- return field.getName();
- }
- return field.getAnnotation(javax.persistence.Column.class).name()
- .equals("") ? field.getName() : field.getAnnotation(
- javax.persistence.Column.class).name();
- }
-
- /**
- * verifies that the name of the annotation is empty if you take the field.
- * name
- * @param field the field
- * @return The name inside annotations or the field's name
- */
- public String getEnumeratedName(Field field) {
- if (isNormalField(field)) {
- return getColumnName(field);
- }
- return field.getName();
- }
-
- /**
- * Return the Field with the KeyValue Annotations.
- * @see KeyValue
- * @param persistenceClass
- * - Class of the object viewed
- * @return the Field if there are not will be return null
- */
- public Field getKeyField(Class<?> persistenceClass) {
- Field field = getField(persistenceClass, Id.class);
- if (field == null) {
- return getField(persistenceClass.getSuperclass(), Id.class);
- }
- return field;
- }
-
- /**
- * Return the Field with the complex key Annotations.
- * @see KeyValue
- * @param persistenceClass
- * - Class of the object viewed
- * @return the Field if there are not will be return null
- */
- public Field getKeyComplexField(Class<?> persistenceClass) {
- Field field = getField(persistenceClass, EmbeddedId.class);
- if (field == null) {
- return getField(persistenceClass.getSuperclass(), EmbeddedId.class);
- }
- return field;
- }
-
- /**
- * Return the Field with the IndexValue Annotations.
- * @see Index
- * @param persistenceClass
- * - Class of the object viewed
- * @return the Field if there are not will be return null
- */
- public Field getIndexField(Class<?> persistenceClass) {
- return getField(persistenceClass, Index.class);
- }
-
- /**
- * Return the Fields with the IndexValue Annotations.
- * @author Dinusha Nandika
- * @see Index
- * @param persistenceClass
- * - Class of the object viewed
- * @return the Fields if there are not will be return empty list
- */
- public List<FieldInformation> getIndexFields(Class<?> persistenceClass) {
- List<FieldInformation> indexFieldList = new ArrayList<>();
- for (Field field : persistenceClass.getDeclaredFields()) {
- if (field.getAnnotation(Index.class) != null) {
- indexFieldList.add(new FieldInformation(field));
- } else if (field.getAnnotation(Embedded.class) != null) {
- indexFieldList.addAll(getIndexFields(field.getType()));
- }
- }
- return indexFieldList;
- }
- /**
- * Get the Field of the Object from annotation if there are not return will.
- * be null
- * @param object
- * - Class of the object viewed
- * @param annotation the annotation
- * @return the field with annotation and null if does not exist
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public Field getField(Class object, Class annotation) {
- for (Field field : object.getDeclaredFields()) {
- if (field.getAnnotation(annotation) != null) {
- return field;
- } else if (field.getAnnotation(Embedded.class) != null) {
- return getField(field.getType(), annotation);
- }
- }
- return null;
- }
-
- /**
- * list the fields in the class.
- * @param class1 the class
- * @return list of the fields
- */
- public List<FieldInformation> listFields(Class<?> class1) {
- List<FieldInformation> fields = new LinkedList<>();
- feedFieldList(class1, fields);
- if (isMappedSuperclass(class1)) {
- feedFieldList(class1.getSuperclass(), fields);
-
- }
- return fields;
- }
-
- /**
- * feed the list with Fields.
- * @param class1
- * @param fields
- */
- private void feedFieldList(Class<?> class1, List<FieldInformation> fields) {
-
- for (Field field : class1.getDeclaredFields()) {
-
- if (isColumnToPersist(field)) {
- fields.add(new FieldInformation(field));
- }
-
- }
- }
-
- /**
- * verify is field has some annotations within.
- * {@link #ColumnUtil#annotations}
- * @param field
- * @return
- */
- private boolean isColumnToPersist(Field field) {
-
- for (Annotation annotation : field.getAnnotations()) {
- int result = Collections.binarySearch(annotations, annotation
- .annotationType().getName());
- if (result >= 0) {
- return true;
- }
- }
- return false;
- }
- /**
- * verify if this is key of the column.
- * @param field the field
- * @return is id
- */
- public boolean isIdField(Field field) {
- return field.getAnnotation(Id.class) != null;
- }
-
- /**
- * verify if this is index of the column.
- * @param field the feiold
- * @return if index
- */
- public boolean isIndexField(Field field) {
- return field.getAnnotation(Index.class) != null;
- }
-
- /**
- * verify if this is GeneratedValue of the column.
- * @param field the field
- * @return if GeneratedValue
- */
- @GeneratedValue
- public boolean isGeneratedValue(Field field) {
- return field.getAnnotation(GeneratedValue.class) != null;
- }
-
- /**
- * verify if this is secundary index of the column.
- * @param field the field
- * @return the exist
- */
- public boolean isSecundaryIndexField(Field field) {
- return field.getAnnotation(Index.class) != null;
- }
-
- /**
- * verify if this is a normal column.
- * @param field the field
- * @return if has column annotation
- */
- public boolean isNormalField(Field field) {
- return field.getAnnotation(javax.persistence.Column.class) != null;
- }
-
- /**
- * verify if this is a enum column.
- * @param field the field
- * @return if has Enumerated annotation
- */
- public boolean isEnumField(Field field) {
- return field.getAnnotation(Enumerated.class) != null;
- }
-
- /**
- * verify if this is a Embedded column.
- * @param field the field
- * @return if has Embedded annotation
- */
- public boolean isEmbeddedField(Field field) {
- return field.getAnnotation(Embedded.class) != null;
- }
-
- /**
- * verify if this is a Embedded id column.
- * @param field the field
- * @return if has EmbeddedId annotation
- */
- public boolean isEmbeddedIdField(Field field) {
- return field.getAnnotation(EmbeddedId.class) != null;
- }
-
- /**
- * verify if this is a Version column.
- * @param field the field
- * @return if has Version annotation
- */
- public boolean isVersionField(Field field) {
- return field.getAnnotation(Version.class) != null;
- }
-
- /**
- * verify is exist father to persist.
- * @param class1 the class
- * @return is has MappedSuperclass annotation
- */
- public boolean isMappedSuperclass(Class<?> class1) {
- return class1.getSuperclass().getAnnotation(MappedSuperclass.class) != null;
- }
- /**
- * verify if the field is a list.
- * @param field the field
- * @return if has ListData annotation
- */
- public boolean isList(Field field) {
- return field.getAnnotation(ListData.class) != null;
- }
- /**
- * verify if the field is a map.
- * @param field the field
- * @return if has MapData annotation
- */
- public boolean isMap(Field field){
- return field.getAnnotation(MapData.class) != null;
- }
- /**
- * verify if the field is a set.
- * @param field the field
- * @return if has SetData annotation
- */
- public boolean isSet(Field field) {
- return field.getAnnotation(SetData.class) != null;
- }
-
- /**
- * verify if the field is custom.
- * @param field the field
- * @return if has CustomData annotation
- */
- public boolean isCustom(Field field) {
- return field.getAnnotation(CustomData.class) != null;
- }
- /**
- * verify if the field is element Collection.
- * @param field the field
- * @return if has ElementCollection annotation
- */
- public boolean isElementCollection(Field field) {
- return field.getAnnotation(ElementCollection.class) != null;
- }
-
-
+/*
+ * Copyright 2012 Otávio Gonçalves de Santana (otaviojava)
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.easycassandra;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.persistence.Column;
+import javax.persistence.ElementCollection;
+import javax.persistence.Embedded;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.Enumerated;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Table;
+import javax.persistence.Version;
+
+import org.easycassandra.util.ReflectionUtil;
+
+/**
+ * Class Util for Column.
+ * @author otavio
+ */
+enum ColumnUtil {
+ INTANCE;
+
+ /**
+ * list contains the annotations to map a bean.
+ */
+ private List<String> annotations;
+ {
+ annotations = new ArrayList<String>();
+ annotations.add(Id.class.getName());
+ annotations.add(ElementCollection.class.getName());
+ annotations.add(SetData.class.getName());
+ annotations.add(ListData.class.getName());
+ annotations.add(MapData.class.getName());
+ annotations.add(Column.class.getName());
+ annotations.add(Embedded.class.getName());
+ annotations.add(EmbeddedId.class.getName());
+ annotations.add(Enumerated.class.getName());
+ annotations.add(Index.class.getName());
+ annotations.add(CustomData.class.getName());
+ Collections.sort(annotations);
+ }
+
+
+ /**
+ * Get The Column name from an Object.
+ * @param object
+ * - Class of the object viewed
+ * @return The name of Column name if there are not will be return null
+ */
+ public String getColumnFamilyNameSchema(Class<?> object) {
+ String schema = getSchemaConcat(object);
+ return schema.concat(getColumnFamily(object));
+ }
+
+ public String getColumnFamily(Class<?> object) {
+ Entity columnFamily = (Entity) object.getAnnotation(Entity.class);
+ Table columnFamilyTable = (Table) object.getAnnotation(Table.class);
+ if (columnFamily != null) {
+ return columnFamily.name().equals("") ? object.getSimpleName()
+ : columnFamily.name();
+ } else if (columnFamilyTable != null) {
+ return columnFamilyTable.name().equals("") ? object.getSimpleName()
+ : columnFamilyTable.name();
+ }
+ return object.getSimpleName();
+ }
+
+ private String getSchemaConcat(Class<?> class1) {
+ String schema = getSchema(class1);
+ if (!"".equals(schema)) {
+ return schema.concat(".");
+ }
+ return "";
+ }
+
+ /**
+ * return the chema looking to class.
+ * @param class1 the class
+ * @return the schema
+ */
+ public String getSchema(Class<?> class1) {
+ Table columnFamily = (Table) class1.getAnnotation(Table.class);
+ if (columnFamily != null) {
+ return columnFamily.schema();
+ }
+ return "";
+ }
+
+ /**
+ * verifies that the name of the annotation is empty if you take the field
+ * name.
+ * @param field
+ * - field for viewd
+ * @return The name inside annotations or the field's name
+ */
+ public String getColumnName(Field field) {
+ if (field.getAnnotation(javax.persistence.Column.class) == null) {
+ return field.getName();
+ }
+ return field.getAnnotation(javax.persistence.Column.class).name()
+ .equals("") ? field.getName() : field.getAnnotation(
+ javax.persistence.Column.class).name();
+ }
+
+ /**
+ * verifies that the name of the annotation is empty if you take the field.
+ * name
+ * @param field the field
+ * @return The name inside annotations or the field's name
+ */
+ public String getEnumeratedName(Field field) {
+ if (isNormalField(field)) {
+ return getColumnName(field);
+ }
+ return field.getName();
+ }
+
+ /**
+ * Return the Field with the KeyValue Annotations.
+ * @see KeyValue
+ * @param persistenceClass
+ * - Class of the object viewed
+ * @return the Field if there are not will be return null
+ */
+ public Field getKeyField(Class<?> persistenceClass) {
+ Field field = getField(persistenceClass, Id.class);
+ if (field == null) {
+ return getField(persistenceClass.getSuperclass(), Id.class);
+ }
+ return field;
+ }
+
+ /**
+ * Return the Field with the complex key Annotations.
+ * @see KeyValue
+ * @param persistenceClass
+ * - Class of the object viewed
+ * @return the Field if there are not will be return null
+ */
+ public Field getKeyComplexField(Class<?> persistenceClass) {
+ Field field = getField(persistenceClass, EmbeddedId.class);
+ if (field == null) {
+ return getField(persistenceClass.getSuperclass(), EmbeddedId.class);
+ }
+ return field;
+ }
+
+ /**
+ * Return the Field with the IndexValue Annotations.
+ * @see Index
+ * @param persistenceClass
+ * - Class of the object viewed
+ * @return the Field if there are not will be return null
+ */
+ public Field getIndexField(Class<?> persistenceClass) {
+ return getField(persistenceClass, Index.class);
+ }
+
+ /**
+ * Return the Fields with the IndexValue Annotations.
+ * @author Dinusha Nandika
+ * @see Index
+ * @param persistenceClass
+ * - Class of the object viewed
+ * @return the Fields if there are not will be return empty list
+ */
+ public List<FieldInformation> getIndexFields(Class<?> persistenceClass) {
+ List<FieldInformation> indexFieldList = new ArrayList<>();
+ for (Field field : persistenceClass.getDeclaredFields()) {
+ if (field.getAnnotation(Index.class) != null) {
+ indexFieldList.add(new FieldInformation(field));
+ } else if (field.getAnnotation(Embedded.class) != null) {
+ indexFieldList.addAll(getIndexFields(field.getType()));
+ }
+ }
+ return indexFieldList;
+ }
+ /**
+ * Get the Field of the Object from annotation if there are not return will.
+ * be null
+ * @param object
+ * - Class of the object viewed
+ * @param annotation the annotation
+ * @return the field with annotation and null if does not exist
+ */
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public Field getField(Class object, Class annotation) {
+ for (Field field : object.getDeclaredFields()) {
+ if (field.getAnnotation(annotation) != null) {
+ return field;
+ } else if (field.getAnnotation(Embedded.class) != null) {
+ return getField(field.getType(), annotation);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * list the fields in the class.
+ * @param class1 the class
+ * @return list of the fields
+ */
+ public List<FieldInformation> listFields(Class<?> class1) {
+ List<FieldInformation> fields = new LinkedList<>();
+ feedFieldList(class1, fields);
+ if (isMappedSuperclass(class1)) {
+ feedFieldList(class1.getSuperclass(), fields);
+
+ }
+ return fields;
+ }
+
+ /**
+ * feed the list with Fields.
+ * @param class1
+ * @param fields
+ */
+ private void feedFieldList(Class<?> class1, List<FieldInformation> fields) {
+
+ for (Field field : class1.getDeclaredFields()) {
+
+ if (isColumnToPersist(field)) {
+ fields.add(new FieldInformation(field));
+ }
+
+ }
+ }
+
+ /**
+ * verify is field has some annotations within.
+ * {@link #ColumnUtil#annotations}
+ * @param field
+ * @return
+ */
+ private boolean isColumnToPersist(Field field) {
+
+ for (Annotation annotation : field.getAnnotations()) {
+ int result = Collections.binarySearch(annotations, annotation
+ .annotationType().getName());
+ if (result >= 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+ /**
+ * verify if this is key of the column.
+ * @param field the field
+ * @return is id
+ */
+ public boolean isIdField(Field field) {
+ return field.getAnnotation(Id.class) != null;
+ }
+
+ /**
+ * verify if this is index of the column.
+ * @param field the feiold
+ * @return if index
+ */
+ public boolean isIndexField(Field field) {
+ return field.getAnnotation(Index.class) != null;
+ }
+
+ /**
+ * verify if this is GeneratedValue of the column.
+ * @param field the field
+ * @return if GeneratedValue
+ */
+ @GeneratedValue
+ public boolean isGeneratedValue(Field field) {
+ return field.getAnnotation(GeneratedValue.class) != null;
+ }
+
+ /**
+ * verify if this is secundary index of the column.
+ * @param field the field
+ * @return the exist
+ */
+ public boolean isSecundaryIndexField(Field field) {
+ return field.getAnnotation(Index.class) != null;
+ }
+
+ /**
+ * verify if this is a normal column.
+ * @param field the field
+ * @return if has column annotation
+ */
+ public boolean isNormalField(Field field) {
+ return field.getAnnotation(javax.persistence.Column.class) != null;
+ }
+
+ /**
+ * verify if this is a enum column.
+ * @param field the field
+ * @return if has Enumerated annotation
+ */
+ public boolean isEnumField(Field field) {
+ return field.getAnnotation(Enumerated.class) != null;
+ }
+
+ /**
+ * verify if this is a Embedded column.
+ * @param field the field
+ * @return if has Embedded annotation
+ */
+ public boolean isEmbeddedField(Field field) {
+ return field.getAnnotation(Embedded.class) != null;
+ }
+
+ /**
+ * verify if this is a Partkey id column.
+ * @param field the field
+ * @return if has PartKey annotation
+ */
+ public boolean isPartkeyField(Field field) {
+ return field.getAnnotation(Partkey.class) != null;
+ }
+
+ /**
+ * verify is this field is Cluester Ordering column.
+ *
+ * @param field the field
+ * @return if has ClusteringOrder annotation
+ */
+ public boolean isClusteringOrderField(Field field) {
+ return field.getAnnotation(ClusteringOrder.class) != null;
+ }
+
+ /**
+ * Retrieve the cluster order.
+ *
+ * @param field the field
+ * @return The instance of Order that indicates the order
+ */
+ public Order getClusterOrder(Field field) {
+ Order order = null;
+ if (isClusteringOrderField(field)) {
+ order = field.getAnnotation(ClusteringOrder.class).order();
+ }
+ return order;
+ }
+
+ /**
+ * verify if this is a Embedded id column.
+ * @param field the field
+ * @return if has EmbeddedId annotation
+ */
+ public boolean isEmbeddedIdField(Field field) {
+ return field.getAnnotation(EmbeddedId.class) != null;
+ }
+
+ /**
+ * verify if this is a Version column.
+ * @param field the field
+ * @return if has Version annotation
+ */
+ public boolean isVersionField(Field field) {
+ return field.getAnnotation(Version.class) != null;
+ }
+
+ /**
+ * verify is exist father to persist.
+ * @param class1 the class
+ * @return is has MappedSuperclass annotation
+ */
+ public boolean isMappedSuperclass(Class<?> class1) {
+ return class1.getSuperclass().getAnnotation(MappedSuperclass.class) != null;
+ }
+ /**
+ * verify if the field is a list.
+ * @param field the field
+ * @return if has ListData annotation
+ */
+ public boolean isList(Field field) {
+ return field.getAnnotation(ListData.class) != null;
+ }
+ /**
+ * verify if the field is a map.
+ * @param field the field
+ * @return if has MapData annotation
+ */
+ public boolean isMap(Field field){
+ return field.getAnnotation(MapData.class) != null;
+ }
+ /**
+ * verify if the field is a set.
+ * @param field the field
+ * @return if has SetData annotation
+ */
+ public boolean isSet(Field field) {
+ return field.getAnnotation(SetData.class) != null;
+ }
+
+ /**
+ * verify if the field is custom.
+ * @param field the field
+ * @return if has CustomData annotation
+ */
+ public boolean isCustom(Field field) {
+ return field.getAnnotation(CustomData.class) != null;
+ }
+ /**
+ * verify if the field is element Collection.
+ * @param field the field
+ * @return if has ElementCollection annotation
+ */
+ public boolean isElementCollection(Field field) {
+ return field.getAnnotation(ElementCollection.class) != null;
+ }
+
+
}
417 src/main/java/org/easycassandra/FieldInformation.java
View
@@ -1,191 +1,226 @@
-package org.easycassandra;
-
-import java.lang.reflect.Field;
-
-import org.easycassandra.util.ReflectionUtil;
-
-/**
- * this data structured has information about the field on a class.
- * @author otaviojava
- *
- */
-public class FieldInformation implements Comparable<FieldInformation> {
- /**
- * the kind of field from annotation.
- */
- private FieldType type;
- /**
- * the field.
- */
- private Field field;
- /**
- * the name.
- */
- private String name;
- /**
- * if the {@link FieldInformation#type} been
- * {@link FieldType#COLLECTION} will use it to define
- * the kind of collection, if not will be
- * {@link FieldType#EMPTY}.
- */
- private FieldType collectionType;
-
- /**
- * if the {@link FieldInformation#type} been
- * {@link FieldType#COLLECTION}, {@link FieldType#SET}
- * {@link FieldType#LIST}, {@link FieldType#MAP} if not will {@link FieldType#EMPTY}.
- */
- private Class<?> key;
- /**
- * if the {@link FieldInformation#type} been
- * {@link FieldType#MAP}, if not will {@link FieldType#EMPTY}.
- */
- private Class<?> value;
- /**
- * indicates this field is embedded.
- */
- private boolean embedded;
- /**
- * indicates this field is key.
- */
- private boolean keyCheck;
- /**
- * list of information when this field is embedded or embedded Id.
- */
- private ClassInformation subFields;
-
- /**
- * {@link FieldInformation#type}.
- * @return {@link FieldInformation#type}
- */
- public FieldType getType() {
- return type;
- }
- /**
- * {@link FieldInformation#field}.
- * @return {@link FieldInformation#field}
- */
- public Field getField() {
- return field;
- }
-
- /**
- * {@link FieldInformation#name}.
- * @return {@link FieldInformation#name}
- */
- public String getName() {
- return name;
- }
- /**
- * {@link FieldInformation#collectionType}.
- * @return {@link FieldInformation#collectionType}
- */
- public FieldType getCollectionType() {
- return collectionType;
- }
- /**
- * {@link FieldInformation#key}.
- * @return {@link FieldInformation#key}
- */
- public Class<?> getKey() {
- return key;
- }
- /**
- * {@link FieldInformation#value}.
- * @return {@link FieldInformation#value}
- */
- public Class<?> getValue() {
- return value;
- }
- /**
- * {@link FieldInformation#embedded}.
- * @return {@link FieldInformation#embedded}
- */
- public boolean isEmbedded() {
- return embedded;
- }
- /**
- * {@link FieldInformation#subFields}.
- * @return {@link FieldInformation#subFields}
- */
- public ClassInformation getSubFields() {
- return subFields;
- }
- public boolean isKeyCheck() {
- return keyCheck;
- }
- /**
- * create the class with field.
- * @param field - field to receive the information
- */
- FieldInformation(Field field) {
- this.embedded = ColumnUtil.INTANCE.isEmbeddedField(field)
- || ColumnUtil.INTANCE.isEmbeddedIdField(field);
-
- this.keyCheck = ColumnUtil.INTANCE.isEmbeddedIdField(field)
- || ColumnUtil.INTANCE.isIdField(field);
- this.type = FieldType.getTypeByField(field);
- this.field = field;
- this.collectionType = FieldType.EMPTY;
- this.name = ColumnUtil.INTANCE.getColumnName(field);
- ReflectionUtil.INSTANCE.makeAccessible(field);
- if (embedded) {
- subFields = ClassInformations.INSTACE.getClass(field.getType());
- }
- definesType();
-
- }
- /**
- * constructor just to bynary search.
- * @param name the name of field
- */
- FieldInformation(String name) {
- this.name = name;
- }
- private void definesType() {
- switch (type) {
- case COLLECTION:
- this.collectionType = FieldType.findCollectionbyQualifield(field);
- definesCollectionType();
- break;
- case SET:
- case LIST:
- key = ReflectionUtil.INSTANCE.getGenericType(field);
- break;
- case MAP:
- ReflectionUtil.KeyValueClass keyValueClass = ReflectionUtil.INSTANCE
- .getGenericKeyValue(field);
- this.key = keyValueClass.getKeyClass();
- this.value = keyValueClass.getValueClass();
- break;
- default:
- break;
- }
- }
-
- private void definesCollectionType() {
- switch (collectionType) {
- case SET:
- case LIST:
- key = ReflectionUtil.INSTANCE.getGenericType(field);
- break;
- case MAP:
- ReflectionUtil.KeyValueClass keyValueClass = ReflectionUtil.INSTANCE
- .getGenericKeyValue(field);
- this.key = keyValueClass.getKeyClass();
- this.value = keyValueClass.getValueClass();
- break;
- default:
- break;
- }
- }
- @Override
- public int compareTo(FieldInformation other) {
- return name.compareTo(other.name);
- }
-
- @Override
- public String toString() {
- return name;
- }
-}
+package org.easycassandra;
+
+import java.lang.reflect.Field;
+
+import org.easycassandra.util.ReflectionUtil;
+
+/**
+ * this data structured has information about the field on a class.
+ * @author otaviojava
+ *
+ */
+public class FieldInformation implements Comparable<FieldInformation> {
+ /**
+ * the kind of field from annotation.
+ */
+ private FieldType type;
+ /**
+ * the field.
+ */
+ private Field field;
+ /**
+ * the name.
+ */
+ private String name;
+ /**
+ * if the {@link FieldInformation#type} been
+ * {@link FieldType#COLLECTION} will use it to define
+ * the kind of collection, if not will be
+ * {@link FieldType#EMPTY}.
+ */
+ private FieldType collectionType;
+
+ /**
+ * if the {@link FieldInformation#type} been
+ * {@link FieldType#COLLECTION}, {@link FieldType#SET}
+ * {@link FieldType#LIST}, {@link FieldType#MAP} if not will {@link FieldType#EMPTY}.
+ */
+ private Class<?> key;
+ /**
+ * if the {@link FieldInformation#type} been
+ * {@link FieldType#MAP}, if not will {@link FieldType#EMPTY}.
+ */
+ private Class<?> value;
+ /**
+ * indicates this field is embedded.
+ */
+ private boolean embedded;
+ /**
+ * indicates this field is key.
+ */
+ private boolean keyCheck;
+ /**
+ * indicates this field is partkey.
+ */
+ private boolean partkeyCheck;
+
+ /**
+ * indicates if the field is part of ordering cluster.
+ */
+ private boolean clusteringOrderCheck;
+
+ /**
+ * indicates the order
+ */
+ private Order order;
+
+ /**
+ * list of information when this field is embedded or embedded Id.
+ */
+ private ClassInformation subFields;
+
+ /**
+ * {@link FieldInformation#type}.
+ * @return {@link FieldInformation#type}
+ */
+ public FieldType getType() {
+ return type;
+ }
+ /**
+ * {@link FieldInformation#field}.
+ * @return {@link FieldInformation#field}
+ */
+ public Field getField() {
+ return field;
+ }
+
+ /**
+ * {@link FieldInformation#name}.
+ * @return {@link FieldInformation#name}
+ */
+ public String getName() {
+ return name;
+ }
+ /**
+ * {@link FieldInformation#collectionType}.
+ * @return {@link FieldInformation#collectionType}
+ */
+ public FieldType getCollectionType() {
+ return collectionType;
+ }
+ /**
+ * {@link FieldInformation#key}.
+ * @return {@link FieldInformation#key}
+ */
+ public Class<?> getKey() {
+ return key;
+ }
+ /**
+ * {@link FieldInformation#value}.
+ * @return {@link FieldInformation#value}
+ */
+ public Class<?> getValue() {
+ return value;
+ }
+ /**
+ * {@link FieldInformation#embedded}.
+ * @return {@link FieldInformation#embedded}
+ */
+ public boolean isEmbedded() {
+ return embedded;
+ }
+ /**
+ * {@link FieldInformation#subFields}.
+ * @return {@link FieldInformation#subFields}
+ */
+ public ClassInformation getSubFields() {
+ return subFields;
+ }
+ public boolean isKeyCheck() {
+ return keyCheck;
+ }
+
+ public boolean isPartKeyCheck() {
+ return partkeyCheck;
+ }
+
+ public boolean isClusteringOrderCheck() {
+ return clusteringOrderCheck;
+ }
+
+ public Order getOrder() {
+ return order;
+ }
+
+ /**
+ * create the class with field.
+ * @param field - field to receive the information
+ */
+ FieldInformation(Field field) {
+ this.embedded = ColumnUtil.INTANCE.isEmbeddedField(field)
+ || ColumnUtil.INTANCE.isEmbeddedIdField(field);
+
+ this.keyCheck = ColumnUtil.INTANCE.isEmbeddedIdField(field)
+ || ColumnUtil.INTANCE.isIdField(field);
+
+ this.partkeyCheck = ColumnUtil.INTANCE.isPartkeyField(field);
+
+ this.clusteringOrderCheck = ColumnUtil.INTANCE.isClusteringOrderField(field);
+
+ this.order = ColumnUtil.INTANCE.getClusterOrder(field);
+
+ this.type = FieldType.getTypeByField(field);
+ this.field = field;
+ this.collectionType = FieldType.EMPTY;
+ this.name = ColumnUtil.INTANCE.getColumnName(field);
+ ReflectionUtil.INSTANCE.makeAccessible(field);
+ if (embedded) {
+ subFields = ClassInformations.INSTACE.getClass(field.getType());
+ }
+ definesType();
+
+ }
+ /**
+ * constructor just to bynary search.
+ * @param name the name of field
+ */
+ FieldInformation(String name) {
+ this.name = name;
+ }
+ private void definesType() {
+ switch (type) {
+ case COLLECTION:
+ this.collectionType = FieldType.findCollectionbyQualifield(field);
+ definesCollectionType();
+ break;
+ case SET:
+ case LIST:
+ key = ReflectionUtil.INSTANCE.getGenericType(field);
+ break;
+ case MAP:
+ ReflectionUtil.KeyValueClass keyValueClass = ReflectionUtil.INSTANCE
+ .getGenericKeyValue(field);
+ this.key = keyValueClass.getKeyClass();
+ this.value = keyValueClass.getValueClass();
+ break;
+ default:
+ break;
+ }
+ }
+
+ private void definesCollectionType() {
+ switch (collectionType) {
+ case SET:
+ case LIST:
+ key = ReflectionUtil.INSTANCE.getGenericType(field);
+ break;
+ case MAP:
+ ReflectionUtil.KeyValueClass keyValueClass = ReflectionUtil.INSTANCE
+ .getGenericKeyValue(field);
+ this.key = keyValueClass.getKeyClass();
+ this.value = keyValueClass.getValueClass();
+ break;
+ default:
+ break;
+ }
+ }
+ @Override
+ public int compareTo(FieldInformation other) {
+ return name.compareTo(other.name);
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+}
26 src/main/java/org/easycassandra/Order.java
View
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2014 Gustavo.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.easycassandra;
+
+/**
+ * Options to cluester ordering.
+ *
+ * @author Gustavo Leitão
+ */
+public enum Order {
+
+ ASC, DESC;
+};
31 src/main/java/org/easycassandra/Partkey.java
View
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.easycassandra;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * The field with this annotation is part of partkey. The partkey is part of complex primary key that cassandra uses to
+ * separete data in diferents clusters.
+ *
+ * @author Gustavo Leitão
+ */
+@Target(ElementType.FIELD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Partkey {
+}
671 src/main/java/org/easycassandra/persistence/cassandra/FixColumnFamily.java 100755 → 100644
View
@@ -1,303 +1,368 @@
-/*
- * Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.easycassandra.persistence.cassandra;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.logging.Logger;
-
-import org.easycassandra.ClassInformation;
-import org.easycassandra.ClassInformations;
-import org.easycassandra.FieldInformation;
-import org.easycassandra.FieldJavaNotEquivalentCQLException;
-import org.easycassandra.KeyProblemsException;
-import org.easycassandra.persistence.cassandra.AddColumnUtil.AddColumn;
-import org.easycassandra.persistence.cassandra.VerifyRowUtil.VerifyRow;
-
-import com.datastax.driver.core.ColumnDefinitions.Definition;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.exceptions.InvalidQueryException;
-import com.datastax.driver.core.querybuilder.QueryBuilder;
-import com.datastax.driver.core.querybuilder.Select;
-
-/**
- * Class to fix a column family.
- * @author otaviojava
- */
-class FixColumnFamily {
-
- private static final String QUERY_PRIMARY_KEY = " PRIMARY KEY (";
-
- /**
- * verify if exist column family and try to create.
- * @param session - bridge to cassandra data base
- * @param keySpace - the keyspace
- * @param familyColumn - name of family column
- * @param class1 - bean
- * @return - if get it or not
- */
- public boolean verifyColumnFamily(Session session, String keySpace, String familyColumn,
- Class<?> class1) {
- try {
- Select select = QueryBuilder.select().from(keySpace, familyColumn).limit(1);
- ResultSet resultSet = session.execute(select);
- verifyRowType(resultSet, class1, session);
- findIndex(class1, session);
- return true;
- } catch (InvalidQueryException exception) {
-
- if (exception.getCause().getMessage().contains("unconfigured columnfamily ")) {
- Logger.getLogger(FixColumnFamily.class.getName()).info(
- "Column family doesn't exist, try to create");
- createColumnFamily(familyColumn, class1, session);
- findIndex(class1, session);
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Column family exists verify.
- * @param resultSet
- */
- private void verifyRowType(ResultSet resultSet, Class<?> class1, Session session) {
- Map<String, String> mapNameType = new HashMap<String, String>();
- for (Definition column : resultSet.getColumnDefinitions()) {
- mapNameType
- .put(column.getName(), column.getType().getName().name());
- }
- ClassInformation classInformation = ClassInformations.INSTACE.getClass(class1);
- verifyRow(classInformation, session, mapNameType);
- }
-
- /**
- * verify relationship beteween Java and CQL type.
- * @param class1
- * @param session
- * @param mapNameType
- */
- private void verifyRow(ClassInformation classInformation, Session session,
- Map<String, String> mapNameType) {
-
- for (FieldInformation fieldInformation : classInformation.getFields()) {
-
- if (fieldInformation.isKeyCheck()) {
- continue;
- } else if (fieldInformation.isEmbedded() && !fieldInformation.isKeyCheck()) {
- verifyRow(fieldInformation.getSubFields(), session, mapNameType);
- continue;
- }
-
- String cqlType = mapNameType.get(fieldInformation.getName().toLowerCase());
- if (cqlType == null) {
- executeAlterTableAdd(classInformation, session, fieldInformation);
- continue;
- }
-
- VerifyRow verifyRow = VerifyRowUtil.INTANCE.factory(fieldInformation);
- List<String> cqlTypes = verifyRow.getTypes(fieldInformation.getField());
-
- if (!cqlTypes.contains(cqlType.toLowerCase())) {
- createMessageErro(classInformation, fieldInformation, cqlType);
- }
-
- }
- }
-
- /**
- * call the command to alter table adding a field.
- * @param class1
- * - bean within column family
- * @param session
- * - bridge to cassandra
- * @param field
- * - field to add in column family
- */
- private void executeAlterTableAdd(ClassInformation classInformation, Session session,
- FieldInformation field) {
- StringBuilder cqlAlterTable = new StringBuilder();
- cqlAlterTable.append("ALTER TABLE ").append(classInformation.getNameSchema());
- cqlAlterTable.append(" ADD ");
- AddColumn addColumn = AddColumnUtil.INSTANCE.factory(field);
- cqlAlterTable.append(addColumn.addRow(field, RelationShipJavaCassandra.INSTANCE));
- cqlAlterTable.deleteCharAt(cqlAlterTable.length() - 1);
- cqlAlterTable.append(";");
- session.execute(cqlAlterTable.toString());
- }
-
- /**
- * Field Java isn't equivalents with CQL type create error mensage.
- * @param classInformation
- * @param field
- * @param cqlTypes
- */
- private void createMessageErro(ClassInformation classInformation,
- FieldInformation field, String cqlType) {
- StringBuilder erroMensage = new StringBuilder();
- erroMensage.append("In the objetc ").append(classInformation.getClass().getName());
- erroMensage.append(" the field ").append(field.getName());
- erroMensage.append(" of the type ").append(field.getField().getType().getName());
- erroMensage.append(" isn't equivalent with CQL type ").append(cqlType);
- erroMensage.append(" was expected: ").append(
- RelationShipJavaCassandra.INSTANCE.getJavaValue(cqlType
- .toLowerCase()));
- throw new FieldJavaNotEquivalentCQLException(erroMensage.toString());
- }
-
- /**
- * Column family doen'snt exist create with this method.
- * @param familyColumn
- * - name of column family
- * @param class1
- * - bean
- * @param session
- * bridge of cassandra data base
- */
- private void createColumnFamily(String familyColumn, Class<?> class1,
- Session session) {
- StringBuilder cqlCreateTable = new StringBuilder();
- cqlCreateTable.append("create table ");
-
- cqlCreateTable.append(familyColumn).append("( ");
- ClassInformation classInformation = ClassInformations.INSTACE.getClass(class1);
- createQueryCreateTable(classInformation, cqlCreateTable);
- if (classInformation.isComplexKey()) {
- addComlexID(classInformation, cqlCreateTable);
- } else {
- addSimpleId(classInformation, cqlCreateTable);
- }
-
- session.execute(cqlCreateTable.toString());
- }
-
- /**
- * add in the query a simple id.
- * @param class1
- * @param cqlCreateTable
- */
- private void addSimpleId(ClassInformation classInformation, StringBuilder cqlCreateTable) {
- FieldInformation keyField = classInformation.getKeyInformation();
- if (keyField == null) {
- createErro(classInformation);
- }
- cqlCreateTable.append(QUERY_PRIMARY_KEY)
- .append(keyField.getName())
- .append(") );");
- }
-
-
- /**
- * add in the query a complex key.
- * @param classInformation
- * @param cqlCreateTable
- */
- private void addComlexID(ClassInformation classInformation, StringBuilder cqlCreateTable) {
-
- FieldInformation keyField = classInformation.getKeyInformation();
- cqlCreateTable.append(QUERY_PRIMARY_KEY);
- boolean firstTime = true;
- if (keyField == null) {
- createErro(classInformation);
- }
- for (FieldInformation subKey : keyField.getSubFields().getFields()) {
- if (firstTime) {
- cqlCreateTable.append(subKey.getName());
- firstTime = false;
- } else {
- cqlCreateTable.append(",").append(subKey.getName());
- }
- }
- cqlCreateTable.append(") );");
- }
-
- /**
- * @param bean
- */
- private void createErro(ClassInformation bean) {
-
- StringBuilder erroMensage = new StringBuilder();
-
- erroMensage.append("the bean ").append(bean.getNameSchema());
- erroMensage
- .append(" hasn't a field with id annotation, "
- + "you may to use either javax.persistence.Id");
- erroMensage.append(" to simple id or javax.persistence.EmbeddedId");
- erroMensage
- .append(" to complex id, another object with one "
- + "or more fields annotated with java.persistence.Column.");
- throw new KeyProblemsException(erroMensage.toString());
- }
-
- /**
- * create a query to create table and return if exist a complex id or not.
- * @param class1
- * @param cqlCreateTable
- * @param javaCassandra
- * @return
- */
- private void createQueryCreateTable(ClassInformation class1,
- StringBuilder cqlCreateTable) {
- for (FieldInformation field : class1.getFields()) {
- if (field.isEmbedded()) {
-
- createQueryCreateTable(field.getSubFields(), cqlCreateTable);
- continue;
- }
-
- AddColumn addColumn = AddColumnUtil.INSTANCE.factory(field);
- cqlCreateTable.append(addColumn.addRow(field,
- RelationShipJavaCassandra.INSTANCE));
- }
- }
-
- /**
- * Find if exists.
- * REMARK edited by : Dinusha Nandika;
- */
- private void findIndex(Class<?> familyColumn, Session session) {
- ClassInformation classInformation = ClassInformations.INSTACE.getClass(familyColumn);
- if (classInformation.getIndexFields().size() == 0) {
- return;
- }
- for (FieldInformation index : classInformation.getIndexFields()) {
- createIndex(classInformation, session, index);
- }
- }
-
- /**
- * method to create index.
- * @param familyColumn
- * @param session
- * @param index
- */
- private void createIndex(ClassInformation familyColumn, Session session,
- FieldInformation index) {
- StringBuilder createIndexQuery;
- createIndexQuery = new StringBuilder();
- createIndexQuery.append("CREATE INDEX ");
- createIndexQuery.append(index.getName()).append(" ON ");
- createIndexQuery.append(familyColumn.getNameSchema());
- createIndexQuery.append(" (").append(index.getName()).append(");");
- try {
- session.execute(createIndexQuery.toString());
- } catch (InvalidQueryException exception) {
- Logger.getLogger(FixColumnFamily.class.getName()).info("Index already exists");
- }
- }
-}
+/*
+ * Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.easycassandra.persistence.cassandra;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Logger;
+
+import org.easycassandra.ClassInformation;
+import org.easycassandra.ClassInformations;
+import org.easycassandra.FieldInformation;
+import org.easycassandra.FieldJavaNotEquivalentCQLException;
+import org.easycassandra.KeyProblemsException;
+import org.easycassandra.persistence.cassandra.AddColumnUtil.AddColumn;
+import org.easycassandra.persistence.cassandra.VerifyRowUtil.VerifyRow;
+
+import com.datastax.driver.core.ColumnDefinitions.Definition;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.exceptions.InvalidQueryException;
+import com.datastax.driver.core.querybuilder.QueryBuilder;
+import com.datastax.driver.core.querybuilder.Select;
+import java.util.Collections;
+import java.util.Comparator;
+import org.easycassandra.Order;
+
+/**
+ * Class to fix a column family.
+ * @author otaviojava
+ */
+class FixColumnFamily {
+
+ private static final String QUERY_PRIMARY_KEY = " PRIMARY KEY (";
+ private static final String CLUSTERING_ORDER = " WITH CLUSTERING ORDER BY (";
+
+ /**
+ * verify if exist column family and try to create.
+ * @param session - bridge to cassandra data base
+ * @param keySpace - the keyspace
+ * @param familyColumn - name of family column
+ * @param class1 - bean
+ * @return - if get it or not
+ */
+ public boolean verifyColumnFamily(Session session, String keySpace, String familyColumn,
+ Class<?> class1) {
+ try {
+ Select select = QueryBuilder.select().from(keySpace, familyColumn).limit(1);
+ ResultSet resultSet = session.execute(select);
+ verifyRowType(resultSet, class1, session);
+ findIndex(class1, session);
+ return true;
+ } catch (InvalidQueryException exception) {
+
+ if (exception.getCause().getMessage().contains("unconfigured columnfamily ")) {
+ Logger.getLogger(FixColumnFamily.class.getName()).info(
+ "Column family doesn't exist, try to create");
+ createColumnFamily(familyColumn, class1, session);
+ findIndex(class1, session);
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Column family exists verify.
+ * @param resultSet
+ */
+ private void verifyRowType(ResultSet resultSet, Class<?> class1, Session session) {
+ Map<String, String> mapNameType = new HashMap<String, String>();
+ for (Definition column : resultSet.getColumnDefinitions()) {
+ mapNameType
+ .put(column.getName(), column.getType().getName().name());
+ }
+ ClassInformation classInformation = ClassInformations.INSTACE.getClass(class1);
+ verifyRow(classInformation, session, mapNameType);
+ }
+
+ /**
+ * verify relationship beteween Java and CQL type.
+ * @param class1
+ * @param session
+ * @param mapNameType
+ */
+ private void verifyRow(ClassInformation classInformation, Session session,
+ Map<String, String> mapNameType) {
+
+ for (FieldInformation fieldInformation : classInformation.getFields()) {
+
+ if (fieldInformation.isKeyCheck()) {
+ continue;
+ } else if (fieldInformation.isEmbedded() && !fieldInformation.isKeyCheck()) {
+ verifyRow(fieldInformation.getSubFields(), session, mapNameType);
+ continue;
+ }
+
+ String cqlType = mapNameType.get(fieldInformation.getName().toLowerCase());
+ if (cqlType == null) {
+ executeAlterTableAdd(classInformation, session, fieldInformation);
+ continue;
+ }
+
+ VerifyRow verifyRow = VerifyRowUtil.INTANCE.factory(fieldInformation);
+ List<String> cqlTypes = verifyRow.getTypes(fieldInformation.getField());
+
+ if (!cqlTypes.contains(cqlType.toLowerCase())) {
+ createMessageErro(classInformation, fieldInformation, cqlType);
+ }
+
+ }
+ }
+
+ /**
+ * call the command to alter table adding a field.
+ * @param class1
+ * - bean within column family
+ * @param session
+ * - bridge to cassandra
+ * @param field
+ * - field to add in column family
+ */
+ private void executeAlterTableAdd(ClassInformation classInformation, Session session,
+ FieldInformation field) {
+ StringBuilder cqlAlterTable = new StringBuilder();
+ cqlAlterTable.append("ALTER TABLE ").append(classInformation.getNameSchema());
+ cqlAlterTable.append(" ADD ");
+ AddColumn addColumn = AddColumnUtil.INSTANCE.factory(field);
+ cqlAlterTable.append(addColumn.addRow(field, RelationShipJavaCassandra.INSTANCE));
+ cqlAlterTable.deleteCharAt(cqlAlterTable.length() - 1);
+ cqlAlterTable.append(";");
+ session.execute(cqlAlterTable.toString());
+ }
+
+ /**
+ * Field Java isn't equivalents with CQL type create error mensage.
+ * @param classInformation
+ * @param field
+ * @param cqlTypes
+ */
+ private void createMessageErro(ClassInformation classInformation,
+ FieldInformation field, String cqlType) {
+ StringBuilder erroMensage = new StringBuilder();
+ erroMensage.append("In the objetc ").append(classInformation.getClass().getName());
+ erroMensage.append(" the field ").append(field.getName());
+ erroMensage.append(" of the type ").append(field.getField().getType().getName());
+ erroMensage.append(" isn't equivalent with CQL type ").append(cqlType);
+ erroMensage.append(" was expected: ").append(
+ RelationShipJavaCassandra.INSTANCE.getJavaValue(cqlType
+ .toLowerCase()));
+ throw new FieldJavaNotEquivalentCQLException(erroMensage.toString());
+ }
+
+ /**
+ * Column family doen'snt exist create with this method.
+ * @param familyColumn
+ * - name of column family
+ * @param class1
+ * - bean
+ * @param session
+ * bridge of cassandra data base
+ */
+ private void createColumnFamily(String familyColumn, Class<?> class1,
+ Session session) {
+ StringBuilder cqlCreateTable = new StringBuilder();
+ cqlCreateTable.append("create table ");
+
+ cqlCreateTable.append(familyColumn).append("( ");
+ ClassInformation classInformation = ClassInformations.INSTACE.getClass(class1);
+ createQueryCreateTable(classInformation, cqlCreateTable);
+ if (classInformation.isComplexKey()) {
+ addComplexID(classInformation, cqlCreateTable);
+ addClusteringOrder(classInformation,cqlCreateTable);
+ } else {
+ addSimpleId(classInformation, cqlCreateTable);
+ }
+
+ cqlCreateTable.append(";");
+
+ session.execute(cqlCreateTable.toString());
+ }
+
+ /**
+ * add in the query a simple id.
+ * @param class1
+ * @param cqlCreateTable
+ */
+ private void addSimpleId(ClassInformation classInformation, StringBuilder cqlCreateTable) {
+ FieldInformation keyField = classInformation.getKeyInformation();
+ if (keyField == null) {
+ createErro(classInformation);
+ }
+ cqlCreateTable.append(QUERY_PRIMARY_KEY)
+ .append(keyField.getName())
+ .append(") )");
+ }
+
+
+ /**
+ * add in the query a complex key.
+ * @param classInformation
+ * @param cqlCreateTable
+ */
+ private void addComplexID(ClassInformation classInformation, StringBuilder cqlCreateTable) {
+
+ FieldInformation keyField = classInformation.getKeyInformation();
+ cqlCreateTable.append(QUERY_PRIMARY_KEY);
+ boolean firstTime = true;
+ boolean endPartkey = false;
+ boolean existsPatkey = false;
+ if (keyField == null) {
+ createErro(classInformation);
+ }
+
+ for (FieldInformation subKey : getSubkeysFieldsOrderedByPartkey(keyField)) {
+ if (firstTime) {
+ if (existsPatkey = subKey.isPartKeyCheck()) {
+ cqlCreateTable.append("(");
+ }
+ cqlCreateTable.append(subKey.getName());
+ firstTime = false;
+ } else {
+ if (existsPatkey && !endPartkey && !subKey.isPartKeyCheck()) {
+ endPartkey = true;
+ cqlCreateTable.append(")");
+ }
+ cqlCreateTable.append(",").append(subKey.getName());
+ }
+ }
+ if (existsPatkey && !endPartkey) {
+ cqlCreateTable.append(")");
+ }
+ cqlCreateTable.append(") )");
+
+ }
+
+ /**
+ * retrieve a ordered list of all complex key's subkeys.
+ *
+ * @param keyField
+ * @return A ordered list
+ */
+ private List<FieldInformation> getSubkeysFieldsOrderedByPartkey(FieldInformation keyField) {
+ List<FieldInformation> keyFields = keyField.getSubFields().getFields();
+ Collections.sort(keyFields, new Comparator<FieldInformation>() {
+
+ @Override
+ public int compare(FieldInformation o1, FieldInformation o2) {
+ return Boolean.compare(o2.isPartKeyCheck(), o1.isPartKeyCheck());
+ }
+ });
+ return keyFields;
+ }
+
+ private void addClusteringOrder(ClassInformation classInformation, StringBuilder cqlCreateTable) {
+
+ FieldInformation keyField = classInformation.getKeyInformation();
+ boolean firstTime = true;
+ for (FieldInformation subKey : keyField.getSubFields().getFields()) {
+ if (subKey.isClusteringOrderCheck() && !subKey.isPartKeyCheck()){
+ if (firstTime){
+ cqlCreateTable.append(CLUSTERING_ORDER);
+ cqlCreateTable.append(subKey.getName()).append(" ").append(getOrderString(subKey));
+ firstTime = false;
+ }else{
+ cqlCreateTable.append(",").append(subKey.getName()).append(" ").append(getOrderString(subKey));
+ }
+ }
+ }
+ if (!firstTime){
+ cqlCreateTable.append(")");
+ }
+
+ }
+
+ private static String getOrderString(FieldInformation subKey) {
+ return subKey.getOrder()==Order.DESC?"DESC":"ASC";
+ }
+
+
+ /**
+ * @param bean
+ */
+ private void createErro(ClassInformation bean) {
+
+ StringBuilder erroMensage = new StringBuilder();
+
+ erroMensage.append("the bean ").append(bean.getNameSchema());
+ erroMensage
+ .append(" hasn't a field with id annotation, "
+ + "you may to use either javax.persistence.Id");
+ erroMensage.append(" to simple id or javax.persistence.EmbeddedId");
+ erroMensage
+ .append(" to complex id, another object with one "
+ + "or more fields annotated with java.persistence.Column.");
+ throw new KeyProblemsException(erroMensage.toString());
+ }
+
+ /**
+ * create a query to create table and return if exist a complex id or not.
+ * @param class1
+ * @param cqlCreateTable
+ * @param javaCassandra
+ * @return
+ */
+ private void createQueryCreateTable(ClassInformation class1,
+ StringBuilder cqlCreateTable) {
+ for (FieldInformation field : class1.getFields()) {
+ if (field.isEmbedded()) {
+
+ createQueryCreateTable(field.getSubFields(), cqlCreateTable);
+ continue;
+ }
+
+ AddColumn addColumn = AddColumnUtil.INSTANCE.factory(field);
+ cqlCreateTable.append(addColumn.addRow(field,
+ RelationShipJavaCassandra.INSTANCE));
+ }
+ }
+
+ /**
+ * Find if exists.
+ * REMARK edited by : Dinusha Nandika;
+ */
+ private void findIndex(Class<?> familyColumn, Session session) {
+ ClassInformation classInformation = ClassInformations.INSTACE.getClass(familyColumn);
+ if (classInformation.getIndexFields().size() == 0) {
+ return;
+ }
+ for (FieldInformation index : classInformation.getIndexFields()) {
+ createIndex(classInformation, session, index);
+ }
+ }
+
+ /**
+ * method to create index.
+ * @param familyColumn
+ * @param session
+ * @param index
+ */
+ private void createIndex(ClassInformation familyColumn, Session session,
+ FieldInformation index) {
+ StringBuilder createIndexQuery;
+ createIndexQuery = new StringBuilder();
+ createIndexQuery.append("CREATE INDEX ");
+ createIndexQuery.append("i_").append(index.getName()).append(" ON ");
+ createIndexQuery.append(familyColumn.getNameSchema());
+ createIndexQuery.append(" (").append(index.getName()).append(");");
+ try {
+ session.execute(createIndexQuery.toString());
+ } catch (InvalidQueryException exception) {
+ Logger.getLogger(FixColumnFamily.class.getName()).info("Index already exists");
+ }
+ }
+}
340 src/main/java/org/easycassandra/persistence/cassandra/SelectBuilderImpl.java
View
@@ -1,170 +1,170 @@
-package org.easycassandra.persistence.cassandra;
-
-import java.util.List;
-
-import org.easycassandra.ClassInformation;
-import org.easycassandra.ClassInformation.KeySpaceInformation;
-
-import com.datastax.driver.core.ConsistencyLevel;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.ResultSetFuture;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.policies.RetryPolicy;
-import com.datastax.driver.core.querybuilder.QueryBuilder;
-import com.datastax.driver.core.querybuilder.Select;
-
-/**
- * select builder, it is easy way to make query with parameters.
- * @author otaviojava
- * @param <T> the kind of class
- */
-public class SelectBuilderImpl <T> implements SelectBuilder<T> {
-
- private Select select;
-
- private Session session;
-
- private ClassInformation classBean;
-
- /**
- * Constructor.
- * @param session the session
- * @param classBean the class
- * @param keySpace the keySpace
- */
- public SelectBuilderImpl(Session session, ClassInformation classBean,
- String keySpace) {
- this.session = session;
-
- this.classBean = classBean;
-
- KeySpaceInformation keySpaceInformation = classBean.getKeySpace(keySpace);
- select = QueryBuilder.select(CreateColumns.INSTANCE
- .getColumns(classBean).toArray(new String[0])).from(
- keySpaceInformation.getKeySpace(), keySpaceInformation.getColumnFamily());
- }
-
- @Override
- public SelectBuilder<T> eq(String name, Object value) {
- select.where(QueryBuilder.eq(classBean.toColumn(name), value));
- return this;
- }
-
- @Override
- public SelectBuilder<T> in(String name, Object... values) {
- select.where(QueryBuilder.in(classBean.toColumn(name), values));
- return this;
- }
-
- @Override
- public SelectBuilder<T> lt(String name, Object value) {
-
- select.where(QueryBuilder.lt(classBean.toColumn(name), value));
- return this;
- }
-
- @Override
- public SelectBuilder<T> lte(String name, Object value) {
- select.where(QueryBuilder.lte(classBean.toColumn(name), value));
- return this;
- }
-
- @Override
- public SelectBuilder<T> gt(String name, Object value) {
- select.where(QueryBuilder.gt(classBean.toColumn(name), value));
- return this;
- }
-
- @Override
- public SelectBuilder<T> gte(String name, Object value) {
- select.where(QueryBuilder.gte(classBean.toColumn(name), value));
- return this;
- }
-
- @Override
- public SelectBuilder<T> between(String name, Object startValue,
- Object endValue) {
- return lte(name, startValue).gt(name, endValue);
- }
-
- @Override
- public SelectBuilder<T> betweenInclusive(String name, Object startValue,
- Object endValue) {
- return lte(name, startValue).gte(name, endValue);
- }
-
- @Override
- public SelectBuilder<T> betweenExclusive(String name, Object startValue,
- Object endValue) {
- return lt(name, startValue).gt(name, endValue);
- }
-
- @Override
- public SelectBuilder<T> asc(String name) {
- select.orderBy(QueryBuilder.asc(classBean.toColumn(name)));
- return this;
- }
-
- @Override
- public SelectBuilder<T> desc(String name) {
- select.orderBy(QueryBuilder.desc(classBean.toColumn(name)));
- return this;
- }
-
- @Override
- public SelectBuilder<T> withConsistencyLevel(ConsistencyLevel consistency) {
- select.setConsistencyLevel(consistency);
- return this;
- }
-
- @Override
- public SelectBuilder<T> withTracing(boolean tracing) {
- if (tracing) {
- select.enableTracing();
- } else {
- select.disableTracing();
- }
- return this;
- }
- @Override
- public SelectBuilder<T> allowFiltering() {
- select.allowFiltering();
- return this;
- }
-
- @Override
- public SelectBuilder<T> withLimit(int limit) {
- select.limit(limit);
- return this;
- }
-
- @Override
- public SelectBuilder<T> withFetchSize(int fetchSize) {
- select.setFetchSize(fetchSize);
- return this;
- }
-
- @Override
- public SelectBuilder<T> withRetryPolicy(RetryPolicy policy) {
- select.setRetryPolicy(policy);
- return this;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<T> execute() {
- ResultSet resultSet = session.execute(select);
- return (List<T>) RecoveryObject.INTANCE.recoverObjet(classBean.getClassInstance(),
- resultSet);
- }
- @Override
- public void executeAsync(ResultAsyncCallBack<List<T>> callBack) {
- ResultSetFuture resultSet = session.executeAsync(select);
- AsyncResult.INSTANCE.runSelect(callBack, resultSet, classBean.getClassInstance());
- }
- @Override
- public String toString() {
- return select.toString();
- }
-
-}
+package org.easycassandra.persistence.cassandra;
+
+import java.util.List;
+
+import org.easycassandra.ClassInformation;
+import org.easycassandra.ClassInformation.KeySpaceInformation;
+
+import com.datastax.driver.core.ConsistencyLevel;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.ResultSetFuture;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.policies.RetryPolicy;
+import com.datastax.driver.core.querybuilder.QueryBuilder;
+import com.datastax.driver.core.querybuilder.Select;
+
+/**
+ * select builder, it is easy way to make query with parameters.
+ * @author otaviojava
+ * @param <T> the kind of class
+ */
+public class SelectBuilderImpl <T> implements SelectBuilder<T> {
+
+ private Select select;
+
+ private Session session;
+
+ private ClassInformation classBean;
+
+ /**
+ * Constructor.
+ * @param session the session
+ * @param classBean the class
+ * @param keySpace the keySpace
+ */
+ public SelectBuilderImpl(Session session, ClassInformation classBean,
+ String keySpace) {
+ this.session = session;
+
+ this.classBean = classBean;
+
+ KeySpaceInformation keySpaceInformation = classBean.getKeySpace(keySpace);
+ select = QueryBuilder.select(CreateColumns.INSTANCE
+ .getColumns(classBean).toArray(new String[0])).from(
+ keySpaceInformation.getKeySpace(), keySpaceInformation.getColumnFamily());
+ }
+
+ @Override
+ public SelectBuilder<T> eq(String name, Object value) {
+ select.where(QueryBuilder.eq(classBean.toColumn(name), value));
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> in(String name, Object... values) {
+ select.where(QueryBuilder.in(classBean.toColumn(name), values));
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> lt(String name, Object value) {
+
+ select.where(QueryBuilder.lt(classBean.toColumn(name), value));
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> lte(String name, Object value) {
+ select.where(QueryBuilder.lte(classBean.toColumn(name), value));
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> gt(String name, Object value) {
+ select.where(QueryBuilder.gt(classBean.toColumn(name), value));
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> gte(String name, Object value) {
+ select.where(QueryBuilder.gte(classBean.toColumn(name), value));
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> between(String name, Object startValue,
+ Object endValue) {
+ return gte(name, startValue).lt(name, endValue);
+ }
+
+ @Override
+ public SelectBuilder<T> betweenInclusive(String name, Object startValue,
+ Object endValue) {
+ return gte(name, startValue).lte(name, endValue);
+ }
+
+ @Override
+ public SelectBuilder<T> betweenExclusive(String name, Object startValue,
+ Object endValue) {
+ return gt(name, startValue).lt(name, endValue);
+ }
+
+ @Override
+ public SelectBuilder<T> asc(String name) {
+ select.orderBy(QueryBuilder.asc(classBean.toColumn(name)));
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> desc(String name) {
+ select.orderBy(QueryBuilder.desc(classBean.toColumn(name)));
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> withConsistencyLevel(ConsistencyLevel consistency) {
+ select.setConsistencyLevel(consistency);
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> withTracing(boolean tracing) {
+ if (tracing) {
+ select.enableTracing();
+ } else {
+ select.disableTracing();
+ }
+ return this;
+ }
+ @Override
+ public SelectBuilder<T> allowFiltering() {
+ select.allowFiltering();
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> withLimit(int limit) {
+ select.limit(limit);
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> withFetchSize(int fetchSize) {
+ select.setFetchSize(fetchSize);
+ return this;
+ }
+
+ @Override
+ public SelectBuilder<T> withRetryPolicy(RetryPolicy policy) {
+ select.setRetryPolicy(policy);
+ return this;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<T> execute() {
+ ResultSet resultSet = session.execute(select);
+ return (List<T>) RecoveryObject.INTANCE.recoverObjet(classBean.getClassInstance(),
+ resultSet);
+ }
+ @Override
+ public void executeAsync(ResultAsyncCallBack<List<T>> callBack) {
+ ResultSetFuture resultSet = session.executeAsync(select);
+ AsyncResult.INSTANCE.runSelect(callBack, resultSet, classBean.getClassInstance());
+ }
+ @Override
+ public String toString() {
+ return select.toString();
+ }
+
+}
Please sign in to comment.
Something went wrong with that request. Please try again.