/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.test.mutlitenant.init;

import org.ow2.jonas.test.mutlitenant.Author;
import org.ow2.jonas.test.mutlitenant.reader.LocalReader;
import org.ow2.jonas.test.mutlitenant.writer.LocalWriter;

import javax.annotation.security.RunAs;
import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;

/**
 * The {@link InitializerBean} EJB is here to initialize only once
 * the Database/Entities. It simply checks if there is some {@link Author}s
 * already persisted; if none are found, we will inject defaults values.
 * @author Guillaume Sauthier
 */
@Stateless(mappedName="myInitializerBean")
@Remote(Initializer.class)
@RunAs("earsample")
public class InitializerBean implements Initializer {

    /**
     * Injected reference to the {@link org.ow2.jonas.test.mutlitenant.writer.Writer} EJB.
     */
    @EJB
    private LocalWriter writer;

    /**
     * Injected reference to the {@link org.ow2.jonas.test.mutlitenant.reader.Reader} EJB.
     */
    @EJB
    private LocalReader reader;

    /**
     * Initialize the minimal set of entities needed by the sample.
     * @see org.ow2.jonas.test.mutlitenant.init.Initializer#initializeEntities()
     */
    public void initializeEntities() {

        if (reader.findAuthor("Honore de Balzac") == null) {
            // Balzac was not persited, add it now.
            Author balzac = new Author("Honore de Balzac");
            // Persists the Author and all of his books
            writer.addAuthor(balzac);
        }

        if (reader.findAuthor("Victor Hugo") == null) {
            // Hugo was not persited, add it now.
            Author hugo = new Author("Victor Hugo");
            // Store
            writer.addAuthor(hugo);
        }
    }

}
