List of usage examples for java.sql Connection getMetaData
DatabaseMetaData getMetaData() throws SQLException;
DatabaseMetaData
object that contains metadata about the database to which this Connection
object represents a connection. From source file:org.apache.syncope.core.util.ImportExport.java
private List<String> sortByForeignKeys(final Connection conn, final Set<String> tableNames, final String schema) throws SQLException { Set<MultiParentNode<String>> roots = new HashSet<MultiParentNode<String>>(); final DatabaseMetaData meta = conn.getMetaData(); final Map<String, MultiParentNode<String>> exploited = new TreeMap<String, MultiParentNode<String>>( String.CASE_INSENSITIVE_ORDER); final Set<String> pkTableNames = new HashSet<String>(); for (String tableName : tableNames) { MultiParentNode<String> node = exploited.get(tableName); if (node == null) { node = new MultiParentNode<String>(tableName); roots.add(node);//w ww.j av a 2 s . co m exploited.put(tableName, node); } ResultSet rs = null; pkTableNames.clear(); try { rs = meta.getImportedKeys(conn.getCatalog(), readSchema(), tableName); // this is to avoid repetition while (rs.next()) { pkTableNames.add(rs.getString("PKTABLE_NAME")); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("While closing tables result set", e); } } } for (String pkTableName : pkTableNames) { if (!tableName.equalsIgnoreCase(pkTableName)) { MultiParentNode<String> pkNode = exploited.get(pkTableName); if (pkNode == null) { pkNode = new MultiParentNode<String>(pkTableName); roots.add(pkNode); exploited.put(pkTableName, pkNode); } pkNode.addChild(node); if (roots.contains(node)) { roots.remove(node); } } } } final List<String> sortedTableNames = new ArrayList<String>(tableNames.size()); MultiParentNodeOp.traverseTree(roots, sortedTableNames); Collections.reverse(sortedTableNames); return sortedTableNames; }
From source file:com.moss.schematrax.SchemaUpdater.java
private boolean tableExists(Connection sqlConnection, String schema, String tableName) throws SQLException { boolean tableExists = false; ResultSet tables = sqlConnection.getMetaData().getTables(null, schema, tableName, null); while (tables.next()) { String nextTableName = tables.getString("TABLE_NAME"); if (nextTableName != null && nextTableName.equals(tableName)) tableExists = true;/*from w w w . j a va2 s. c o m*/ } return tableExists; }
From source file:com.zg.action.admin.InstallAction.java
public String save() throws URISyntaxException, IOException, DocumentException { if (isInstalled()) { return ajaxJsonErrorMessage("SHOP++?????"); }/* w ww . j a va 2 s . com*/ if (StringUtils.isEmpty(databaseHost)) { return ajaxJsonErrorMessage("?!"); } if (StringUtils.isEmpty(databasePort)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(databasePassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseName)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminPassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(installStatus)) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "requiredCheckFinish"); return ajaxJson(jsonMap); } String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName + "?useUnicode=true&characterEncoding=UTF-8"; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // ? connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword); DatabaseMetaData databaseMetaData = connection.getMetaData(); String[] types = { "TABLE" }; resultSet = databaseMetaData.getTables(null, databaseName, "%", types); if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "databaseCheckFinish"); return ajaxJson(jsonMap); } // ? if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) { StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = null; String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SQL_INSTALL_FILE_NAME; bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8")); String line = ""; while (null != line) { line = bufferedReader.readLine(); stringBuffer.append(line); if (null != line && line.endsWith(";")) { System.out.println("[SHOP++?]SQL: " + line); preparedStatement = connection.prepareStatement(stringBuffer.toString()); preparedStatement.executeUpdate(); stringBuffer = new StringBuffer(); } } String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','" + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');"; String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');"; preparedStatement = connection.prepareStatement(insertAdminSql); preparedStatement.executeUpdate(); preparedStatement = connection.prepareStatement(insertAdminRoleSql); preparedStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); return ajaxJsonErrorMessage("???!"); } finally { try { if (resultSet != null) { resultSet.close(); resultSet = null; } if (preparedStatement != null) { preparedStatement.close(); preparedStatement = null; } if (connection != null) { connection.close(); connection = null; } } catch (SQLException e) { e.printStackTrace(); } } // ??? String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + JDBC_CONFIG_FILE_NAME; Properties properties = new Properties(); properties.put("jdbc.driver", "com.mysql.jdbc.Driver"); properties.put("jdbc.url", jdbcUrl); properties.put("jdbc.username", databaseUsername); properties.put("jdbc.password", databasePassword); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); properties.put("hibernate.show_sql", "false"); properties.put("hibernate.format_sql", "false"); OutputStream outputStream = new FileOutputStream(configFilePath); properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION); outputStream.close(); // ?? String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + BACKUP_WEB_CONFIG_FILE_NAME; String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String webConfigFilePath = new File( Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/" + WEB_CONFIG_FILE_NAME; String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("") .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME; String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath)); FileUtils.copyFile(new File(backupApplicationContextConfigFilePath), new File(applicationContextConfigFilePath)); FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath), new File(compassApplicationContextConfigFilePath)); FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath), new File(securityApplicationContextConfigFilePath)); // ?? //String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + SystemConfigUtils.CONFIG_FILE_NAME; File systemConfigFile = new File( ConfigurationManager.getConfigProperties(SystemConfigUtils.CONFIG_FILE_PATH_NAME)); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(systemConfigFile); Element rootElement = document.getRootElement(); Element systemConfigElement = rootElement.element("systemConfig"); Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled"); if (isInstalledNode == null) { isInstalledNode = systemConfigElement.addElement("isInstalled"); } isInstalledNode.setText("true"); try { OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML? outputFormat.setEncoding("UTF-8");// XML? outputFormat.setIndent(true);// ? outputFormat.setIndent(" ");// TAB? outputFormat.setNewlines(true);// ?? XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat); xmlWriter.write(document); xmlWriter.close(); } catch (Exception e) { e.printStackTrace(); } return ajaxJsonSuccessMessage("SHOP++?????"); }
From source file:com.faithbj.shop.action.admin.InstallAction.java
public String save() throws URISyntaxException, IOException, DocumentException { if (isInstalled()) { return ajaxJsonErrorMessage("CAIJINGLING?????"); }//from w w w . j a v a 2s.co m if (StringUtils.isEmpty(databaseHost)) { return ajaxJsonErrorMessage("?!"); } if (StringUtils.isEmpty(databasePort)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(databasePassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseName)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminPassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(installStatus)) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "requiredCheckFinish"); return ajaxJson(jsonMap); } String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName + "?useUnicode=true&characterEncoding=UTF-8"; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // ? connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword); DatabaseMetaData databaseMetaData = connection.getMetaData(); String[] types = { "TABLE" }; resultSet = databaseMetaData.getTables(null, databaseName, "%", types); if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "databaseCheckFinish"); return ajaxJson(jsonMap); } // ? if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) { StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = null; String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SQL_INSTALL_FILE_NAME; bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8")); String line = ""; while (null != line) { line = bufferedReader.readLine(); stringBuffer.append(line); if (null != line && line.endsWith(";")) { System.out.println("[CAIJINGLING?]SQL: " + line); preparedStatement = connection.prepareStatement(stringBuffer.toString()); preparedStatement.executeUpdate(); stringBuffer = new StringBuffer(); } } String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','" + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');"; String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');"; preparedStatement = connection.prepareStatement(insertAdminSql); preparedStatement.executeUpdate(); preparedStatement = connection.prepareStatement(insertAdminRoleSql); preparedStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); return ajaxJsonErrorMessage("???!"); } finally { try { if (resultSet != null) { resultSet.close(); resultSet = null; } if (preparedStatement != null) { preparedStatement.close(); preparedStatement = null; } if (connection != null) { connection.close(); connection = null; } } catch (SQLException e) { e.printStackTrace(); } } // ??? String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + JDBC_CONFIG_FILE_NAME; Properties properties = new Properties(); properties.put("jdbc.driver", "com.mysql.jdbc.Driver"); properties.put("jdbc.url", jdbcUrl); properties.put("jdbc.username", databaseUsername); properties.put("jdbc.password", databasePassword); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); properties.put("hibernate.show_sql", "false"); properties.put("hibernate.format_sql", "false"); OutputStream outputStream = new FileOutputStream(configFilePath); properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION); outputStream.close(); // ?? String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + BACKUP_WEB_CONFIG_FILE_NAME; String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String webConfigFilePath = new File( Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/" + WEB_CONFIG_FILE_NAME; String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("") .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME; String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath)); FileUtils.copyFile(new File(backupApplicationContextConfigFilePath), new File(applicationContextConfigFilePath)); FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath), new File(compassApplicationContextConfigFilePath)); FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath), new File(securityApplicationContextConfigFilePath)); // ?? String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SystemConfigUtil.CONFIG_FILE_NAME; File systemConfigFile = new File(systemConfigFilePath); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(systemConfigFile); Element rootElement = document.getRootElement(); Element systemConfigElement = rootElement.element("systemConfig"); Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled"); if (isInstalledNode == null) { isInstalledNode = systemConfigElement.addElement("isInstalled"); } isInstalledNode.setText("true"); try { OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML? outputFormat.setEncoding("UTF-8");// XML? outputFormat.setIndent(true);// ? outputFormat.setIndent(" ");// TAB? outputFormat.setNewlines(true);// ?? XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat); xmlWriter.write(document); xmlWriter.close(); } catch (Exception e) { e.printStackTrace(); } return ajaxJsonSuccessMessage("CAIJINGLING?????"); }
From source file:com.manydesigns.portofino.sync.DatabaseSyncer.java
public Database syncDatabase(final Model sourceModel) throws Exception { String databaseName = connectionProvider.getDatabase().getDatabaseName(); Database targetDatabase = new Database(); targetDatabase.setDatabaseName(databaseName); Connection conn = null; try {//from w ww . ja v a 2s . c o m logger.debug("Acquiring connection"); conn = connectionProvider.acquireConnection(); logger.debug("Reading database metadata"); DatabaseMetaData metadata = conn.getMetaData(); logger.debug("Creating Liquibase connection"); DatabaseConnection liquibaseConnection = new JdbcConnection(conn); logger.debug("Retrieving source database"); Database sourceDatabase = DatabaseLogic.findDatabaseByName(sourceModel, databaseName); if (sourceDatabase == null) { logger.debug("Source database not found. Creating an empty one."); sourceDatabase = new Database(); } logger.debug("Reading schema names from metadata"); List<Schema> schemas = connectionProvider.getDatabase().getSchemas(); DatabaseSnapshotGeneratorFactory dsgf = DatabaseSnapshotGeneratorFactory.getInstance(); logger.debug("Finding Liquibase database"); DatabaseFactory databaseFactory = DatabaseFactory.getInstance(); liquibase.database.Database liquibaseDatabase = databaseFactory .findCorrectDatabaseImplementation(liquibaseConnection); for (Schema schema : schemas) { logger.info("Processing schema: {}", schema.getSchemaName()); Schema sourceSchema = DatabaseLogic.findSchemaByNameIgnoreCase(sourceDatabase, schema.getSchemaName()); if (sourceSchema == null) { logger.debug("Source schema not found. Creating an empty one."); sourceSchema = new Schema(); sourceSchema.setSchemaName(schema.getSchemaName()); } logger.debug("Creating Liquibase database snapshot"); DatabaseSnapshot snapshot = dsgf.createSnapshot(liquibaseDatabase, schema.getSchemaName(), null); logger.debug("Synchronizing schema"); Schema targetSchema = new Schema(); targetSchema.setDatabase(targetDatabase); targetDatabase.getSchemas().add(targetSchema); syncSchema(snapshot, sourceSchema, targetSchema); } } finally { connectionProvider.releaseConnection(conn); } targetDatabase.setConnectionProvider(connectionProvider); connectionProvider.setDatabase(targetDatabase); return targetDatabase; }
From source file:com.thinkbiganalytics.schema.DBSchemaParser.java
/** * Lists the tables in the specified schema that match the specified table pattern.d * * @param conn the JDBC connection//from w ww . j a v a 2 s. c om * @param catalog the catalog name pattern, or {@code null} * @param schema the schema name pattern, or {@code null} * @param tableName the table name pattern @return a result set containing the matching table metadata * @return the list of tables or {@code null} if there was a problem */ @Nullable private ResultSet getTables(@Nonnull final Connection conn, @Nullable String catalog, @Nullable final String schema, @Nonnull final String tableName) { try { DatabaseType databaseType = null; try { databaseType = DatabaseType.fromMetaData(conn); } catch (MetaDataAccessException e) { //if can't get the db type, then treat it as normal looking for TABLE and VIEW } if (DatabaseType.TERADATA.equals(databaseType)) { return conn.getMetaData().getTables(catalog, schema, tableName, null); //Teradata-specific } else { return conn.getMetaData().getTables(catalog, schema, tableName, new String[] { "TABLE", "VIEW" }); } } catch (final SQLException e) { log.debug("Failed to list tables for catalog:{} schema:{} tableName:{}", catalog, schema, tableName, e); return null; } }
From source file:net.shopxx.action.admin.InstallAction.java
public String save() throws URISyntaxException, IOException, DocumentException { if (isInstalled()) { return ajaxJsonErrorMessage("SHOP++?????"); }/*from ww w . j av a2 s. c o m*/ if (StringUtils.isEmpty(databaseHost)) { return ajaxJsonErrorMessage("?!"); } if (StringUtils.isEmpty(databasePort)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(databasePassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseName)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminPassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(installStatus)) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "requiredCheckFinish"); return ajaxJson(jsonMap); } String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName + "?useUnicode=true&characterEncoding=UTF-8"; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // ? connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword); DatabaseMetaData databaseMetaData = connection.getMetaData(); String[] types = { "TABLE" }; resultSet = databaseMetaData.getTables(null, databaseName, "%", types); if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "databaseCheckFinish"); return ajaxJson(jsonMap); } // ? if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) { StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = null; String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SQL_INSTALL_FILE_NAME; bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8")); String line = ""; while (null != line) { line = bufferedReader.readLine(); stringBuffer.append(line); if (null != line && line.endsWith(";")) { System.out.println("[SHOP++?]SQL: " + line); preparedStatement = connection.prepareStatement(stringBuffer.toString()); preparedStatement.executeUpdate(); stringBuffer = new StringBuffer(); } } String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','" + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');"; String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');"; preparedStatement = connection.prepareStatement(insertAdminSql); preparedStatement.executeUpdate(); preparedStatement = connection.prepareStatement(insertAdminRoleSql); preparedStatement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); return ajaxJsonErrorMessage("???!"); } finally { try { if (resultSet != null) { resultSet.close(); resultSet = null; } if (preparedStatement != null) { preparedStatement.close(); preparedStatement = null; } if (connection != null) { connection.close(); connection = null; } } catch (SQLException e) { e.printStackTrace(); } } // ??? String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + JDBC_CONFIG_FILE_NAME; Properties properties = new Properties(); properties.put("jdbc.driver", "com.mysql.jdbc.Driver"); properties.put("jdbc.url", jdbcUrl); properties.put("jdbc.username", databaseUsername); properties.put("jdbc.password", databasePassword); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); properties.put("hibernate.show_sql", "false"); properties.put("hibernate.format_sql", "false"); OutputStream outputStream = new FileOutputStream(configFilePath); properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION); outputStream.close(); // ?? String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + BACKUP_WEB_CONFIG_FILE_NAME; String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String webConfigFilePath = new File( Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/" + WEB_CONFIG_FILE_NAME; String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("") .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME; String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath)); FileUtils.copyFile(new File(backupApplicationContextConfigFilePath), new File(applicationContextConfigFilePath)); FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath), new File(compassApplicationContextConfigFilePath)); FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath), new File(securityApplicationContextConfigFilePath)); // ?? String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SystemConfigUtil.CONFIG_FILE_NAME; File systemConfigFile = new File(systemConfigFilePath); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(systemConfigFile); Element rootElement = document.getRootElement(); Element systemConfigElement = rootElement.element("systemConfig"); Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled"); if (isInstalledNode == null) { isInstalledNode = systemConfigElement.addElement("isInstalled"); } isInstalledNode.setText("true"); try { OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML? outputFormat.setEncoding("UTF-8");// XML? outputFormat.setIndent(true);// ? outputFormat.setIndent(" ");// TAB? outputFormat.setNewlines(true);// ?? XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat); xmlWriter.write(document); xmlWriter.close(); } catch (Exception e) { e.printStackTrace(); } return ajaxJsonSuccessMessage("SHOP++?????"); }
From source file:com.jaspersoft.jasperserver.war.common.HeartbeatBean.java
private void initHeartbeat() { osName = System.getProperty("os.name"); osVersion = System.getProperty("os.version"); javaVendor = System.getProperty("java.vendor"); javaVersion = System.getProperty("java.version"); serverInfo = servletContext.getServerInfo(); location = servletContext.getRealPath("/"); dbName = null;//from w w w .jav a 2 s .c o m dbVersion = null; Connection connection = null; try { connection = dataSource.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); dbName = metaData.getDatabaseProductName(); dbVersion = metaData.getDatabaseProductVersion(); } catch (SQLException e) { if (log.isDebugEnabled()) log.debug("Getting database metadata failed.", e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { } } } String idSource = //javaVendor + "|" //+ javaVersion + "|" serverInfo + "|" + productName + "|" //+ productVersion + "|" + (location == null ? "" : location); MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { //heartbeat is always silent } if (messageDigest == null) { localId = String.valueOf(idSource.hashCode()); } else { byte[] idBytes = messageDigest.digest(idSource.getBytes()); StringBuffer idBuffer = new StringBuffer(2 * idBytes.length); for (int i = 0; i < idBytes.length; i++) { String hexa = Integer.toHexString(128 + idBytes[i]).toUpperCase(); hexa = ("00" + hexa).substring(hexa.length()); idBuffer.append(hexa); } localId = idBuffer.toString(); } /* */ File localIdFile = getLocalIdFile(); if (localIdFile.exists() && localIdFile.isFile()) { localIdProperties = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(localIdFile); localIdProperties.load(fis); } catch (IOException e) { if (log.isDebugEnabled()) log.debug("Loading heartbeat local ID properties file failed.", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } } } heartbeatId = localIdProperties.getProperty(PROPERTY_HEARTBEAT_ID); /* */ File clientInfoCacheFile = getClientInfoCacheFile(); if (clientInfoCacheFile.exists() && clientInfoCacheFile.isFile()) { try { clientInfoCache = (HeartbeatInfoCache) JRLoader.loadObject(clientInfoCacheFile); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Loading heartbeat cache from serialized file failed.", e); } } lastCacheSaveTime = System.currentTimeMillis(); }
From source file:com.amazon.carbonado.repo.jdbc.JDBCRepository.java
/** * @param name name to give repository instance * @param isMaster when true, storables in this repository must manage * version properties and sequence properties * @param dataSource provides JDBC database connections * @param catalog optional catalog to search for tables -- actual meaning * is database independent/*from w ww . jav a 2 s.c om*/ * @param schema optional schema to search for tables -- actual meaning is * is database independent * @param forceStoredSequence tells the repository to use a stored sequence * even if the database supports native sequences */ @SuppressWarnings("unchecked") JDBCRepository(AtomicReference<Repository> rootRef, String name, boolean isMaster, Iterable<TriggerFactory> triggerFactories, DataSource dataSource, boolean dataSourceClose, String catalog, String schema, Integer fetchSize, Map<String, Boolean> autoVersioningMap, Map<String, Boolean> suppressReloadMap, String sequenceSelectStatement, boolean forceStoredSequence, boolean primaryKeyCheckDisabled, SchemaResolver resolver) throws RepositoryException { super(name); if (dataSource == null) { throw new IllegalArgumentException("DataSource cannot be null"); } mIsMaster = isMaster; mTriggerFactories = triggerFactories; mRootRef = rootRef; mDataSource = dataSource; mDataSourceClose = dataSourceClose; mCatalog = catalog; mSchema = schema; mFetchSize = fetchSize; mPrimaryKeyCheckDisabled = primaryKeyCheckDisabled; mAutoVersioningMap = autoVersioningMap; mSuppressReloadMap = suppressReloadMap; mResolver = resolver; mOpenConnections = new IdentityHashMap<Connection, Object>(); mOpenConnectionsLock = new ReentrantLock(true); // Temporarily set to generic one, in case there's a problem during initialization. mExceptionTransformer = new JDBCExceptionTransformer(); mTxnMgr = new JDBCTransactionManager(this); getLog().info("Opening repository \"" + getName() + '"'); // Test connectivity and get some info on transaction isolation levels. Connection con = getConnection(); try { DatabaseMetaData md = con.getMetaData(); if (md == null || !md.supportsTransactions()) { throw new RepositoryException("Database does not support transactions"); } mDatabaseProductName = md.getDatabaseProductName(); boolean supportsSavepoints; try { supportsSavepoints = md.supportsSavepoints(); } catch (AbstractMethodError e) { supportsSavepoints = false; } if (supportsSavepoints) { con.setAutoCommit(false); // Some JDBC drivers (HSQLDB) lie about their savepoint support. try { con.setSavepoint(); } catch (SQLException e) { mLog.warn("JDBC driver for " + mDatabaseProductName + " reports supporting savepoints, but it " + "doesn't appear to work: " + e); supportsSavepoints = false; } finally { con.rollback(); con.setAutoCommit(true); } } mSupportsSavepoints = supportsSavepoints; mSupportsSelectForUpdate = md.supportsSelectForUpdate(); mSupportsScrollInsensitiveReadOnly = md.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); mJdbcDefaultIsolationLevel = md.getDefaultTransactionIsolation(); mDefaultIsolationLevel = mapIsolationLevelFromJdbc(mJdbcDefaultIsolationLevel); mReadUncommittedLevel = selectIsolationLevel(md, IsolationLevel.READ_UNCOMMITTED); mReadCommittedLevel = selectIsolationLevel(md, IsolationLevel.READ_COMMITTED); mRepeatableReadLevel = selectIsolationLevel(md, IsolationLevel.REPEATABLE_READ); mSerializableLevel = selectIsolationLevel(md, IsolationLevel.SERIALIZABLE); } catch (SQLException e) { throw toRepositoryException(e); } finally { try { closeConnection(con); } catch (SQLException e) { // Don't care. } } mSupportStrategy = JDBCSupportStrategy.createStrategy(this); if (forceStoredSequence) { mSupportStrategy.setSequenceSelectStatement(null); } else if (sequenceSelectStatement != null && sequenceSelectStatement.length() > 0) { mSupportStrategy.setSequenceSelectStatement(sequenceSelectStatement); } mSupportStrategy.setForceStoredSequence(forceStoredSequence); mExceptionTransformer = mSupportStrategy.createExceptionTransformer(); getLog().info("Opened repository \"" + getName() + '"'); setAutoShutdownEnabled(true); }
From source file:org.metis.push.PusherBean.java
/** * Called by Spring after all of this bean's properties have been set. */// ww w.j a v a 2 s. co m public void afterPropertiesSet() throws Exception { // create the session registry setWdsSessions(new Hashtable<String, WdsSocketSession>(getInitCapacity())); // log info for the jdbc driver being used // this will also attempt to open connection // with jdbc driver try { Connection con = getDataSource().getConnection(); if (con != null) { DatabaseMetaData dbmd = con.getMetaData(); setDbConnectionAcquired(true); if (dbmd != null) { setDriverName(dbmd.getDriverName().trim().toLowerCase()); // record the URL to the DB setDbUrl(dbmd.getURL().trim()); isOracle = (getDriverName() != null && getDriverName().indexOf(ORACLE_STR) >= 0) ? true : false; LOG.info(getBeanName() + ":Is Oracle JDBC Driver = " + isOracle); LOG.info(getBeanName() + ":JDBC Driver name = " + getDriverName()); LOG.info(getBeanName() + ":JDBC Driver version = " + dbmd.getDriverVersion().trim()); LOG.info(getBeanName() + ":JDBC Driver product name = " + dbmd.getDatabaseProductName().trim()); LOG.info(getBeanName() + ":JDBC URL = " + getDbUrl()); LOG.info(getBeanName() + ":JDBC Driver database product version = " + dbmd.getDatabaseProductVersion().trim()); con.close(); } else { LOG.info(getBeanName() + ": Unable to get JDBC driver meta data"); } } else { LOG.info(getBeanName() + ": Unable to get JDBC connection"); } } catch (SQLException exc) { LOG.error(getBeanName() + ": got this exception when trying to " + "get driver meta data: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } // bean must be assigned a JDBC DataSource if (getDataSource() == null) { throw new Exception( getBeanName() + ".afterPropertiesSet: this bean has not been " + "assigned a JDBC DataSource"); } // do some validation if (getSqls4Get() == null) { throw new Exception("The PusherBean must be assigned at least one SQL statement"); } // create and validate the injected SQL statements sqlStmnts4Get = new ArrayList<SqlStmnt>(); for (String sql : getSqls4Get()) { // get the frequency settings Map<String, Long> map = Utils.parseTimeInterval(sql); sql = Utils.stripTimeInterval(sql); sql = Utils.stripCall(sql); SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate()); if (stmt.isEqual(sqlStmnts4Get)) { throw new Exception("Injected SQL statements for GET are not distinct"); } // set the frequency stmt.setIntervalTime(map.get(TIME_INTERVAL)); if (map.get(TIME_INTERVAL_MAX) != null) { stmt.setIntervalMax(map.get(TIME_INTERVAL_MAX)); } if (map.get(TIME_INTERVAL_STEP) != null) { stmt.setIntervalStep(map.get(TIME_INTERVAL_STEP)); } sqlStmnts4Get.add(stmt); } if (LOG.isDebugEnabled()) { for (SqlStmnt sqlstmnt : sqlStmnts4Get) { LOG.debug(getBeanName() + ": SQL for GET = " + sqlstmnt.getOriginal()); LOG.debug(getBeanName() + ": Parameterized SQL for GET = " + sqlstmnt.getPrepared()); } } if (getHazelcastInstance() != null) { LOG.debug(getBeanName() + ": My Hazelcast Instance Name = " + getHazelcastInstance().getName()); ; } }