001/*
002 * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Dragos Mihalache
016 */
017package org.nuxeo.ecm.platform.uidgen;
018
019import javax.persistence.Column;
020import javax.persistence.Entity;
021import javax.persistence.GeneratedValue;
022import javax.persistence.GenerationType;
023import javax.persistence.Id;
024import javax.persistence.NamedQueries;
025import javax.persistence.NamedQuery;
026import javax.persistence.Table;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030
031/**
032 * UID entity - keeps last indexes of all generated UIDs.
033 */
034@Entity
035@NamedQueries({ @NamedQuery(name = "UIDSequence.findByKey", query = "from UIDSequenceBean seq where seq.key = :key") })
036@Table(name = "NXP_UIDSEQ")
037public class UIDSequenceBean {
038
039    public static final Log log = LogFactory.getLog(UIDSequenceBean.class);
040
041    @Id
042    @Column(name = "SEQ_ID", nullable = false)
043    @GeneratedValue(strategy = GenerationType.AUTO)
044    protected int id;
045
046    @Column(name = "SEQ_KEY", nullable = false, unique = true)
047    private String key;
048
049    @Column(name = "SEQ_INDEX", nullable = false)
050    private int index;
051
052    /**
053     * Default constructor needed for EJB container instantiation.
054     */
055    public UIDSequenceBean() {
056    }
057
058    /**
059     * Constructor taking as argument the key for which this sequence is created. The index is defaulted to 1.
060     *
061     * @param key
062     */
063    public UIDSequenceBean(String key) {
064        this.key = key;
065        index = 0;
066    }
067
068    public int getId() {
069        return id;
070    }
071
072    public void setId(int id) {
073        this.id = id;
074    }
075
076    public String getKey() {
077        return key;
078    }
079
080    public void setKey(String key) {
081        this.key = key;
082    }
083
084    public int getIndex() {
085        return index;
086    }
087
088    public static String stringify(UIDSequenceBean bean) {
089        return "UIDSeq(" + bean.key + "," + bean.index + ")";
090    }
091
092    @Override
093    public String toString() {
094        return stringify(this);
095    }
096
097    public int nextIndex() {
098        index += 1;
099        log.debug("updated to " + this);
100        return index;
101    }
102
103}