TestDataBean.java 9.84 KB
package fi.insomnia.bortal.beans;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.LoggerFactory;

import fi.insomnia.bortal.facade.BillFacade;
import fi.insomnia.bortal.facade.BillLineFacade;
import fi.insomnia.bortal.facade.CompoEntryFacade;
import fi.insomnia.bortal.facade.CompoFacade;
import fi.insomnia.bortal.facade.EventMapFacade;
import fi.insomnia.bortal.facade.EventOrganiserFacade;
import fi.insomnia.bortal.facade.PlaceFacade;
import fi.insomnia.bortal.facade.UserFacade;
import fi.insomnia.bortal.model.Bill;
import fi.insomnia.bortal.model.BillLine;
import fi.insomnia.bortal.model.Compo;
import fi.insomnia.bortal.model.CompoEntry;
import fi.insomnia.bortal.model.LanEvent;
import fi.insomnia.bortal.model.EventMap;
import fi.insomnia.bortal.model.Place;
import fi.insomnia.bortal.model.User;
import fi.insomnia.bortal.utilities.ThreadLocalContextHolder;
import fi.insomnia.bortal.utilities.apachecodec.binary.Base64;

/**
 * Session Bean implementation class TestDataBean
 */
@Stateless
// @DeclareRoles("ADMIN_BASE")
// @RolesAllowed("ADMIN_BASE")
public class TestDataBean implements TestDataBeanLocal {
    @PersistenceContext
    private EntityManager em;

