Example usage for org.hibernate Session doReturningWork

List of usage examples for org.hibernate Session doReturningWork

Introduction

In this page you can find the example usage for org.hibernate Session doReturningWork.

Prototype

<T> T doReturningWork(ReturningWork<T> work) throws HibernateException;

Source Link

Document

Controller for allowing users to perform JDBC related work using the Connection managed by this Session.

Usage

From source file:br.com.casadasmarmitas.util.HibernateUtil.java

public static Connection getConnection() {
    Session sessao = fabricaSessoes.openSession();
    Connection conexao = sessao.doReturningWork(new ReturningWork<Connection>() {
        @Override/*from   w w  w . j  a v  a 2s  .c  om*/
        public Connection execute(Connection conn) throws SQLException {
            return conn;
        }
    });
    return conexao;
}

From source file:com.eclecticlogic.pedal.provider.hibernate.HibernateProviderAccessSpiImpl.java

License:Apache License

@Override
public <R> R exec(EntityManager entityManager, final Function<Connection, R> work) {
    Session session = entityManager.unwrap(Session.class);
    return session.doReturningWork(new ReturningWork<R>() {

        @Override/*from   w w w .  ja v a  2  s .com*/
        public R execute(Connection connection) throws SQLException {
            return work.apply(connection);
        }
    });
}

From source file:com.herval.gestaoefetivo.util.HibernateUtil.java

public static Connection getConexao() {
    Session sessao = sessionFactory.openSession();

    Connection conexao = sessao.doReturningWork(new ReturningWork<Connection>() {
        @Override//from   w w w . j  a  va 2  s . co m
        public Connection execute(Connection conn) throws SQLException {
            return conn;
        }
    });

    return conexao;
}

From source file:io.vertigo.database.plugins.sql.connection.hibernate.HibernateConnectionProviderPlugin.java

License:Apache License

/**
 * @param em EntityManager/*  w  ww .  ja v  a2 s  .c o m*/
 * @return the sqlConnection
 */
private SqlConnection obtainWrappedConnection(final EntityManager em) {
    //preconisation StackOverFlow to get current jpa connection
    final Session session = em.unwrap(Session.class);
    return session.doReturningWork(connection -> new SqlConnection(connection, getDataBase(), false));

}

From source file:io.vertigo.dynamo.plugins.database.connection.hibernate.HibernateConnectionProviderPlugin.java

License:Apache License

/**
 * @param em EntityManager// w  w w.  jav  a  2  s.c o m
 * @return the sqlConnection
 */
private SqlConnection obtainWrappedConnection(final EntityManager em) {
    //preconisation StackOverFlow to get current jpa connection
    final Session session = em.unwrap(Session.class);
    return session.doReturningWork(new ReturningWork<SqlConnection>() {
        @Override
        public SqlConnection execute(final Connection connection) throws SQLException {
            return new SqlConnection(connection, getDataBase(), false);
        }
    });
}

From source file:net.clanwolf.starmap.server.util.WebDataInterface.java

License:Apache License

