Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager getTransaction.

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void pauseQueuedJob(int idJob) {
    jqmlogger.trace("Job status number " + idJob + " will be set to HOLDED");
    EntityManager em = null;

    try {/*from ww  w .java 2s. co  m*/
        em = getEm();
        em.getTransaction().begin();
        em.createQuery("UPDATE JobInstance j SET j.state = 'HOLDED' WHERE j.id = :idJob")
                .setParameter("idJob", idJob).executeUpdate();
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException("An attempt was made to pause a job instance that did not exist.");
    } catch (Exception e) {
        throw new JqmClientException("could not pause a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void resumeJob(int idJob) {
    jqmlogger.trace("Job status number " + idJob + " will be resumed");
    EntityManager em = null;

    try {//from   w w w  .ja v a2s  . c  o  m
        em = getEm();
        em.getTransaction().begin();
        em.createQuery("UPDATE JobInstance j SET j.state = 'SUBMITTED' WHERE j.id = :idJob")
                .setParameter("idJob", idJob).executeUpdate();
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException(
                "An attempt was made to resume a job instance that did not exist.");
    } catch (Exception e) {
        throw new JqmClientException("could not resume a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:net.echinopsii.ariane.community.plugin.rabbitmq.directory.RabbitmqDirectoryBootstrap.java

private void plugDirectoryJPAProvider() {
    Company pivotal = null;//from w ww .j  av  a  2s.com
    Application rabbitmq = null;

    directoryJpaProvider.addSubPersistenceBundle(FrameworkUtil.getBundle(RabbitmqDirectoryBootstrap.class));

    EntityManager em = directoryJpaProvider.createEM();
    CriteriaBuilder builder = em.getCriteriaBuilder();

    CriteriaQuery<Company> cmpCriteria = builder.createQuery(Company.class);
    Root<Company> cmpRoot = cmpCriteria.from(Company.class);
    cmpCriteria.select(cmpRoot).where(builder.equal(cmpRoot.<String>get("name"), "Pivotal"));
    TypedQuery<Company> cmpQuery = em.createQuery(cmpCriteria);
    try {
        pivotal = cmpQuery.getSingleResult();
        log.debug("Pivotal company already defined ...");
    } catch (NoResultException e) {
        log.debug("Pivotal company will be defined ...");
    } catch (Exception e) {
        throw e;
    }

    CriteriaQuery<Application> appCriteria = builder.createQuery(Application.class);
    Root<Application> appRoot = appCriteria.from(Application.class);
    appCriteria.select(appRoot).where(builder.equal(appRoot.<String>get("name"), "RabbitMQ"));
    TypedQuery<Application> appQuery = em.createQuery(appCriteria);
    try {
        rabbitmq = appQuery.getSingleResult();
        log.debug("RabbitMQ application already defined ...");
    } catch (NoResultException e) {
        log.debug("RabbitMQ application will be defined ...");
    } catch (Exception e) {
        throw e;
    }

    em.getTransaction().begin();

    if (pivotal == null) {
        pivotal = new Company().setNameR("Pivotal").setDescriptionR("Pivotal");
        em.persist(pivotal);
    }

    if (rabbitmq == null) {
        rabbitmq = new Application().setNameR("RabbitMQ").setCompanyR(pivotal).setShortNameR("RabbitMQ")
                .setColorCodeR("ff6600").setDescriptionR("Robust messaging for applications");
        em.persist(rabbitmq);
    }

    if (!pivotal.getApplications().contains(rabbitmq)) {
        pivotal.getApplications().add(rabbitmq);
    }

    em.flush();
    em.getTransaction().commit();
}

From source file:com.enioka.jqm.tools.JqmEngine.java

/**
 * Starts the engine// w w w .  j ava 2 s  . co m
 * 
 * @param nodeName
 *            the name of the node to start, as in the NODE table of the database.
 * @throws JqmInitError
 */
void start(String nodeName) {
    if (nodeName == null || nodeName.isEmpty()) {
        throw new IllegalArgumentException("nodeName cannot be null or empty");
    }

    // Set thread name - used in audits
    Thread.currentThread().setName("JQM engine;;" + nodeName);
    Helpers.setLogFileName(nodeName);

    // Log: we are starting...
    jqmlogger.info("JQM engine version " + this.getVersion() + " for node " + nodeName + " is starting");
    jqmlogger.info("Java version is " + System.getProperty("java.version") + ". JVM was made by "
            + System.getProperty("java.vendor") + " as " + System.getProperty("java.vm.name") + " version "
            + System.getProperty("java.vm.version"));

    // JNDI first - the engine itself uses JNDI to fetch its connections!
    Helpers.registerJndiIfNeeded();

    // Database connection
    EntityManager em = Helpers.getNewEm();

    // Node configuration is in the database
    node = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
            .getSingleResult();

    // Check if double-start
    long toWait = (long) (1.1 * Long.parseLong(Helpers.getParameter("internalPollingPeriodMs", "60000", em)));
    if (node.getLastSeenAlive() != null
            && Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis() <= toWait) {
        long r = Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis();
        throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " was running less than " + r / 1000
                + " seconds ago. Either stop the other node, or if it already stopped, please wait "
                + (toWait - r) / 1000 + " seconds");
    }

    // Prevent very quick multiple starts by immediately setting the keep-alive
    em.getTransaction().begin();
    node.setLastSeenAlive(Calendar.getInstance());
    em.getTransaction().commit();

    // Only start if the node configuration seems OK
    Helpers.checkConfiguration(nodeName, em);

    // Log parameters
    Helpers.dumpParameters(em, node);

    // Log level
    Helpers.setLogLevel(node.getRootLogLevel());

    // Log multicasting (& log4j stdout redirect)
    GlobalParameter gp1 = em
            .createQuery("SELECT g FROM GlobalParameter g WHERE g.key = :k", GlobalParameter.class)
            .setParameter("k", "logFilePerLaunch").getSingleResult();
    if ("true".equals(gp1.getValue()) || "both".equals(gp1.getValue())) {
        RollingFileAppender a = (RollingFileAppender) Logger.getRootLogger().getAppender("rollingfile");
        MultiplexPrintStream s = new MultiplexPrintStream(System.out, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setOut(s);
        ((ConsoleAppender) Logger.getRootLogger().getAppender("consoleAppender"))
                .setWriter(new OutputStreamWriter(s));
        s = new MultiplexPrintStream(System.err, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setErr(s);
    }

    // Remote JMX server
    if (node.getJmxRegistryPort() != null && node.getJmxServerPort() != null && node.getJmxRegistryPort() > 0
            && node.getJmxServerPort() > 0) {
        JmxAgent.registerAgent(node.getJmxRegistryPort(), node.getJmxServerPort(), node.getDns());
    } else {
        jqmlogger.info(
                "JMX remote listener will not be started as JMX registry port and JMX server port parameters are not both defined");
    }

    // Jetty
    this.server = new JettyServer();
    this.server.start(node, em);

    // JMX
    if (node.getJmxServerPort() != null && node.getJmxServerPort() > 0) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            name = new ObjectName("com.enioka.jqm:type=Node,name=" + this.node.getName());
            mbs.registerMBean(this, name);
        } catch (Exception e) {
            throw new JqmInitError("Could not create JMX beans", e);
        }
        jqmlogger.info("JMX management bean for the engine was registered");
    } else {
        loadJmxBeans = false;
        jqmlogger.info("JMX management beans will not be loaded as JMX server port is null or zero");
    }

    // Security
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManagerPayload());
    }
    jqmlogger.info("Security manager was registered");

    // Cleanup
    purgeDeadJobInstances(em, this.node);

    // Force Message EMF load
    em.createQuery("SELECT m FROM Message m WHERE 1=0", Message.class).getResultList();

    // Pollers
    syncPollers(em, this.node);
    jqmlogger.info("All required queues are now polled");

    // Internal poller (stop notifications, keepalive)
    intPoller = new InternalPoller(this);
    Thread t = new Thread(intPoller);
    t.start();

    // Kill notifications
    killHook = new SignalHandler(this);
    Runtime.getRuntime().addShutdownHook(killHook);

    // Done
    em.close();
    em = null;
    latestNodeStartedName = node.getName();
    jqmlogger.info("End of JQM engine initialization");
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void killJob(int idJob) {
    // First try to cancel the JI (works if it is not already running)
    try {/* w  ww  . j a  v  a 2  s.  co  m*/
        cancelJob(idJob);
        return;
    } catch (JqmClientException e) {
        // Nothing to do - this is thrown if already running. Just go on, this is a standard kill.
    }

    EntityManager em = null;
    try {
        em = getEm();
        em.getTransaction().begin();
        JobInstance j = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_READ);
        if (j == null) {
            throw new NoResultException("Job instance does not exist or has already finished");
        }
        jqmlogger.trace("The " + j.getState() + " job (ID: " + idJob + ")" + " will be marked for kill");

        j.setState(State.KILLED);

        Message m = new Message();
        m.setJi(idJob);
        m.setTextMessage("Kill attempt on the job");
        em.persist(m);
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException("An attempt was made to kill a job instance that did not exist.");
    } catch (Exception e) {
        throw new JqmClientException("Could not kill a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:op.allowance.PnlAllowance.java

private JPanel createContentPanel4(final Resident resident, LocalDate month) {
    final String key = getKey(resident, month);

    if (!contentmap.containsKey(key)) {

        JPanel pnlMonth = new JPanel(new VerticalLayout());

        pnlMonth.setBackground(getBG(resident, 11));
        pnlMonth.setOpaque(false);/*from  w w  w.j a  v  a2 s .com*/

        //            final String prevKey = resident.getRID() + "-" + SYSCalendar.eom(month.minusMonths(1)).getYear() + "-" + SYSCalendar.eom(month.minusMonths(1)).getMonthOfYear();
        if (!carrySums.containsKey(key)) {
            carrySums.put(key, AllowanceTools.getSUM(resident, SYSCalendar.eom(month.minusMonths(1))));
        }

        BigDecimal rowsum = carrySums.get(key);

        if (!cashmap.containsKey(key)) {
            cashmap.put(key, AllowanceTools.getMonth(resident, month.toDate()));
        }

        JLabel lblEOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMaximumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.endofmonth") + "</td>"
                + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        pnlMonth.add(lblEOM);

        for (final Allowance allowance : cashmap.get(key)) {

            String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                    + DateFormat.getDateInstance().format(allowance.getPit()) + "</td>"
                    + "<td width=\"400\" align=\"left\">" + allowance.getText() + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                    + cf.format(allowance.getAmount())
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>"
                    +

                    "</font></html>";

            DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                }
            });
            cptitle.getButton().setIcon(
                    allowance.isReplaced() || allowance.isReplacement() ? SYSConst.icon22eraser : null);

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
                /***
                 *      _____    _ _ _
                 *     | ____|__| (_) |_
                 *     |  _| / _` | | __|
                 *     | |__| (_| | | |_
                 *     |_____\__,_|_|\__|
                 *
                 */
                final JButton btnEdit = new JButton(SYSConst.icon22edit3);
                btnEdit.setPressedIcon(SYSConst.icon22edit3Pressed);
                btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnEdit.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnEdit.setContentAreaFilled(false);
                btnEdit.setBorder(null);
                btnEdit.setToolTipText(SYSTools.xx("admin.residents.cash.btnedit.tooltip"));
                btnEdit.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        final JidePopup popupTX = new JidePopup();
                        popupTX.setMovable(false);
                        PnlTX pnlTX = getPnlTX(resident, allowance);
                        popupTX.setContentPane(pnlTX);
                        popupTX.removeExcludedComponent(pnlTX);
                        popupTX.setDefaultFocusComponent(pnlTX);

                        popupTX.setOwner(btnEdit);
                        GUITools.showPopup(popupTX, SwingConstants.WEST);

                    }
                });
                cptitle.getRight().add(btnEdit);
                // you can edit your own entries or you are a manager. once they are replaced or a replacement record, its over.
                btnEdit.setEnabled((OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, internalClassID)
                        || allowance.getUser().equals(OPDE.getLogin().getUser())) && !allowance.isReplaced()
                        && !allowance.isReplacement());

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                final JButton btnUndoTX = new JButton(SYSConst.icon22undo);
                btnUndoTX.setPressedIcon(SYSConst.icon22Pressed);
                btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnUndoTX.setContentAreaFilled(false);
                btnUndoTX.setBorder(null);
                btnUndoTX.setToolTipText(SYSTools.xx("admin.residents.cash.btnundotx.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>" + "<br/><i>"
                                        + allowance.getText() + "&nbsp;" + cf.format(allowance.getAmount())
                                        + "</i><br/>" + SYSTools.xx("misc.questions.undo2"),
                                SYSConst.icon48undo, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();

                                                Allowance myOldAllowance = em.merge(allowance);
                                                Allowance myCancelAllowance = em
                                                        .merge(new Allowance(myOldAllowance));
                                                em.lock(em.merge(myOldAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myOldAllowance, LockModeType.OPTIMISTIC);
                                                myOldAllowance.setReplacedBy(myCancelAllowance,
                                                        em.merge(OPDE.getLogin().getUser()));

                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myCancelAllowance.getPit());

                                                final String keyMonth = myCancelAllowance.getResident().getRID()
                                                        + "-" + txDate.getYear() + "-"
                                                        + txDate.getMonthOfYear();
                                                contentmap.remove(keyMonth);
                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(allowance);
                                                cashmap.get(keyMonth).add(myOldAllowance);
                                                cashmap.get(keyMonth).add(myCancelAllowance);
                                                Collections.sort(cashmap.get(keyMonth));

                                                updateCarrySums(myCancelAllowance);

                                                createCP4(myCancelAllowance.getResident());

                                                try {
                                                    cpMap.get(keyMonth).setCollapsed(false);
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                buildPanel();

                                            } catch (OptimisticLockException ole) {
                                                OPDE.warn(ole);
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                if (ole.getMessage()
                                                        .indexOf("Class> entity.info.Resident") > -1) {
                                                    OPDE.getMainframe().emptyFrame();
                                                    OPDE.getMainframe().afterLogin();
                                                }
                                                OPDE.getDisplayManager()
                                                        .addSubMessage(DisplayManager.getLockMessage());
                                            } catch (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnUndoTX);
                btnUndoTX.setEnabled(!allowance.isReplaced() && !allowance.isReplacement());
            }

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) {
                /***
                 *      ____       _      _
                 *     |  _ \  ___| | ___| |_ ___
                 *     | | | |/ _ \ |/ _ \ __/ _ \
                 *     | |_| |  __/ |  __/ ||  __/
                 *     |____/ \___|_|\___|\__\___|
                 *
                 */
                final JButton btnDelete = new JButton(SYSConst.icon22delete);
                btnDelete.setPressedIcon(SYSConst.icon22deletePressed);
                btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnDelete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnDelete.setContentAreaFilled(false);
                btnDelete.setBorder(null);
                btnDelete.setToolTipText(SYSTools.xx("admin.residents.cash.btndelete.tooltip"));
                btnDelete.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.delete1") + "<br/><i>" + allowance.getText()
                                        + "&nbsp;" + cf.format(allowance.getAmount()) + "</i><br/>"
                                        + SYSTools.xx("misc.questions.delete2"),
                                SYSConst.icon48delete, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();
                                                Allowance myAllowance = em.merge(allowance);
                                                em.lock(em.merge(myAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);

                                                Allowance theOtherOne = null;
                                                // Check for special cases
                                                if (myAllowance.isReplacement()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacementFor());
                                                    theOtherOne.setReplacedBy(null);
                                                    theOtherOne.setEditedBy(null);
                                                    myAllowance.setEditPit(null);
                                                }
                                                if (myAllowance.isReplaced()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacedBy());
                                                    theOtherOne.setReplacementFor(null);
                                                }

                                                em.remove(myAllowance);
                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myAllowance.getPit());
                                                final String keyMonth = myAllowance.getResident().getRID() + "-"
                                                        + txDate.getYear() + "-" + txDate.getMonthOfYear();

                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(myAllowance);
                                                if (theOtherOne != null) {
                                                    cashmap.get(keyMonth).remove(theOtherOne);
                                                    cashmap.get(keyMonth).add(theOtherOne);
                                                    Collections.sort(cashmap.get(keyMonth));
                                                }

                                                // only to update the carrysums. myAllowance will be discarded soon.
                                                myAllowance.setAmount(myAllowance.getAmount().negate());
                                                updateCarrySums(myAllowance);

                                                createCP4(myAllowance.getResident());

                                                try {
                                                    if (cpMap.containsKey(keyMonth)) {
                                                        cpMap.get(keyMonth).setCollapsed(false);
                                                    }
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                buildPanel();
                                            } catch (OptimisticLockException ole) {
                                                OPDE.warn(ole);
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                if (ole.getMessage()
                                                        .indexOf("Class> entity.info.Resident") > -1) {
                                                    OPDE.getMainframe().emptyFrame();
                                                    OPDE.getMainframe().afterLogin();
                                                }
                                                OPDE.getDisplayManager()
                                                        .addSubMessage(DisplayManager.getLockMessage());
                                            } catch (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnDelete);
            }
            pnlMonth.add(cptitle.getMain());
            linemap.put(allowance, cptitle.getMain());

            rowsum = rowsum.subtract(allowance.getAmount());
        }

        JLabel lblBOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMinimumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.startofmonth")
                + "</td>" + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        lblBOM.setBackground(getBG(resident, 11));
        pnlMonth.add(lblBOM);
        contentmap.put(key, pnlMonth);
    }

    return contentmap.get(key);
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void cancelJob(int idJob) {
    EntityManager em = null;
    JobInstance ji = null;//from ww w .  j a v a  2 s .  com
    try {
        em = getEm();
        em.getTransaction().begin();
        ji = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_WRITE);
        if (ji.getState().equals(State.SUBMITTED)) {
            ji.setState(State.CANCELLED);
        } else {
            throw new NoResultException();
        }
        em.getTransaction().commit();
    } catch (NoResultException e) {
        closeQuietly(em);
        throw new JqmClientException(
                "the job is already running, has already finished or never existed to begin with");
    }

    try {
        em.getTransaction().begin();
        History h = new History();
        h.setId(ji.getId());
        h.setJd(ji.getJd());
        h.setApplicationName(ji.getJd().getApplicationName());
        h.setSessionId(ji.getSessionID());
        h.setQueue(ji.getQueue());
        h.setQueueName(ji.getQueue().getName());
        h.setEnqueueDate(ji.getCreationDate());
        h.setUserName(ji.getUserName());
        h.setEmail(ji.getEmail());
        h.setParentJobId(ji.getParentId());
        h.setApplication(ji.getApplication());
        h.setModule(ji.getModule());
        h.setKeyword1(ji.getKeyword1());
        h.setKeyword2(ji.getKeyword2());
        h.setKeyword3(ji.getKeyword3());
        h.setProgress(ji.getProgress());
        h.setStatus(State.CANCELLED);
        h.setNode(ji.getNode());
        if (ji.getNode() != null) {
            h.setNodeName(ji.getNode().getName());
        }
        em.persist(h);

        em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", ji.getId()).executeUpdate();
        em.getTransaction().commit();
    } catch (Exception e) {
        throw new JqmClientException("could not cancel job instance", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void setJobQueuePosition(int idJob, int position) {
    EntityManager em = null;
    JobInstance ji = null;// w  w  w .j a va2  s.  c o  m
    try {
        em = getEm();
        em.getTransaction().begin();
        ji = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_WRITE);
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmClientException(
                "Could not lock a job by the given ID. It may already have been executed or a timeout may have occurred.",
                e);
    }

    if (!ji.getState().equals(State.SUBMITTED)) {
        closeQuietly(em);
        throw new JqmInvalidRequestException(
                "Job is already set for execution. Too late to change its position in the queue");
    }

    try {
        int current = ji.getCurrentPosition(em);
        int betweenUp = 0;
        int betweenDown = 0;

        if (current == position) {
            // Nothing to do
            em.getTransaction().rollback();
            return;
        } else if (current < position) {
            betweenDown = position;
            betweenUp = position + 1;
        } else {
            betweenDown = position - 1;
            betweenUp = position;
        }

        // No locking - we'll deal with exceptions
        List<JobInstance> currentJobs = em
                .createQuery("SELECT ji from JobInstance ji ORDER BY ji.internalPosition", JobInstance.class)
                .setMaxResults(betweenUp).getResultList();

        if (currentJobs.isEmpty()) {
            ji.setInternalPosition(0);
        } else if (currentJobs.size() < betweenUp) {
            ji.setInternalPosition(currentJobs.get(currentJobs.size() - 1).getInternalPosition() + 0.00001);
        } else {
            // Normal case: put the JI between the two others.
            ji.setInternalPosition((currentJobs.get(betweenUp - 1).getInternalPosition()
                    + currentJobs.get(betweenDown - 1).getInternalPosition()) / 2);
        }
        em.getTransaction().commit();
    } catch (Exception e) {
        throw new JqmClientException("could not change the queue position of a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void deleteJob(int idJob) {
    jqmlogger.trace("Job status number " + idJob + " will be deleted");
    EntityManager em = null;

    try {//from ww w  .j ava  2  s .co  m
        em = getEm();

        // Two transactions against deadlock.
        JobInstance job = em.find(JobInstance.class, idJob);
        em.getTransaction().begin();
        em.refresh(job, LockModeType.PESSIMISTIC_WRITE);
        if (job.getState().equals(State.SUBMITTED)) {
            job.setState(State.CANCELLED);
        }
        em.getTransaction().commit();

        if (!job.getState().equals(State.CANCELLED)) {
            // Job is not in queue anymore - just return.
            return;
        }

        em.getTransaction().begin();
        em.createQuery("DELETE FROM Message WHERE ji = :i").setParameter("i", job.getId()).executeUpdate();
        em.createQuery("DELETE FROM RuntimeParameter WHERE ji = :i").setParameter("i", job.getId())
                .executeUpdate();
        em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", job.getId()).executeUpdate();
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException(
                "An attempt was made to delete a job instance that did not exist.");
    } catch (Exception e) {
        throw new JqmClientException("could not delete a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:nl.b3p.viewer.admin.monitoring.MonitorJob.java

public void execute(JobExecutionContext jec) throws JobExecutionException {

    try {/*from   w w w. java 2  s . c  o m*/
        Stripersist.requestInit();
        EntityManager em = Stripersist.getEntityManager();

        StringBuilder monitoringFailures = new StringBuilder();

        int online = 0, offline = 0;

        // TODO: where monitoringEnabled = true...
        for (GeoService gs : (List<GeoService>) em.createQuery("from GeoService").getResultList()) {

            String debugMsg = String.format("%s service %s (#%d) with URL: %s", gs.getProtocol(), gs.getName(),
                    gs.getId(), gs.getUrl());
            try {

                if (isInterrupted()) {
                    log.info("Interrupted, ending monitoring job");
                    return;
                }

                gs.checkOnline();
                online++;
                gs.setMonitoringStatusOK(true);
                log.debug("ONLINE: " + debugMsg);
            } catch (Exception e) {
                gs.setMonitoringStatusOK(false);
                offline++;
                log.debug("OFFLINE: " + debugMsg);
                if (log.isTraceEnabled()) {
                    log.trace("Exception", e);
                }
                String message = e.toString();
                Throwable cause = e.getCause();
                while (cause != null) {
                    message += "; " + cause.toString();
                    cause = cause.getCause();
                }
                monitoringFailures.append(String.format("%s service %s (#%d)\nURL: %s\nFout: %s\n\n",
                        gs.getProtocol(), gs.getName(), gs.getId(), gs.getUrl(), message));
            }
        }

        em.getTransaction().commit();

        log.info(String.format("Total services %d, online: %d, offline: %d, runtime: %d s", online + offline,
                online, offline, jec.getJobRunTime() / 1000));

        if (offline > 0) {

            Set emails = new HashSet();
            for (User admin : (List<User>) em.createQuery("select u from User u " + "join u.groups g "
                    + "where g.name = '" + Group.SERVICE_ADMIN + "' ").getResultList()) {
                emails.add(admin.getDetails().get(User.DETAIL_EMAIL));
            }
            emails.remove(null);

            if (!emails.isEmpty()) {
                StringBuilder mail = new StringBuilder();

                SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyy HH:mm:ss");
                mail.append(String.format(
                        "Bij een controle op %s zijn in het gegevensregister %d services gevonden waarbij fouten zijn geconstateerd.\n"
                                + "\nDe volgende controle zal worden uitgevoerd op %s.\nHieronder staat de lijst met probleemservices:\n\n",
                        f.format(jec.getFireTime()), offline, f.format(jec.getNextFireTime())));
                mail.append(monitoringFailures);

                mail(jec, emails, offline + " services zijn offline bij controle", mail.toString());
            }

        }
    } catch (Exception e) {
        log.error("Error", e);
    } finally {
        Stripersist.requestComplete();
    }

}