    public static final String TEST_MAP_IMAGE_NAME = "testmap.png";
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TestDataBean.class);
    @EJB
    private EventMapFacade eventMapFacade;
    @EJB
    private EventBeanLocal eventBean;
    @EJB
    private UserFacade userFacade;
    @EJB
    private PlaceFacade placeFacade;
    @EJB
    private CompoFacade compoFacade;
    @EJB
    private CompoEntryFacade compoEntryFacade;
    @EJB
    private BillFacade billFacade;
    @EJB
    private BillLineFacade billLineFacade;
    @EJB
    private RoleBeanLocal role;
    @EJB
    private UserBeanLocal userbean;
   
    // @PersistenceUnit
    // private EntityManagerFactory emf;
    //

    public void bootstrap() {

    }

    public void writeMap( long bytes) {
        EventMap map = new EventMap(eventBean.getCurrentEvent());
        map.setName("test" + bytes);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes; ++i) {

            sb.append((char) (33 + i % 92));
        }
        map.setMapData(sb.toString());
        eventMapFacade.create(map);
    }

    public EventMap readMap(long bytes) {

        return eventMapFacade.findByName("test" + bytes);

    }

    /**
     * Default constructor.
     */
    public TestDataBean() {
        // TODO Auto-generated constructor stub
    }

    public User createUser() {

        User u = new User();
        u.setActive(true);
        u.setAddress("Pallokorvankatu 1");
        u.setNick("kavija");
        Calendar bday = Calendar.getInstance();
        bday.set(Calendar.YEAR, 1990);
        u.setBirthday(bday);
        u.setCreated(Calendar.getInstance());
        u.setEmail("kalle.kavija@example.com");
        u.setFirstnames("Kalle Kauko");
        u.setLastname("Kävija");
        u.setLogin("kavija");
        u.setNick("^Kkavija^]9a8/");
        u.resetPassword("kavija");
        u.setPhone("123-45679854");
        u.setTown("Keikyän MLK");
        u.setPostalTown("Keykyä");
        u.setZip("393929");
        userFacade.create(u);
        return u;
    }

    public User createAdmin() {

        User u = new User();

        u.setActive(true);
        u.setAddress("Elite 1337");
        u.setNick("admin");
        Calendar bday = Calendar.getInstance();
        bday.set(Calendar.YEAR, 1980);
        u.setBirthday(bday);
        u.setCreated(Calendar.getInstance());
        u.setEmail("admin@inter.net");
        u.setFirstnames("Asko Admin");
        u.setLastname("admin");
        u.setLogin("admin");
        u.setNick("admin");
        u.resetPassword("admin");
        u.setPhone("1337");
        u.setTown("Adminila");
        u.setPostalTown("Adminila ");
        u.setZip("6666");
        u.setSuperadmin(true);
        userFacade.create(u);

        return u;
    }

    public Bill createBill( User u) {
        Bill b = new Bill(eventBean.getCurrentEvent());
        b.setUser(u);
        b.setAddr1("Kalle Kävijä");
        b.setAddr2("co / Pelivieroitus Ry");
        b.setAddr3("Pallokorvankatu 1");
        b.setAddr4("696969 Keikyä");
        b.setAddr5("FINLAND! \\o/");
        b.setBillNumber(123123);
        b.setDelayIntrest(11);
        b.setDeliveryTerms("Toimitetaan, ehkä...");
        Calendar duedate = Calendar.getInstance();
        duedate.add(Calendar.DATE, 14);
        b.setDueDate(duedate);
        b.setNotes("Some notes...");
        b.setNoticetime("14 vrk");
        b.setOurReference("Meitin viite ( Insomnia XII )");
        b.setPaymentTime(14);
        b.setSentDate(Calendar.getInstance());
        b.setTheirReference("Niitten viite ( tyhjä? )");
        billFacade.create(b);
        createBillLine(b, "Tuote1", 1239.3, "kpl", 11.0, 0.22);
        createBillLine(b, "Tuote2", 0.3, "pss", 11.0, 0.22);
        createBillLine(b, "Tuote3", 9.3, "l", 11.0, 0.22);
        createBillLine(b, "Tuote4", 9, "kWh", 99931911.0, 0);
        createBillLine(b, "Tuote5", 33, "mol", 11.0, 0.22);
        createBillLine(b, "Tuote6", 39939.23123123, "rad", 122.0, 0.18);

        return b;
    }

    private BillLine createBillLine(Bill b, String line, double d, String qname, double e, double f) {
        return createBillLine(b, line, new BigDecimal(d), qname, new BigDecimal(e), new BigDecimal(f));

    }

    private BillLine createBillLine(Bill b, String line, BigDecimal q, String qname, BigDecimal price, BigDecimal vat) {
        BillLine bl = new BillLine(b);
        bl.setName(line);
        bl.setQuantity(q);
        bl.setUnitName(qname);
        bl.setUnitPrice(price);
        bl.setVat(vat);

        billLineFacade.create(bl);
        return bl;
    }

    public EventMap generateTestMap() {
        LanEvent event = eventBean.getCurrentEvent();
        try {
            logger.info("Generating Test Map for event: " + event);
            EventMap map = new EventMap(event);

            InputStream stream = getClass().getResourceAsStream(TEST_MAP_IMAGE_NAME);
            File file = new File(getClass().getResource(TEST_MAP_IMAGE_NAME).toURI());

            long length = file.length();
            // Create the byte array to hold the data
            byte[] bytes = new byte[(int) length];

            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                    && (numRead = stream.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }

            // Ensure all the bytes have been read in
            if (offset < bytes.length) {
                throw new IOException("Could not completely read file " + file.getName());
            }

            stream.close();
            String str = Base64.encodeBase64String(bytes);
            logger.debug("Saving image with {} base64 encoded chars", str.length());
            map.setMapData(str);
            map.setName("test0");
            eventMapFacade.create(map);

            return map;

        } catch (URISyntaxException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    /**
     * Generate all metashit, ex. events.
     */
    private User generateUser() {
        User user = new User();

        user.setNick("Nick");
        user.setPassword("plaah");

        userFacade.create(user);

        return user;
    }

    public void generateTestPlaces(EventMap map) {

        logger.info("Adding places to map {}, event {}", map);
        for (int x = 5; x < 400; x += 50) {
            for (int y = 5; y < 150; y += 50) {
                Place place = new Place(map);
                place.setMap(map);
                place.setMapX(x);
                place.setMapY(y);
                place.setWidth(50);
                place.setHeight(50);
                // map.getPlaces().add(place);
                placeFacade.create(place);
            }
        }
    }

    public void printPlacesInfo() {
        logger.debug("Fetching places");
        List<Place> places = placeFacade.findAll();
        logger.debug("Got places: {}", places);
        logger.info("Printing info from places");
        for (Place place : places) {
            logger.info("Place id: {}. Event Map id: {}.", place.getId().getId(), place.getMap().getId().getId());
        }
    }

    @Override
    public void generateTestCompos() {
        LanEvent event = eventBean.getCurrentEvent();
        Compo compo = new Compo(event);
        compo.setName("Test compo");
        compo.setHoldVoting(false);
        compoFacade.create(compo);

        CompoEntry compoEntry1 = new CompoEntry(event);
        compoEntry1.setCompo(compo);
        compoEntry1.setCreated(Calendar.getInstance());
        compoEntry1.setName("Test entry for test compo");
        compoEntryFacade.create(compoEntry1);

        CompoEntry compoEntry2 = new CompoEntry(event);
        compoEntry2.setCompo(compo);
        compoEntry2.setCreated(Calendar.getInstance());
        compoEntry2.setName("Another test entry for test compo");
        compoEntryFacade.create(compoEntry2);
    }

    @Override
    public void flushMaps() {
        Query q = em.createQuery("delete from EventMap");
        q.executeUpdate();
    }

    public void contextTest() {
        logger.debug("Hostname: {}",ThreadLocalContextHolder.get("HTTP_URL_HOSTNAME"));
      
    }
}