public static void createSystemList(SystemListTypes type) {
    initialize();/*from   w  w w .  ja  v a2s  . c o m*/
    Log.print("Starting with the creation of the system list: " + type.name());

    EntityManager manager = EntityManagerHelper.getEntityManager();
    manager.getTransaction().begin();

    Session session = manager.unwrap(Session.class);
    ResultObject result = session.doReturningWork(new ReturningWork<ResultObject>() {
        @Override
        public ResultObject execute(Connection conn) throws SQLException {
            // execute your SQL
            ResultSet rs = null;
            ResultObject resultObject = new ResultObject();
            String systemsList = null;
            try (PreparedStatement stmt = conn.prepareStatement(selects.get(type.name()))) {
                rs = stmt.executeQuery();
                Log.print("Select done...");

                if (universe == null) {
                    universe = new UniverseDTO();
                }

                if (type == SystemListTypes.Factions) {
                    universe.factions.clear();
                    while (rs.next()) {
                        FactionDTO f = new FactionDTO();
                        f.setName(rs.getString("name"));
                        f.setShortName(rs.getString("short"));
                        f.setColor(rs.getString("color"));
                        f.setLogo(rs.getString("logo"));

                        universe.factions.put(f.getShortName(), f);
                    }
                    Log.print("Created universe classes (Factions)...");
                }

                if (type == SystemListTypes.HH_StarSystems) {
                    universe.starSystems.clear();
                    while (rs.next()) {
                        StarSystemDTO ss = new StarSystemDTO();
                        ss.setId(rs.getInt("sid"));
                        ss.setName(rs.getString("name"));
                        ss.setX(rs.getBigDecimal("x"));
                        ss.setY(rs.getBigDecimal("y"));
                        ss.setAffiliation(rs.getString("affiliation"));
                        ss.setStarType1(rs.getString("startype1"));
                        ss.setStarClass(rs.getString("class"));
                        ss.setSarnaLink(rs.getString("link"));
                        ss.setInfrastructure(rs.getString("infrastructure"));
                        ss.setWealth(rs.getString("wealth"));
                        ss.setVeternacy(rs.getString("veternacy"));
                        ss.setType(rs.getString("type"));

                        HashMap<String, String> maps = new HashMap<>();
                        maps.put("s1map1", rs.getString("s1map1"));
                        maps.put("s1map2", rs.getString("s1map2"));
                        maps.put("s1map3", rs.getString("s1map3"));
                        maps.put("s2map1", rs.getString("s2map1"));
                        maps.put("s2map2", rs.getString("s2map2"));
                        maps.put("s2map3", rs.getString("s2map3"));
                        maps.put("s3map1", rs.getString("s3map1"));
                        maps.put("s3map2", rs.getString("s3map2"));
                        maps.put("s3map3", rs.getString("s3map3"));
                        ss.setMaps(maps);

                        universe.starSystems.put(ss.getId(), ss);
                    }
                    Log.print("Created universe classes (StarSystems)...");
                }

                if (type == SystemListTypes.HH_Attacks) {
                    universe.attacks.clear();
                    while (rs.next()) {
                        AttackDTO a = new AttackDTO();
                        a.setId(rs.getInt("aid"));
                        a.setSeason(rs.getInt("season"));
                        a.setRound(rs.getInt("round"));
                        a.setPriority(rs.getInt("priority"));
                        a.setStarSystemId(rs.getInt("starsystem"));
                        a.setStarSystemDataId(rs.getInt("starsystemdata"));
                        a.setAttackedFromStarSystem(rs.getInt("attackedfromstarsystem"));
                        a.setAttackType(rs.getInt("attackType"));
                        a.setAttackerId(rs.getInt("attacker"));
                        a.setDefenderId(rs.getInt("defender"));

                        universe.attacks.add(a);
                    }
                    Log.print("Created universe classes (Attacks)...");
                }

                if (type == SystemListTypes.HH_Jumpships) {
                    universe.jumpships.clear();
                    while (rs.next()) {
                        JumpshipDTO js = new JumpshipDTO();
                        js.setShipID(rs.getInt("jsid"));
                        js.setShipName(rs.getString("jumpshipName"));
                        js.setShipID(rs.getInt("jumpshipFactionID"));
                        js.setStarSystemHistory(rs.getString("starHist"));
                        js.setLastMovedInRound(rs.getInt("lastMovedInRound"));
                        js.setCombatReady(rs.getBoolean("attackReady"));

                        universe.jumpships.put(js.getShipName(), js);
                    }
                    Log.print("Created universe classes (Jumpships)...");
                }
                universe.currentSeason = 1;
                universe.currentRound = 6;

                // create JSON representation
                rs.beforeFirst();
                systemsList = getJSONFromResultSet(rs, type.name(), true);
            } catch (Exception e) {
                Log.exception(WebDataInterface.class, e);
            }
            resultObject.setResultList(systemsList);
            return resultObject;
        }
    });

    File mapDataFile = null;
    File mapDataFileHH = null;
    File mapDataFileCM = null;

    String decodedPath = "";
    String systemsList = result.getResultList();
    String filename = "";
    String filenameHH = "";
    String filenameCM = "";

    try {
        String path = WebDataInterface.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String pathHH = "/var/www/vhosts/clanwolf.net/httpdocs/starmap_CM";
        String pathCM = "/var/www/vhosts/clanwolf.net/httpdocs/starmap_HH";

        decodedPath = URLDecoder.decode(path, "UTF-8");
        File f = new File(decodedPath);
        String parent = f.getParent();
        filename = parent + File.separator + "mapdata_" + type.name() + ".json";
        filenameHH = pathHH + File.separator + "mapdata_" + type.name() + ".json";
        filenameCM = pathCM + File.separator + "mapdata_" + type.name() + ".json";

        mapDataFile = new File(filename);
        mapDataFileHH = new File(filenameHH);
        mapDataFileCM = new File(filenameCM);

        Log.print("Wrote file: " + filename);
        Log.print("Wrote file: " + filenameHH);
        Log.print("Wrote file: " + filenameCM);
    } catch (UnsupportedEncodingException usee) {
        Log.exception(WebDataInterface.class, usee);
    }

    if (mapDataFile != null) {
        try (BufferedWriter br = new BufferedWriter(new FileWriter(mapDataFile))) {
            br.write(systemsList);
        } catch (IOException ioe) {
            Log.exception(WebDataInterface.class, ioe);
        }
    } else {
        RuntimeException rte = new RuntimeException("Could not write file: " + filename);
        Log.exception(WebDataInterface.class, rte);
        throw rte;
    }

    if (mapDataFileHH != null) {
        try (BufferedWriter br = new BufferedWriter(new FileWriter(mapDataFileHH))) {
            br.write(systemsList);
        } catch (IOException ioe) {
            Log.exception(WebDataInterface.class, ioe);
        }
    } else {
        RuntimeException rte = new RuntimeException("Could not write file: " + mapDataFileHH);
        Log.exception(WebDataInterface.class, rte);
        throw rte;
    }

    if (mapDataFileCM != null) {
        try (BufferedWriter br = new BufferedWriter(new FileWriter(mapDataFileCM))) {
            br.write(systemsList);
        } catch (IOException ioe) {
            Log.exception(WebDataInterface.class, ioe);
        }
    } else {
        RuntimeException rte = new RuntimeException("Could not write file: " + mapDataFileCM);
        Log.exception(WebDataInterface.class, rte);
        throw rte;
    }

    manager.getTransaction().commit();
    manager.close();
}

