List of usage examples for javax.sql DataSource getConnection
Connection getConnection() throws SQLException;
Attempts to establish a connection with the data source that this DataSource object represents.
From source file:org.beangle.webapp.database.action.BrowserAction.java
private void loadObjects() throws Exception { QueryContext queryConext = getQueryContext(); DataSource datasource = queryConext.getDataSource(); DatasourceBean dsbean = queryConext.getDatasourceBean(); DatabaseMetaData meta = datasource.getConnection().getMetaData(); List<String> schemas = CollectUtils.newArrayList(); ResultSet rs = meta.getSchemas(); while (rs.next()) { schemas.add(rs.getString(1));/*from w w w . j ava2 s .co m*/ } // MetadataLoader loader = new MetadataLoader((Dialect) Class.forName(dsbean.getProvider().getDialect()) // .newInstance(), meta); Set<Table> tables = CollectUtils.newHashSet(); if (!schemas.isEmpty()) { String schema = get("schema"); if (StringUtils.isNotEmpty(schema)) { queryConext.setSchema(schema); } if (StringUtils.isEmpty(schema)) { schema = queryConext.getSchema(); if (StringUtils.isEmpty(schema)) { schema = schemas.get(0); } } put("schema", schema); // tables = loader.loadTables(null, schema, false); } put("schemas", schemas); put("tables", tables); }
From source file:id.go.kemdikbud.tandajasa.dao.PegawaiDaoTest.java
@Test public void testHapus() throws Exception { DataSource ds = ctx.getBean(DataSource.class); Connection koneksiDatabase = ds.getConnection(); PreparedStatement ps = koneksiDatabase.prepareStatement("select count(*) as jumlah from pegawai"); ResultSet rsSebelum = ps.executeQuery(); Assert.assertTrue(rsSebelum.next()); Long jumlahRecordSebelum = rsSebelum.getLong(1); rsSebelum.close();/*from w ww . j av a 2 s . c o m*/ PegawaiDao pd = (PegawaiDao) ctx.getBean("pegawaiDao"); Pegawai p = pd.cariById(100); Assert.assertNotNull(p); pd.delete(p); ResultSet rsSetelah = ps.executeQuery(); Assert.assertTrue(rsSetelah.next()); Long jumlahRecordSetelah = rsSetelah.getLong("jumlah"); rsSetelah.close(); koneksiDatabase.close(); Assert.assertEquals(new Long(jumlahRecordSebelum - 1), new Long(jumlahRecordSetelah)); }
From source file:de.iritgo.aktario.jdbc.UpdateObject.java
/** * Insert a new data object into the database. * * @param object The data object to create. *///from ww w .j ava 2 s .c o m private void update(DataObject object) { Connection connection = null; PreparedStatement stmt = null; try { JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager"); DataSource dataSource = jdbcManager.getDefaultDataSource(); connection = dataSource.getConnection(); StringBuffer sqlAssigns = new StringBuffer("id=?"); for (Iterator i = object.getAttributes().entrySet().iterator(); i.hasNext();) { Map.Entry attribute = (Map.Entry) i.next(); if (attribute.getValue() instanceof IObjectList) { continue; } sqlAssigns.append(", " + (String) attribute.getKey() + "=?"); } String sql = "update " + object.getTypeId() + " set " + sqlAssigns.toString() + " where id=" + object.getUniqueId(); stmt = connection.prepareStatement(sql); putAttributesToStatement(object, stmt); stmt.execute(); Log.logVerbose("persist", "JDBCManager", "UPDATE " + object.getTypeId() + ":" + object.getUniqueId() + " |" + sql + "|"); } catch (Exception x) { Log.logError("persist", "JDBCManager", "Error while creating new database record: " + x); } finally { DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(connection); } }
From source file:name.marcelomorales.siqisiqi.examples.simple.init.InitialData.java
@Inject public InitialData(DataSource dataSource) throws SQLException, IOException { jdbcTemplate = new JdbcTemplate(dataSource); try (Connection c = dataSource.getConnection()) { URL resource = Resources.getResource("ddl.sql"); String s = Resources.toString(resource, Charsets.US_ASCII); Iterable<String> split = Splitter.on(';').omitEmptyStrings().trimResults().split(s); for (String sql : split) { try (Statement st = c.createStatement()) { st.execute(sql);/*from ww w . j a v a2 s . c o m*/ } } c.commit(); // this is needed because we don't use @TransactionAttribute } }
From source file:fll.web.developer.ReplaceChallengeDescriptor.java
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Top of ReplaceChallengeDescriptor.doPost"); }//from w ww . j a v a 2 s. c o m final StringBuilder message = new StringBuilder(); Connection connection = null; try { final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); final Document curDoc = ApplicationAttributes.getChallengeDocument(application); // must be first to ensure the form parameters are set UploadProcessor.processUpload(request); // create a new empty database from an XML descriptor final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldoc"); final Document newDoc = ChallengeParser .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET)); final String compareMessage = ChallengeParser.compareStructure(curDoc, newDoc); if (null == compareMessage) { GenerateDB.insertOrUpdateChallengeDocument(newDoc, connection); application.setAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT, newDoc); message.append("<p><i>Successfully replaced challenge descriptor</i></p>"); } else { message.append("<p class='error'>"); message.append(compareMessage); message.append("</p>"); } } catch (final FileUploadException fue) { message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>"); LOGGER.error(fue, fue); } catch (final SQLException sqle) { message.append("<p class='error'>Error talking to the database: " + sqle.getMessage() + "</p>"); LOGGER.error(sqle, sqle); throw new RuntimeException("Error talking to the database", sqle); } finally { SQLFunctions.close(connection); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Top of ReplaceChallengeDescriptor.doPost"); } session.setAttribute("message", message.toString()); response.sendRedirect(response.encodeRedirectURL("index.jsp")); }
From source file:fll.web.report.PerformanceScoreDump.java
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { CSVWriter csv = null;/*from ww w .j av a 2 s . c o m*/ Connection connection = null; try { final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); final int tournamentID = Queries.getCurrentTournament(connection); response.reset(); response.setContentType("text/csv"); response.setHeader("Content-Disposition", "filename=performance_scores.csv"); csv = new CSVWriter(response.getWriter()); writeHeader(csv); writeData(connection, tournamentID, csv); } catch (final SQLException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(csv); SQLFunctions.close(connection); } }
From source file:com.jaspersoft.jasperserver.remote.connection.JndiConnectionStrategy.java
@Override public JndiConnection createConnection(JndiConnection connectionDescription, Map<String, Object> data) throws IllegalParameterValueException { Connection conn = null;//from ww w . ja v a 2s . c o m boolean passed = false; Throwable exception = null; try { Context ctx = new InitialContext(); DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/" + connectionDescription.getJndiName()); conn = dataSource.getConnection(); if (conn != null) { passed = true; } } catch (SQLException vex) { if (vex.getMessage().indexOf("[JI_CONNECTION_VALID]") >= 0) passed = true; exception = vex; } catch (Throwable e) { exception = e; } finally { if (conn != null) try { conn.close(); } catch (SQLException e) { log.error("Couldn't disconnect JNDI connection", e); } } if (!passed) { throw new ConnectionFailedException(connectionDescription.getJndiName(), "jndiName", "Invalid JNDI name: " + connectionDescription.getJndiName(), exception); } return connectionDescription; }
From source file:id.go.kemdikbud.tandajasa.dao.PegawaiDaoTest.java
@Test public void testInsert() throws Exception { Golongan g = new Golongan(); g.setId(99);// w w w. j a v a 2 s .co m Pegawai p = new Pegawai(); p.setNip("123"); p.setNama("Endy Muhardin"); p.setGolongan(g); DataSource ds = ctx.getBean(DataSource.class); Connection koneksiDatabase = ds.getConnection(); PreparedStatement ps = koneksiDatabase.prepareStatement("select count(*) as jumlah from pegawai"); ResultSet rsSebelum = ps.executeQuery(); Assert.assertTrue(rsSebelum.next()); Long jumlahRecordSebelum = rsSebelum.getLong(1); rsSebelum.close(); PegawaiDao pd = (PegawaiDao) ctx.getBean("pegawaiDao"); pd.save(p); ResultSet rsSetelah = ps.executeQuery(); Assert.assertTrue(rsSetelah.next()); Long jumlahRecordSetelah = rsSetelah.getLong("jumlah"); rsSetelah.close(); koneksiDatabase.close(); Assert.assertEquals(new Long(jumlahRecordSebelum + 1), new Long(jumlahRecordSetelah)); }
From source file:fll.web.api.CategoryScheduleMappingServlet.java
@Override protected final void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final ServletContext application = getServletContext(); final DataSource datasource = ApplicationAttributes.getDataSource(application); Connection connection = null; try {//w ww . j a v a 2 s . com connection = datasource.getConnection(); final ObjectMapper jsonMapper = new ObjectMapper(); response.reset(); response.setContentType("application/json"); final PrintWriter writer = response.getWriter(); final int currentTournament = Queries.getCurrentTournament(connection); final Collection<CategoryColumnMapping> mappings = CategoryColumnMapping.load(connection, currentTournament); jsonMapper.writeValue(writer, mappings); } catch (final SQLException e) { LOGGER.fatal("Database Exception", e); throw new RuntimeException(e); } finally { SQLFunctions.close(connection); } }
From source file:fll.web.api.ScheduleServlet.java
@Override protected final void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final ServletContext application = getServletContext(); final DataSource datasource = ApplicationAttributes.getDataSource(application); Connection connection = null; try {/* w ww . j a v a 2 s . c o m*/ connection = datasource.getConnection(); final ObjectMapper jsonMapper = new ObjectMapper(); response.reset(); response.setContentType("application/json"); final PrintWriter writer = response.getWriter(); final int currentTournament = Queries.getCurrentTournament(connection); if (TournamentSchedule.scheduleExistsInDatabase(connection, currentTournament)) { final TournamentSchedule schedule = new TournamentSchedule(connection, currentTournament); jsonMapper.writeValue(writer, schedule); } else { jsonMapper.writeValue(writer, ""); } } catch (final SQLException e) { throw new RuntimeException(e); } finally { SQLFunctions.close(connection); } }