mitm.common.hibernate.CertificateArrayUserType.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.hibernate.CertificateArrayUserType.java

Source

/*
 * Copyright (c) 2008-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, 
 * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, 
 * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, 
 * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Eclipse Public License, 
 * tyrex license, freemarker license, dom4j license, mx4j license,
 * Spice Software License, Common Development and Distribution License
 * (CDDL), Common Public License (CPL) the licensors of this Program grant 
 * you additional permission to convey the resulting work.
 */
package mitm.common.hibernate;

import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.security.NoSuchProviderException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import mitm.common.security.SecurityFactoryFactory;
import mitm.common.security.SecurityFactoryFactoryException;

import org.apache.commons.lang.SerializationUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.type.Type;
import org.hibernate.usertype.CompositeUserType;

/**
 * Hibernate CompositeUserType that can be used to persist an array of 
 * {@link Certificate} (Certificate[])
 * 
 * @author Martijn Brinkers
 *
 */
public class CertificateArrayUserType implements CompositeUserType {
    private static final int CERTIFICATE_ARRAY_COLUMN = 0;

    /*
     * Subject and Issuer DN will be stored as CLOB because
     * there is no maximum size for a DN
     */
    private static final Type[] PROPERTY_TYPES = { Hibernate.BINARY, /* certificate array */
    };

    private static final String[] PROPERTY_NAMES = { "certificates", };

    @Override
    public Object assemble(Serializable cached, SessionImplementor session, Object owner)
            throws HibernateException {
        return deepCopy(cached);
    }

    private Certificate cloneCertificate(Certificate original)
            throws CertificateException, NoSuchProviderException, SecurityFactoryFactoryException {
        byte[] encodedCert = original.getEncoded();

        String certificateType = original.getType();

        CertificateFactory factory = SecurityFactoryFactory.getSecurityFactory()
                .createCertificateFactory(certificateType);

        Certificate copy = factory.generateCertificate(new ByteArrayInputStream(encodedCert));

        return copy;
    }

    @Override
    public Object deepCopy(Object value) throws HibernateException {
        if (value == null) {
            return null;
        }

        if (!(value instanceof Certificate[])) {
            throw new IllegalArgumentException("Object is not an array of Certificate.");
        }

        Certificate[] originals = (Certificate[]) value;

        Certificate[] copy = new Certificate[originals.length];

        try {
            for (int i = 0; i < originals.length; i++) {
                copy[i] = cloneCertificate(originals[i]);
            }
        } catch (CertificateException e) {
            throw new HibernateException(e);
        } catch (NoSuchProviderException e) {
            throw new HibernateException(e);
        }

        return copy;
    }

    @Override
    public Serializable disassemble(Object value, SessionImplementor session) throws HibernateException {
        return (Serializable) deepCopy(value);
    }

    @Override
    public boolean equals(Object o1, Object o2) throws HibernateException {
        return new EqualsBuilder().append(o1, o2).isEquals();
    }

    /* 
     * override hashCode because we override equals 
     */
    @Override
    public int hashCode(Object object) throws HibernateException {
        return new HashCodeBuilder().append(object).toHashCode();
    }

    @Override
    public String[] getPropertyNames() {
        return PROPERTY_NAMES;
    }

    @Override
    public Type[] getPropertyTypes() {
        return PROPERTY_TYPES;
    }

    private byte[] toBytes(Certificate[] certificates) throws CertificateEncodingException {
        /* 
         * we need to make encodedCerts a LinkedList and not a List because SerializationUtils.serialize 
         * requires the implementation to be serializable.
         */
        LinkedList<EncodedCertificate> encodedCerts = new LinkedList<EncodedCertificate>();

        for (Certificate certificate : certificates) {
            encodedCerts.add(new EncodedCertificate(certificate));
        }

        return SerializationUtils.serialize(encodedCerts);
    }

    @Override
    public Object getPropertyValue(Object component, int property) throws HibernateException {
        if (component == null) {
            return null;
        }

        if (!(component instanceof Certificate[])) {
            throw new IllegalArgumentException("Object is not an array of Certificate.");
        }

        Certificate[] certificates = (Certificate[]) component;

        try {
            switch (property) {
            case CERTIFICATE_ARRAY_COLUMN:
                return toBytes(certificates);
            }
        } catch (CertificateEncodingException e) {
            throw new HibernateException(e);
        }

        return null;
    }

    @Override
    public boolean isMutable() {
        /*  Certificate is immutable */
        return false;
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
            throws HibernateException, SQLException {
        Certificate[] certificates = null;

        byte[] bytes = rs.getBytes(names[CERTIFICATE_ARRAY_COLUMN]);

        if (!rs.wasNull() && bytes != null) {
            Object deserialized = SerializationUtils.deserialize(bytes);

            if (!(deserialized instanceof LinkedList)) {
                throw new IllegalArgumentException("Object is not a LinkedList.");
            }

            try {
                @SuppressWarnings("unchecked")
                List<EncodedCertificate> encodedCertificates = (LinkedList<EncodedCertificate>) deserialized;

                certificates = new Certificate[encodedCertificates.size()];

                for (int i = 0; i < certificates.length; i++) {
                    certificates[i] = encodedCertificates.get(i).getCertificate();
                }
            } catch (CertificateException e) {
                throw new HibernateException(e);
            } catch (NoSuchProviderException e) {
                throw new HibernateException(e);
            }
        }

        return certificates;
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
            throws HibernateException, SQLException {
        byte[] encoded = null;

        try {
            if (value != null) {
                if (!(value instanceof Certificate[])) {
                    throw new IllegalArgumentException("Object is not an array of Certificate.");
                }

                Certificate[] certificates = (Certificate[]) value;

                encoded = toBytes(certificates);
            }
        } catch (CertificateEncodingException e) {
            throw new HibernateException(e);
        }

        Hibernate.BINARY.nullSafeSet(st, encoded, index + CERTIFICATE_ARRAY_COLUMN);
    }

    @Override
    public Object replace(Object original, Object target, SessionImplementor session, Object owner)
            throws HibernateException {
        return original;
    }

    @Override
    public Class<?> returnedClass() {
        return Certificate[].class;
    }

    @Override
    public void setPropertyValue(Object comnponent, int property, Object value) throws HibernateException {
        /* Certificate[] is immutable */
    }
}