From source file:org.n52.sos.ds.hibernate.admin.HibernateGeneralQueryDAO.java

License:Open Source License

private QueryResult doWork(QueryWork work, String query) {
    Session s = null;
    try {/*ww  w .j a v  a 2  s.c  o m*/
        s = sessionHolder.getSession();
        return s.doReturningWork(work.setQuery(query));
    } catch (Exception ex) {
        return new ErrorResult(ex);
    } finally {
        sessionHolder.returnSession(s);
    }
}

From source file:org.n52.sos.ds.hibernate.admin.HibernateGeneralQueryDAO.java

License:Open Source License

private QueryResult doTransactionalWork(QueryWork work, String query) {
    Session s = null;
    try {/* w  ww  . j av  a 2s  .c  o m*/
        s = sessionHolder.getSession();
        Transaction t = s.beginTransaction();
        try {
            QueryResult result = s.doReturningWork(work.setQuery(query));
            t.commit();
            return result;
        } catch (HibernateException e) {
            t.rollback();
            throw e;
        }
    } catch (Exception ex) {
        return new ErrorResult(ex);
    } finally {
        sessionHolder.returnSession(s);
    }
}

From source file:ufsm.ctism.utils.JReportsUtils.java

/**
 * Mtodo para gerao do PDF do relatrio, a partir de um modelo e dos parmetros
 * @param report arquivo .jasper do relatrio
 * @param params mapa dos parmetros a serem passados para a construo do relatrio
 * @return o PDF gerado pelo jasper reports, ou null, caso tenha havido algum problema na gerao dele.
 * @throws IOException caso o parametro report nao seja encontrado
 *//*from   w w  w  .ja v  a 2  s.com*/
public File getPDF(InputStream report, Map<String, Object> params) throws IOException {
    File ret = File.createTempFile("report", ".pdf");

    org.hibernate.Session dbSession = HibernateUtils.getInstance().getStatefullSession();
    JasperPrint print;
    try {
        print = dbSession.doReturningWork(new ReturningWork<JasperPrint>() {
            @Override
            public JasperPrint execute(Connection connection) throws SQLException {
                try {
                    return JasperFillManager.fillReport(report, params, connection);
                } catch (JRException ex) {
                    return null;
                }
            }
        });
    } catch (HibernateException ex) {
        return null;
    }
    dbSession.close();
    String absPath = ret.getAbsolutePath();
    try {
        JasperExportManager.exportReportToPdfFile(print, absPath);
    } catch (JRException ex) {
        return null;
    }
    return ret;
}