/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ua.kpi.dao;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.hibernate.criterion.Expression.sql;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;
import ua.kpi.mvc.Javacore;
/**
*
* @author CodeFire
*/
@Component
public class DBController implements ApplicationContextAware {
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
public JdbcTemplate jdbcTempalte() {
initContext();
DriverManagerDataSource dataSource = context.getBean("dataSource", DriverManagerDataSource.class);
System.out.println("Data source is " + dataSource);
JdbcTemplate template = new JdbcTemplate(dataSource);
return template;
}
public ApplicationContext getContext() {
initContext();
return context;
}
public ApplicationContext getContext(String configFilename) {
return new ClassPathXmlApplicationContext(configFilename);
}
private void initContext() {
if (context == null) {
context = new ClassPathXmlApplicationContext();
}
}
public List<String> getDBInfo(JdbcTemplate template, String param) {
String sql = "select * from javacore";
List<String> l = null;
List<Javacore> list = template.queryForList(sql, Javacore.class);
for (Javacore jc : list) {
l.add(jc.getTopic());
}
return l;
}
public List<String> getDBInfo() throws SQLException {
DriverManagerDataSource dataSource = context.getBean("dataSource", DriverManagerDataSource.class);
List<String> data;
try (Connection connect = dataSource.getConnection()) {
DatabaseMetaData metaData = connect.getMetaData();
data = new ArrayList<>();
data.add(metaData.getDatabaseProductName());
data.add(metaData.getDatabaseProductVersion());
}
return data;
}
public List<String> getDBInfo(String param) throws SQLException {
DriverManagerDataSource dataSource = context.getBean("dataSource", DriverManagerDataSource.class);
List<String> list = null;
try (Connection connect = dataSource.getConnection()) {
Statement statement = connect.createStatement();
ResultSet result = statement.getResultSet();
while (result.next()) {
list.add(result.getString("topic"));
}
}
return list;
}
}