All Downloads are FREE. Search and download functionalities are using the official Maven repository.

pep1.commons.jpa.util.RandomIntIdGenerator Maven / Gradle / Ivy

/*
 * Copyright (C) 2016 Leonard Osang
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 */

package pep1.commons.jpa.util;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
import org.springframework.util.NumberUtils;

import java.io.Serializable;
import java.util.Properties;

@Slf4j
public class RandomIntIdGenerator implements IdentifierGenerator, Configurable {

    public static final String LENGTH_CONFIG_KEY = "length";

    private static final Integer DEFAULT_LENGTH = 12;

    private Long min;
    private Long max;

    @Override
    public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
        Integer length = DEFAULT_LENGTH;
        try {
            Integer configuredLength = NumberUtils.parseNumber(properties.getProperty(LENGTH_CONFIG_KEY), Integer.class);
            length = (configuredLength != null) ? configuredLength : DEFAULT_LENGTH;
        } catch (NumberFormatException | NullPointerException e) {
            log.warn("Error while parsing configuration", e);
            // do nothing
        }

        min = NumberUtils.parseNumber("1" + new String(new char[length - 1]).replace('\0', '0'), Long.class);
        max = NumberUtils.parseNumber("9" + new String(new char[length - 1]).replace('\0', '0'), Long.class);

        if (log.isDebugEnabled()) {
            log.info("length: {}", length);
            log.info("min: {}", min);
            log.info("max: {}", max);
        }
    }

    @Override
    public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
        if (log.isDebugEnabled()) {
            log.debug("Invoking generate id method for object {}.", object);
        }

        return (long) Math.floor(Math.random() * max) + min;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy