ei.ne.ke.cassandra.cql3.SimpleEntitySpecification.java Source code

Java tutorial

Introduction

Here is the source code for ei.ne.ke.cassandra.cql3.SimpleEntitySpecification.java

Source

/*
 * Copyright 2013 EK3 Technologies, Inc.
 *
 * 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 ei.ne.ke.cassandra.cql3;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.Row;
import com.netflix.astyanax.model.Rows;

/**
 * Helper class for AstyanaxCql3Repository.
 * @param <T> the entity type
 * @param <ID> the key type
 * @see http://www.datastax.com/docs/1.2/cql_cli/cql_data_types
 * @see http://www.datastax.com/doc-source/developer/java-driver/reference/
 *      javaClass2Cql3Datatypes_r.html*
 */
public final class SimpleEntitySpecification<T, ID extends Serializable> implements EntitySpecification<T, ID> {

    static final Logger LOGGER = LoggerFactory.getLogger(SimpleEntitySpecification.class);

    private final Class<T> entityClazz;
    private final Class<ID> keyClazz;
    private final ColumnFamily<String, String> columnFamily;
    private final String table;
    private final Field keyField;
    private final String keyColumn;
    private final Map<String, AttributeAccessor> attributeAccessors;
    private final List<String> mappedColumns;

    /**
     * Constructor.
     * @param entityClazz .
     * @param keyClazz .
     */
    SimpleEntitySpecification(Class<T> entityClazz, Class<ID> keyClazz) {
        this.entityClazz = Preconditions.checkNotNull(entityClazz);
        this.keyClazz = Preconditions.checkNotNull(keyClazz);
        this.columnFamily = EntitySpecificationUtils.inferColumnFamily(this.entityClazz);
        this.table = this.columnFamily.getName();
        this.keyField = EntitySpecificationUtils.findPrimaryKeyField(this.entityClazz);
        this.keyColumn = EntitySpecificationUtils.getPrimaryKeyColumnName(this.keyField);
        this.attributeAccessors = EntitySpecificationUtils.createAccessors(this.entityClazz);
        this.mappedColumns = Lists.newArrayList(this.attributeAccessors.keySet());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ColumnFamily<String, String> getColumnFamily() {
        return columnFamily;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getTable() {
        return table;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<String> getKeyColumns() {
        return Arrays.asList(keyColumn);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<String> getMappedColumns() {
        return mappedColumns;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ID constructKey() {
        return BeanUtils.instantiateClass(keyClazz);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public T constructEntity() {
        return BeanUtils.instantiateClass(entityClazz);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public ID getKey(T entity) {
        try {
            return (ID) keyField.get(entity);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Couldn't access key field annotated", e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<ID> getKey(List<T> entities) {
        try {
            List<ID> keys = Lists.newArrayListWithExpectedSize(entities.size());
            for (T entity : entities) {
                keys.add((ID) keyField.get(entity));
            }
            return keys;
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Couldn't access key field annotated", e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, ByteBuffer> getSerializedKeyValues(ID key) {
        Preconditions.checkNotNull(key);
        Map<String, ByteBuffer> result = Maps.newLinkedHashMap();
        result.put(keyColumn, SerializerFactory.inferSerializer(keyClazz).toByteBuffer(key));
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Map<String, ByteBuffer> getSerializedKeyValues(T entity) {
        Preconditions.checkNotNull(entity);
        AttributeAccessor accessor = attributeAccessors.get(keyColumn);
        Map<String, ByteBuffer> result = Maps.newLinkedHashMap();
        result.put(keyColumn, EntitySpecificationUtils.serializeAttribute(accessor, entity));
        return result;
    }

    @Override
    public Map<String, ByteBuffer> serialize(T entity) {
        Preconditions.checkNotNull(entity);
        Map<String, ByteBuffer> result = Maps.newLinkedHashMap();
        for (Map.Entry<String, AttributeAccessor> entry : attributeAccessors.entrySet()) {
            result.put(entry.getKey(), EntitySpecificationUtils.serializeAttribute(entry.getValue(), entity));
        }
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public T map(ColumnList<String> columns) {
        T entity = BeanUtils.instantiateClass(entityClazz);
        for (Column<String> column : columns) {
            String normalizedColumnName = EntitySpecificationUtils.normalizeCqlElementName(column.getName());
            AttributeAccessor accessor = attributeAccessors.get(normalizedColumnName);
            if (accessor == null) {
                LOGGER.warn("The CQL3 column {} isn't mapped to any entity attribute.", normalizedColumnName);
                continue;
            }
            EntitySpecificationUtils.deserializeAttribute(column, accessor, entity);
        }
        return entity;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<T> map(Rows<String, String> rows) {
        List<T> entities = Lists.newArrayListWithExpectedSize(rows.size());
        for (Row<String, String> row : rows) {
            entities.add(map(row.getColumns()));
        }
        return entities;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<ByteBuffer> map(T entity) {
        List<ByteBuffer> serializedValues = Lists.newArrayListWithExpectedSize(attributeAccessors.size());
        for (Map.Entry<String, AttributeAccessor> entry : attributeAccessors.entrySet()) {
            AttributeAccessor accessor = entry.getValue();
            ByteBuffer buf = EntitySpecificationUtils.serializeAttribute(accessor, entity);
            serializedValues.add(buf);
        }
        return serializedValues;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<List<ByteBuffer>> map(List<T> entities) {
        List<List<ByteBuffer>> serializedEntities = Lists.newArrayListWithExpectedSize(entities.size());
        for (T entity : entities) {
            serializedEntities.add(map(entity));
        }
        return serializedEntities;
    }

}