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.killbill.billing.plugin.dao.PluginDao.java
public PluginDao(final DataSource dataSource, final SQLDialect dialect) throws SQLException { this.dataSource = dataSource; this.dialect = dialect; final String schema; Connection connection = null; try {/*w w w . j a v a2 s . c o m*/ connection = dataSource.getConnection(); schema = connection.getCatalog(); } finally { if (connection != null) { connection.close(); } } this.settings = new Settings().withRenderMapping(new RenderMapping() .withSchemata(new MappedSchema().withInput(DEFAULT_SCHEMA_NAME).withOutput(schema))); }
From source file:azkaban.jobtype.ReportalTeradataRunner.java
@Override protected void runReportal() throws Exception { System.out.println("Reportal Teradata: Setting up Teradata"); List<Exception> exceptions = new ArrayList<Exception>(); Class.forName("com.teradata.jdbc.TeraDriver"); String connectionString = props.getString("reportal.teradata.connection.string", null); String user = props.getString("reportal.teradata.username", null); String pass = props.getString("reportal.teradata.password", null); if (user == null) { System.out.println("Reportal Teradata: Configuration incomplete"); throw new RuntimeException("The reportal.teradata.username variable was not defined."); }//from ww w . j av a 2 s . c o m if (pass == null) { System.out.println("Reportal Teradata: Configuration incomplete"); throw new RuntimeException("The reportal.teradata.password variable was not defined."); } DataSource teraDataSource = new TeradataDataSource(connectionString, user, pass); Connection conn = teraDataSource.getConnection(); String sqlQueries[] = cleanAndGetQueries(jobQuery, proxyUser); int numQueries = sqlQueries.length; for (int i = 0; i < numQueries; i++) { try { String queryLine = sqlQueries[i]; // Only store results from the last statement if (i == numQueries - 1) { PreparedStatement stmt = prepareStatement(conn, queryLine); stmt.execute(); ResultSet rs = stmt.getResultSet(); outputQueryResult(rs, outputStream); stmt.close(); } else { try { PreparedStatement stmt = prepareStatement(conn, queryLine); stmt.execute(); stmt.close(); } catch (NullPointerException e) { // An empty query (or comment) throws a NPE in JDBC. Yay! System.err.println( "Caught NPE in execute call because report has a NOOP query: " + queryLine); } } } catch (Exception e) { // Catch and continue. Delay exception throwing until we've run all queries in this task. System.out.println("Reportal Teradata: SQL query failed. " + e.getMessage()); e.printStackTrace(); exceptions.add(e); } } if (exceptions.size() > 0) { throw new CompositeException(exceptions); } System.out.println("Reportal Teradata: Ended successfully"); }
From source file:Controllers.AppointmentController.java
/** * * @param appointment/* www . j a v a2s .c o m*/ * @param result * @param modelMap * @return */ @RequestMapping(method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) public String AddApp(@ModelAttribute("appointment") Appointment appointment, BindingResult result, ModelMap modelMap) { int accountId = appointment.getAccountId(); int departmentId = appointment.getDepartmentId(); Date fulldate = appointment.getDate(); java.sql.Date date = new java.sql.Date(fulldate.getTime()); String message = appointment.getMessage(); String content = ""; if (departmentId == 0 || date == null) { content = "Sorry, you didn't fill some of fields. Please, try again."; modelMap.addAttribute("content", content); return "appointmentConfirmation"; } Date m = null; int appointmentcounter = 0; Appointment[] appointments = fetchAppointments(); for (int i = 0; i < appointments.length; i++) { if (appointments[i].getDate().compareTo(date) == 0 && appointments[i].getDepartmentId() == departmentId) appointmentcounter++; } if (appointmentcounter >= 2) { content = "Sorry, there is no any free spaces for your appointment on " + date + " to visit " + findDepartmentName(departmentId) + ". Please, select another day.<br>"; modelMap.addAttribute("content", content); return "appointmentConfirmation"; } try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource"); connection = ds.getConnection(); Statement stmt = connection.createStatement(); PreparedStatement pstmt; pstmt = connection.prepareStatement( "INSERT INTO appointments (accountId, departmentId, date, message)\n" + "VALUES (?,?,?,?);"); pstmt.setInt(1, accountId); pstmt.setInt(2, departmentId); pstmt.setDate(3, date); pstmt.setString(4, message); pstmt.execute(); content = "<h4>Appontment have been setted.</h4><br><h5>Please, check information below.</h5><br>" + "<table>" + "<tr><td>Seleted department:</td><td>" + findDepartmentName(departmentId) + "</td></tr>" + "<tr><td>Seleted date:</td><td>" + new SimpleDateFormat("yyyy-MM-dd").format(date) + "</td></tr>" + "<tr><td>Attached message</td><td>" + message + "</td></tr>" + "</table>"; stmt.close(); } catch (NamingException ex) { Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex); } modelMap.addAttribute("content", content); return "appointmentConfirmation"; }
From source file:fll.web.setup.CreateDB.java
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { String redirect;/*from w ww. ja v a 2 s.c o m*/ final StringBuilder message = new StringBuilder(); InitFilter.initDataSource(application); final DataSource datasource = ApplicationAttributes.getDataSource(application); Connection connection = null; try { connection = datasource.getConnection(); // must be first to ensure the form parameters are set UploadProcessor.processUpload(request); if (null != request.getAttribute("chooseDescription")) { final String description = (String) request.getAttribute("description"); try { final URL descriptionURL = new URL(description); final Document document = ChallengeParser .parse(new InputStreamReader(descriptionURL.openStream(), Utilities.DEFAULT_CHARSET)); GenerateDB.generateDB(document, connection); application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT); message.append("<p id='success'><i>Successfully initialized database</i></p>"); redirect = "/admin/createUsername.jsp"; } catch (final MalformedURLException e) { throw new FLLInternalException("Could not parse URL from choosen description: " + description, e); } } else if (null != request.getAttribute("reinitializeDatabase")) { // create a new empty database from an XML descriptor final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldocument"); if (null == xmlFileItem || xmlFileItem.getSize() < 1) { message.append("<p class='error'>XML description document not specified</p>"); redirect = "/setup"; } else { final Document document = ChallengeParser .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET)); GenerateDB.generateDB(document, connection); application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT); message.append("<p id='success'><i>Successfully initialized database</i></p>"); redirect = "/admin/createUsername.jsp"; } } else if (null != request.getAttribute("createdb")) { // import a database from a dump final FileItem dumpFileItem = (FileItem) request.getAttribute("dbdump"); if (null == dumpFileItem || dumpFileItem.getSize() < 1) { message.append("<p class='error'>Database dump not specified</p>"); redirect = "/setup"; } else { ImportDB.loadFromDumpIntoNewDB(new ZipInputStream(dumpFileItem.getInputStream()), connection); // remove application variables that depend on the database application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT); message.append("<p id='success'><i>Successfully initialized database from dump</i></p>"); redirect = "/admin/createUsername.jsp"; } } else { message.append( "<p class='error'>Unknown form state, expected form fields not seen: " + request + "</p>"); redirect = "/setup"; } } catch (final FileUploadException fue) { message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>"); LOG.error(fue, fue); redirect = "/setup"; } catch (final IOException ioe) { message.append("<p class='error'>Error reading challenge descriptor: " + ioe.getMessage() + "</p>"); LOG.error(ioe, ioe); redirect = "/setup"; } catch (final SQLException sqle) { message.append("<p class='error'>Error loading data into the database: " + sqle.getMessage() + "</p>"); LOG.error(sqle, sqle); redirect = "/setup"; } finally { SQLFunctions.close(connection); } session.setAttribute("message", message.toString()); response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + redirect)); }
From source file:com.yahoo.sql4d.indexeragent.sql.DBAccessor.java
@Override public Tuple2<DataSource, Connection> makeObject() throws Exception { DataSource ds = new DriverManagerDataSource(format(connectorUrl, host, port, db), id, password); return new Tuple2<>(ds, ds.getConnection()); }
From source file:com.sterlingcommerce.xpedx.webchannel.services.XPEDXGetAllReportsAction.java
public void getConnection() throws SQLException { String XCOM_MST_CUST = getCustomerNo(getWCContext().getBuyerOrgCode()); String DBUrl = YFSSystem.getProperty("datasource_url"); String DBName = YFSSystem.getProperty("datasource_name"); //String DBUrl= "t3://localhost:7002"; //String DBName= "SeptJNDI"; Connection connection = null; Statement stmt = null;/* ww w . j a va 2 s . c om*/ ResultSet rs = null; XPEDXReportBean rpBean = null; try { Hashtable ht = new Hashtable(); ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); ht.put("java.naming.provider.url", DBUrl); Context env = new InitialContext(ht); //InitialContext context = new InitialContext(ht); DataSource dataSource = (DataSource) env.lookup(DBName); connection = dataSource.getConnection(); if (log.isDebugEnabled()) { log.debug("Connection successful.."); } //String schemaName=YFSSystem.getProperty("schemaname"); //String Query="select distinct RPT_CUID, RPT_NAME,RPT_ID,RPT_KIND, RPT_DESC from " + schemaName + ".xpedx_custom_rpt_dtl where XCOM_MST_CUST=" + "'"+ XCOM_MST_CUST +"'"+"AND CUST_ROLE in ("; String Query = "select distinct RPT_CUID, RPT_NAME,RPT_ID,RPT_KIND, RPT_DESC from DH.xpedx_custom_rpt_dtl where XCOM_MST_CUST=" + "'" + XCOM_MST_CUST + "'" + "AND CUST_ROLE in ("; Query = getUserRole(Query); stmt = connection.createStatement(); boolean test = stmt.execute(Query); dataExchangeReportList = new ArrayList<Report>(); if (test == true) { rs = stmt.getResultSet(); while (rs.next()) { Report report = new Report(); report.setCuid(rs.getString("RPT_CUID")); report.setName(rs.getString("RPT_NAME")); report.setKind(rs.getString("RPT_KIND")); report.setId(rs.getInt("RPT_ID")); report.setDescription(rs.getString("RPT_DESC")); dataExchangeReportList.add(report); } } } catch (Exception e) { LOG.debug("Not able to connect to DEV Datasource:->" + e.getMessage()); } finally { stmt.close(); connection.close(); } }
From source file:com.sf.ddao.shards.ops.MultiShardSelectSqlOperation.java
@Override public boolean execute(Context context) throws Exception { ShardedConnectionHandler shardedConnectionHandler = CtxHelper.get(context, ShardedConnectionHandler.class); Map<DataSource, Collection<Object>> shardKeyListMap = shardedConnectionHandler.getShardKeyMapping(context); final MethodCallCtx callCtx = CtxHelper.get(context, MethodCallCtx.class); List<Object> resList = new ArrayList<Object>(shardKeyListMap.size()); for (Map.Entry<DataSource, Collection<Object>> entry : shardKeyListMap.entrySet()) { DataSource ds = entry.getKey(); Collection<Object> keys = entry.getValue(); //noinspection unchecked context.put(KEY_LIST_CONTEXT_VALUE, JoinListParameter.join(keys)); Connection oldConnection = ConnectionHandlerHelper.setConnection(context, ds.getConnection()); try {//from w w w.ja v a 2 s . c o m assert oldConnection == null; super.execute(context); resList.add(callCtx.getLastReturn()); } finally { ConnectionHandlerHelper.closeConnection(context); } } @SuppressWarnings({ "unchecked" }) Object res = resultMerger.reduce(resList); callCtx.setLastReturn(res); return CONTINUE_PROCESSING; }
From source file:fll.web.developer.QueryHandler.java
@SuppressFBWarnings(value = { "SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE" }, justification = "Executing query from user") @Override/*ww w .ja v a 2s .c o m*/ protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { final List<String> columnNames = new LinkedList<String>(); final List<Map<String, String>> data = new LinkedList<Map<String, String>>(); String error = null; DataSource datasource = ApplicationAttributes.getDataSource(application); Statement stmt = null; ResultSet rs = null; Connection connection = null; try { connection = datasource.getConnection(); final String query = request.getParameter(QUERY_PARAMETER); stmt = connection.createStatement(); rs = stmt.executeQuery(query); ResultSetMetaData meta = rs.getMetaData(); for (int columnNum = 1; columnNum <= meta.getColumnCount(); ++columnNum) { columnNames.add(meta.getColumnName(columnNum).toLowerCase()); } while (rs.next()) { final Map<String, String> row = new HashMap<String, String>(); for (final String columnName : columnNames) { final String value = rs.getString(columnName); row.put(columnName, value); } data.add(row); } } catch (final SQLException e) { error = e.getMessage(); LOGGER.error("Exception doing developer query", e); } finally { SQLFunctions.close(rs); SQLFunctions.close(stmt); SQLFunctions.close(connection); } response.setContentType("application/json"); response.setCharacterEncoding(Utilities.DEFAULT_CHARSET.name()); final ResultData result = new ResultData(columnNames, data, error); final ObjectMapper jsonMapper = new ObjectMapper(); final Writer writer = response.getWriter(); jsonMapper.writeValue(writer, result); }
From source file:binky.reportrunner.service.impl.DatasourceServiceImpl.java
@Override public String testDataSource(RunnerDataSource runnerDs) { try {/*from w w w . ja va2 s. c o m*/ //fix for issue 105 - when not editing password but just testing if (runnerDs.getPassword() == null || runnerDs.getPassword().trim().isEmpty()) { // see if ds already exists but we are hiding the password RunnerDataSource pwget = this.dataSourceDao.get(runnerDs.getDataSourceName()); if (pwget != null) { logger.debug("supplied password was blank - using stored password (if any)"); runnerDs.setPassword(pwget.getPassword()); } } else { EncryptionUtil enc = new EncryptionUtil(); runnerDs.setPassword(enc.encrpyt(this.secureKey, runnerDs.getPassword())); } DataSource ds = this.getDs(runnerDs); Connection conn = ds.getConnection(); DatabaseMetaData meta = conn.getMetaData(); String information = meta.getDatabaseProductName() + ", " + meta.getDatabaseProductVersion(); conn.close(); if (ds instanceof BasicDataSource) { ((BasicDataSource) ds).close(); } return information; } catch (Exception e) { if (e instanceof NullPointerException) { logger.fatal(e.getMessage(), e); } logger.debug(e.getMessage()); return "ERROR - " + e.getClass().getSimpleName() + ": " + e.getMessage(); } }
From source file:com.micromux.cassandra.jdbc.PooledTest.java
@Test public void twoMillionConnections() throws Exception { CassandraDataSource connectionPoolDataSource = new CassandraDataSource(HOST, PORT, KEYSPACE, USER, PASSWORD, VERSION, CONSISTENCY, TRUST_STORE, TRUST_PASS); DataSource pooledCassandraDataSource = new PooledCassandraDataSource(connectionPoolDataSource); for (int i = 0; i < 2000000; i++) { Connection connection = pooledCassandraDataSource.getConnection(); connection.close();/*from w w w. jav a 2 s . c om*/ } }