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.trpr.dataaccess.orm.handler.HibernateHandler.java
/** * Equals method implementation. Checks if the database URLs of the underlying session factory match * @param persistenceHandler the PersistenceHandler to check for equals * @return true if the specified PersistenceHandler equals this one * @throws PersistenceException in case of SQL exceptions in accessing the handlers' properties *///from w w w .j a va 2s . c o m public boolean equals(PersistenceHandler persistenceHandler) throws PersistenceException { DataSource currentDatasource = SessionFactoryUtils.getDataSource(this.template.getSessionFactory()); DataSource otherDatasource = SessionFactoryUtils .getDataSource(((HibernateHandler) persistenceHandler).getTemplate().getSessionFactory()); try { return (currentDatasource.getConnection().getMetaData().getURL() .equalsIgnoreCase(otherDatasource.getConnection().getMetaData().getURL())); } catch (SQLException e) { throw new PersistenceException("Error evaluating PersistenceHandler#equals() : " + e.getMessage(), e); } }
From source file:net.trust.datacollection.thread.DataCollectionThread.java
public void run() { if (log.isDebugEnabled()) log.debug("" + interFetchConfigName + ""); //Spring//w w w .j a v a 2s .c o m ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext); DataSource dataSource = (DataSource) context.getBean("sqlServerDataSource"); //SqlServer baseSqlMapDAO = (BaseSqlMapDAO) context.getBean("baseSqlMapDAO"); //MySqlIbatis try { Connection conn = dataSource.getConnection(); Statement stem = conn.createStatement(); if (log.isDebugEnabled()) log.debug(interSelectSql); ResultSet rs = stem.executeQuery(interSelectSql); boolean localSelectFlag = false, localInsertFlag = false, localUpdateFlag = false; //MySqlSQL if (null != localSelectSql && !"".equals(localSelectSql)) { localSelectFlag = true; } //if //MySqlInsertSQL if (null != localInsertSql && !"".equals(localInsertSql)) { localInsertFlag = true; } //if //MySqlUpdateSQL if (null != localUpdateSql && !"".equals(localUpdateSql)) { localUpdateFlag = true; } //if if (localSelectFlag) { //select List selectField = createField(localSelectSql); if (localInsertFlag) { //insert List insertField = createField(localInsertSql); if (localUpdateFlag) { //update List updateField = createField(localUpdateSql); while (rs.next()) { if (findIsExistIbatisSql(localSelectSql, selectField, rs) == 0) {//insertupdate executeIbatisSql(localInsertSql, insertField, rs); //insert } else { executeIbatisSql(localUpdateSql, updateField, rs); //update } //if } } else { while (rs.next()) { if (findIsExistIbatisSql(localSelectSql, selectField, rs) > 0) {// executeIbatisSql(localInsertSql, insertField, rs); //insert } } } //if } else if (localUpdateFlag) { List updateField = createField(localUpdateSql); while (rs.next()) { executeIbatisSql(localUpdateSql, updateField, rs); //update } } //if } else { if (localInsertFlag) { //insert List insertField = createField(localInsertSql); while (rs.next()) { executeIbatisSql(localInsertSql, insertField, rs); //insert } } else if (localUpdateFlag) { List updateField = createField(localUpdateSql); while (rs.next()) { executeIbatisSql(localUpdateSql, updateField, rs); //update } } //if } //if if (log.isDebugEnabled()) log.debug("" + interFetchConfigName + ""); } catch (SQLException e) { e.printStackTrace(); } //try }
From source file:org.flywaydb.test.dbunit.DBUnitTestExecutionListener.java
/** * Get the dbunit specific database connection * * @param dataSource//from w ww . ja va2 s .c om * @return * @throws Exception */ protected IDatabaseConnection getConnection(final DataSource dataSource, final TestContext context) throws Exception { // get connection final Connection con = dataSource.getConnection(); final DatabaseMetaData databaseMetaData = con.getMetaData(); IDatabaseConnection connection = null; try { DatabaseConnectionFactory factory = context.getApplicationContext() .getBean(DatabaseConnectionFactory.class); if (factory != null) { dbConnectionFactory = factory; } } catch (Exception e) { logger.debug(String.format("We ignore if we could not find a instance of '%s'", DatabaseConnectionFactory.class.getName())); } if (dbConnectionFactory != null) { connection = dbConnectionFactory.createConnection(con, databaseMetaData); return connection; } // else { // //nnneee // DatabaseConnectionFactory factory = context.getApplicationContext().getBean(DatabaseConnectionFactory.class); // dbConnectionFactory = factory; // connection = dbConnectionFactory.createConnection(con, databaseMetaData); // return connection; // } return null; }
From source file:com.kylinolap.rest.service.QueryService.java
protected List<TableMeta> getMetadata(CubeManager cubeMgr, String project, boolean cubedOnly) throws SQLException { Connection conn = null;//from w w w . j a v a2 s . c o m ResultSet columnMeta = null; List<TableMeta> tableMetas = null; try { DataSource dataSource = getOLAPDataSource(project); conn = dataSource.getConnection(); DatabaseMetaData metaData = conn.getMetaData(); logger.debug("getting table metas"); ResultSet JDBCTableMeta = metaData.getTables(null, null, null, null); tableMetas = new LinkedList<TableMeta>(); Map<String, TableMeta> tableMap = new HashMap<String, TableMeta>(); while (JDBCTableMeta.next()) { String catalogName = JDBCTableMeta.getString(1); String schemaName = JDBCTableMeta.getString(2); // Not every JDBC data provider offers full 10 columns, for // example, // PostgreSQL has only 5 TableMeta tblMeta = new TableMeta(catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, JDBCTableMeta.getString(3), JDBCTableMeta.getString(4), JDBCTableMeta.getString(5), null, null, null, null, null); if (!cubedOnly || getProjectManager().isExposedTable(project, tblMeta.getTABLE_NAME())) { tableMetas.add(tblMeta); tableMap.put(tblMeta.getTABLE_SCHEM() + "#" + tblMeta.getTABLE_NAME(), tblMeta); } } logger.debug("getting column metas"); columnMeta = metaData.getColumns(null, null, null, null); while (columnMeta.next()) { String catalogName = columnMeta.getString(1); String schemaName = columnMeta.getString(2); // kylin(optiq) is not strictly following JDBC specification ColumnMeta colmnMeta = new ColumnMeta(catalogName == null ? Constant.FakeCatalogName : catalogName, schemaName == null ? Constant.FakeSchemaName : schemaName, columnMeta.getString(3), columnMeta.getString(4), columnMeta.getInt(5), columnMeta.getString(6), columnMeta.getInt(7), getInt(columnMeta.getString(8)), columnMeta.getInt(9), columnMeta.getInt(10), columnMeta.getInt(11), columnMeta.getString(12), columnMeta.getString(13), getInt(columnMeta.getString(14)), getInt(columnMeta.getString(15)), columnMeta.getInt(16), columnMeta.getInt(17), columnMeta.getString(18), columnMeta.getString(19), columnMeta.getString(20), columnMeta.getString(21), getShort(columnMeta.getString(22)), columnMeta.getString(23)); if (!cubedOnly || getProjectManager().isExposedColumn(project, colmnMeta.getTABLE_NAME(), colmnMeta.getCOLUMN_NAME())) { tableMap.get(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME()).addColumn(colmnMeta); } } logger.debug("done column metas"); } finally { close(columnMeta, null, conn); } return tableMetas; }
From source file:com.redhat.lightblue.rest.crud.ITCaseCrudResourceRDBMSTest.java
@Test public void testSelect() throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, URISyntaxException, JSONException { try {//from w w w . j av a2 s . c o m Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup("java:/mydatasource"); Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); stmt.execute( "CREATE TABLE Country ( name varchar(255), iso2code varchar(255), iso3code varchar(255) );"); stmt.execute("INSERT INTO Country (name,iso2code,iso3code) VALUES ('a','CA','c');"); stmt.close(); conn.close(); Assert.assertNotNull("CrudResource was not injected by the container", cutCrudResource); RestConfiguration.setDatasources(new DataSourcesConfiguration( JsonUtils.json(readConfigFile(RestConfiguration.DATASOURCE_FILENAME)))); RestConfiguration.setFactory(new LightblueFactory(RestConfiguration.getDatasources())); String expectedCreated = readFile("expectedCreated.json"); String metadata = readFile("metadata.json"); EntityMetadata em = RestConfiguration.getFactory().getJSONParser() .parseEntityMetadata(JsonUtils.json(metadata)); RestConfiguration.getFactory().getMetadata().createNewMetadata(em); EntityMetadata em2 = RestConfiguration.getFactory().getMetadata().getEntityMetadata("country", "1.0.0"); String resultCreated = RestConfiguration.getFactory().getJSONParser().convert(em2).toString(); JSONAssert.assertEquals(expectedCreated, resultCreated, false); String expectedFound = readFile("expectedFound.json"); String resultFound = cutCrudResource.find("country", "1.0.0", readFile("resultFound.json")).getEntity() .toString(); // TODO / NOTE we can change the result format if needed, now it return an array of arrays //System.err.println("!!!!!!!!!!!!!!!!!" + resultFound); JSONAssert.assertEquals(expectedFound, resultFound, false); } catch (NamingException | SQLException ex) { throw new IllegalStateException(ex); } mongo.dropDatabase(DB_NAME); }
From source file:com.redhat.lightblue.rest.crud.ITCaseCrudResourceRDBMSTest.java
@Test public void testSelectAll() throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, URISyntaxException, JSONException { try {//w ww. ja v a 2 s .co m Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup("java:/mydatasource"); Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); stmt.execute( "CREATE TABLE Country ( name varchar(255), iso2code varchar(255), iso3code varchar(255) );"); stmt.execute("INSERT INTO Country (name,iso2code,iso3code) VALUES ('a','CA','c');"); stmt.close(); conn.close(); Assert.assertNotNull("CrudResource was not injected by the container", cutCrudResource); RestConfiguration.setDatasources(new DataSourcesConfiguration( JsonUtils.json(readConfigFile(RestConfiguration.DATASOURCE_FILENAME)))); RestConfiguration.setFactory(new LightblueFactory(RestConfiguration.getDatasources())); String expectedCreated = readFile("expectedCreated.json"); String metadata = readFile("metadata.json"); EntityMetadata em = RestConfiguration.getFactory().getJSONParser() .parseEntityMetadata(JsonUtils.json(metadata)); RestConfiguration.getFactory().getMetadata().createNewMetadata(em); EntityMetadata em2 = RestConfiguration.getFactory().getMetadata().getEntityMetadata("country", "1.0.0"); String resultCreated = RestConfiguration.getFactory().getJSONParser().convert(em2).toString(); JSONAssert.assertEquals(expectedCreated, resultCreated, false); String expectedFound = readFile("expectedFoundAll.json"); String resultFound = cutCrudResource.find("country", "1.0.0", readFile("resultFoundAll.json")) .getEntity().toString(); // TODO / NOTE we can change the result format if needed, now it return an array of arrays //System.err.println("!!!!!!!!!!!!!!!!!" + resultFound); JSONAssert.assertEquals(expectedFound, resultFound, false); } catch (NamingException | SQLException ex) { throw new IllegalStateException(ex); } mongo.dropDatabase(DB_NAME); }
From source file:com.validation.manager.test.AbstractVMTestCase.java
@After @Override/* ww w . j a v a 2s .co m*/ protected void tearDown() throws Exception { LOG.info("Deleting database!"); deleteTestUsers(); Connection conn = null; Statement stmt = null; try { Map<String, Object> properties = DataBaseManager.getEntityManagerFactory().getProperties(); DataSource ds = new JdbcDataSource(); ((JdbcDataSource) ds).setPassword((String) properties.get("javax.persistence.jdbc.password")); ((JdbcDataSource) ds).setUser((String) properties.get("javax.persistence.jdbc.user")); ((JdbcDataSource) ds).setURL((String) properties.get("javax.persistence.jdbc.url")); //Load the H2 driver forName("org.h2.Driver"); conn = ds.getConnection(); stmt = conn.createStatement(); stmt.executeUpdate("DROP ALL OBJECTS DELETE FILES"); } catch (SQLException | ClassNotFoundException ex) { LOG.log(Level.SEVERE, null, ex); } finally { try { if (stmt != null) { stmt.close(); } } catch (SQLException ex) { fail(); } try { if (conn != null) { conn.close(); } } catch (SQLException ex) { fail(); } } DataBaseManager.close(); postTearDown(); LOG.info("Done!"); }
From source file:fll.web.GatherBugReport.java
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { final DataSource datasource = ApplicationAttributes.getDataSource(application); Connection connection = null; ZipOutputStream zipOut = null; final StringBuilder message = new StringBuilder(); try {/*from w ww . j ava 2s . com*/ if (null != SessionAttributes.getMessage(session)) { message.append(SessionAttributes.getMessage(session)); } connection = datasource.getConnection(); final Document challengeDocument = ApplicationAttributes.getChallengeDocument(application); final File fllWebInfDir = new File(application.getRealPath("/WEB-INF")); final String nowStr = new SimpleDateFormat("yyyy-MM-dd_HH-mm").format(new Date()); final File bugReportFile = File.createTempFile(nowStr, ".zip", fllWebInfDir); zipOut = new ZipOutputStream(new FileOutputStream(bugReportFile)); final String description = request.getParameter("bug_description"); if (null != description) { zipOut.putNextEntry(new ZipEntry("bug_description.txt")); zipOut.write(description.getBytes(Utilities.DEFAULT_CHARSET)); } zipOut.putNextEntry(new ZipEntry("server_info.txt")); zipOut.write(String.format( "Java version: %s%nJava vendor: %s%nOS Name: %s%nOS Arch: %s%nOS Version: %s%nServlet API: %d.%d%nServlet container: %s%n", System.getProperty("java.vendor"), // System.getProperty("java.version"), // System.getProperty("os.name"), // System.getProperty("os.arch"), // System.getProperty("os.version"), // application.getMajorVersion(), application.getMinorVersion(), // application.getServerInfo()).getBytes(Utilities.DEFAULT_CHARSET)); addDatabase(zipOut, connection, challengeDocument); addLogFiles(zipOut, application); message.append(String.format( "<i>Bug report saved to '%s', please notify the computer person in charge to look for bug report files.</i>", bugReportFile.getAbsolutePath())); session.setAttribute(SessionAttributes.MESSAGE, message); response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/")); } catch (final SQLException sqle) { throw new RuntimeException(sqle); } finally { SQLFunctions.close(connection); IOUtils.closeQuietly(zipOut); } }
From source file:it.lufraproini.cms.servlet.Upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w. j av a2 s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs * @throws org.apache.commons.fileupload.FileUploadException * @throws java.sql.SQLException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException, SQLException, Exception { /*verifica validit sessione*/ HttpSession s = SecurityLayer.checkSession(request); if (s != null) { /*DBMS*/ DataSource ds = (DataSource) getServletContext().getAttribute("datasource"); Connection connection = ds.getConnection(); /**/ CMSDataLayerImpl datalayer = new CMSDataLayerImpl(connection); String digest = ""; String html = ""; String tipo = ""; Map template_data = new HashMap(); Map info = new HashMap(); info = prendiInfo(request); //info = request.getParameterMap(); /*per prevedere l'upload di un nuovo tipo di file basta dare un valore personalizzato al submit nella form e creare un if con il flusso relativo all'oggetto da caricare nel file system e nel database*/ tipo = info.get("submit").toString(); try { //flusso immagine if (tipo.equals("immagine")) { Immagine img; Boolean thumbnail = false; html = "show_immagine.ftl.html"; digest = action_upload(request, info); img = memorizzaImmagine(info, datalayer, digest, (Long) s.getAttribute("userid")); img.setNome(SecurityLayer.stripSlashes(img.getNome()));//potrebbe causare eccezione su img null if (info.containsKey("thumbnail")) { thumbnail = creaThumbnail(img, s.getAttribute("username").toString()); } template_data.put("thumbnail", thumbnail.toString()); template_data.put("immagine", img); template_data.put("id", img.getId()); template_data.put("id_utente", 2); } //flusso css else if (tipo.equals("css")) { Css css = null; html = "show_css.ftl.html"; action_upload(request, info); css = memorizzaCss(info, datalayer); css.setDescrizione(SecurityLayer.stripSlashes(css.getDescrizione()));//potrebbe generare una nullpointerexception css.setNome(SecurityLayer.stripSlashes(css.getNome())); template_data.put("css", css); template_data.put("identifier", css.getId()); } //flusso slide else if (tipo.equals("slide")) { Slide img = null; html = "show_slide.ftl.html"; digest = action_upload(request, info); img = memorizzaSlide(info, datalayer, digest); /*visualizzazione della slide appena inserita*/ img.setDescrizione(SecurityLayer.stripSlashes(img.getDescrizione())); img.setNome(SecurityLayer.stripSlashes(img.getNome())); template_data.put("slide", img); template_data.put("id", img.getId()); } template_data.put("outline_tpl", ""); TemplateResult tr = new TemplateResult(getServletContext()); tr.activate(html, template_data, response); } catch (ErroreGrave ex) { Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); FailureResult res = new FailureResult(getServletContext()); res.activate(ex.getMessage(), request, response); } } else { response.sendRedirect("Homepage.html"); } }
From source file:com.redhat.lightblue.rest.crud.ITCaseCrudResourceRDBMSTest.java
@Test public void testDelete() throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, URISyntaxException, JSONException { try {// w ww . j a v a2 s . c om Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup("java:/mydatasource"); Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); stmt.execute( "CREATE TABLE Country ( name varchar(255), iso2code varchar(255), iso3code varchar(255) );"); stmt.execute("INSERT INTO Country (name,iso2code,iso3code) VALUES ('a','CA','c');"); stmt.close(); conn.close(); Assert.assertNotNull("CrudResource was not injected by the container", cutCrudResource); RestConfiguration.setDatasources(new DataSourcesConfiguration( JsonUtils.json(readConfigFile(RestConfiguration.DATASOURCE_FILENAME)))); RestConfiguration.setFactory(new LightblueFactory(RestConfiguration.getDatasources())); String expectedCreated = readFile("expectedCreated.json"); String metadata = readFile("metadata.json").replaceAll("YYZ", " DELETE FROM Country WHERE ISO2CODE=:ISO2CODE;"); EntityMetadata em = RestConfiguration.getFactory().getJSONParser() .parseEntityMetadata(JsonUtils.json(metadata)); RestConfiguration.getFactory().getMetadata().createNewMetadata(em); EntityMetadata em2 = RestConfiguration.getFactory().getMetadata().getEntityMetadata("country", "1.0.0"); String resultCreated = RestConfiguration.getFactory().getJSONParser().convert(em2).toString(); JSONAssert.assertEquals(expectedCreated, resultCreated, false); String expectedDeleted = readFile("expectedDeleted.json"); String resultDeleted = cutCrudResource.delete("country", "1.0.0", readFile("resultDeleted.json")) .getEntity().toString(); //System.err.println("!!!!!!!!!!!!!!!!!" + resultDeleted); ds = (DataSource) initCtx.lookup("java:/mydatasource"); conn = ds.getConnection(); stmt = conn.createStatement(); stmt.execute("SELECT * FROM Country;"); ResultSet resultSet = stmt.getResultSet(); Assert.assertEquals(false, resultSet.next()); JSONAssert.assertEquals(expectedDeleted, resultDeleted, false); } catch (NamingException | SQLException ex) { throw new IllegalStateException(ex); } mongo.dropDatabase(DB_NAME); }