List of usage examples for java.sql DatabaseMetaData getURL
String getURL() throws SQLException;
From source file:org.sonar.server.platform.monitoring.DatabaseMonitor.java
private void completeDbAttributes(Map<String, Object> attributes) { try (DbSession dbSession = dbClient.openSession(false); Connection connection = dbSession.getConnection()) { DatabaseMetaData metadata = connection.getMetaData(); attributes.put("Database", metadata.getDatabaseProductName()); attributes.put("Database Version", metadata.getDatabaseProductVersion()); attributes.put("Username", metadata.getUserName()); attributes.put("URL", metadata.getURL()); attributes.put("Driver", metadata.getDriverName()); attributes.put("Driver Version", metadata.getDriverVersion()); attributes.put("Version Status", getMigrationStatus()); } catch (SQLException e) { throw new IllegalStateException("Fail to get DB metadata", e); }//from w w w .j a v a 2s . co m }
From source file:org.wso2.carbon.registry.core.config.RegistryConfigurationProcessor.java
/** * Read XML configuration from the passed InputStream, or from the classpath. * * @param in an InputStream containing XML data, or null. * @param registryContext the RegistryContext to populate * * @throws RegistryException if there's a problem *///from w ww . j a v a2s.co m public static void populateRegistryConfig(InputStream in, RegistryContext registryContext) throws RegistryException { if (in == null) { in = Thread.currentThread().getContextClassLoader() .getResourceAsStream("org/wso2/carbon/registry/core/servlet/registry.xml"); if (in == null) { return; } } try { StAXOMBuilder builder = new StAXOMBuilder(CarbonUtils.replaceSystemVariablesInXml(in)); OMElement configElement = builder.getDocumentElement(); if (configElement != null) { OMElement registryRootEle = configElement.getFirstChildWithName(new QName("registryRoot")); if (registryRootEle != null) { String registryRoot = registryRootEle.getText(); if (registryRoot != null && !registryRoot.equals(RegistryConstants.ROOT_PATH)) { if (registryRoot.endsWith(RegistryConstants.PATH_SEPARATOR)) { registryRoot = registryRoot.substring(0, registryRoot.length() - 1); } else if (!registryRoot.startsWith(RegistryConstants.PATH_SEPARATOR)) { registryRoot = RegistryConstants.ROOT_PATH + registryRoot; } } else { registryRoot = null; } registryContext.setRegistryRoot(registryRoot); } OMElement readOnlyEle = configElement.getFirstChildWithName(new QName("readOnly")); if (readOnlyEle != null) { registryContext .setReadOnly(CarbonUtils.isReadOnlyNode() || "true".equals(readOnlyEle.getText())); } OMElement enableCachingEle = configElement.getFirstChildWithName(new QName("enableCache")); if (enableCachingEle != null) { registryContext.setCacheEnabled("true".equals(enableCachingEle.getText())); } SecretResolver secretResolver = SecretResolverFactory.create(configElement, false); Iterator dbConfigs = configElement.getChildrenWithName(new QName("dbConfig")); // Read Database configurations while (dbConfigs.hasNext()) { OMElement dbConfig = (OMElement) dbConfigs.next(); DataBaseConfiguration dataBaseConfiguration = new DataBaseConfiguration(); dataBaseConfiguration.setPasswordManager(secretResolver); String dbName = dbConfig.getAttributeValue(new QName("name")); if (dbName == null) { throw new RegistryException("The database configuration name cannot be " + "null."); } dataBaseConfiguration.setConfigName(dbName); OMElement dataSource = dbConfig.getFirstChildWithName(new QName("dataSource")); if (dataSource != null) { String dataSourceName = dataSource.getText(); dataBaseConfiguration.setDataSourceName(dataSourceName); try { Context context = new InitialContext(); Connection connection = null; try { connection = ((DataSource) context.lookup(dataSourceName)).getConnection(); DatabaseMetaData metaData = connection.getMetaData(); // We need to obtain the connection URL and the username, which is // required for building the cache key. dataBaseConfiguration.setDbUrl(metaData.getURL()); dataBaseConfiguration.setUserName(metaData.getUserName()); } finally { if (connection != null) { connection.close(); } } } catch (NamingException ignored) { log.warn("Unable to look-up JNDI name " + dataSourceName); } catch (SQLException e) { e.printStackTrace(); throw new RegistryException("Unable to connect to Data Source", e); } } else { OMElement userName = dbConfig.getFirstChildWithName(new QName("userName")); if (userName != null) { dataBaseConfiguration.setUserName(userName.getText()); } OMElement password = dbConfig.getFirstChildWithName(new QName("password")); if (password != null) { dataBaseConfiguration.setPassWord(password.getText()); } OMElement url = dbConfig.getFirstChildWithName(new QName("url")); String dbUrl = url.getText(); if (dbUrl != null) { // If the connection URL contains ${carbon.home}, replace it with the // corresponding value. if (dbUrl.contains(CarbonConstants.CARBON_HOME_PARAMETER)) { File carbonHomeDir; carbonHomeDir = new File(CarbonUtils.getCarbonHome()); String path = carbonHomeDir.getPath(); path = path.replaceAll(Pattern.quote("\\"), "/"); if (carbonHomeDir.exists() && carbonHomeDir.isDirectory()) { dbUrl = dbUrl.replaceAll(Pattern.quote(CarbonConstants.CARBON_HOME_PARAMETER), path); } else { log.warn("carbon home invalid"); String[] tempStrings1 = dbUrl .split(Pattern.quote(CarbonConstants.CARBON_HOME_PARAMETER)); String tempUrl = tempStrings1[1]; String[] tempStrings2 = tempUrl.split("/"); for (int i = 0; i < tempStrings2.length - 1; i++) { dbUrl = tempStrings1[0] + tempStrings2[i] + "/"; } dbUrl = dbUrl + tempStrings2[tempStrings2.length - 1]; } url.setText(dbUrl); } } dataBaseConfiguration.setDbUrl(url.getText()); OMElement driverName = dbConfig.getFirstChildWithName(new QName("driverName")); if (driverName != null) { dataBaseConfiguration.setDriverName(driverName.getText()); } OMElement maxWait = dbConfig.getFirstChildWithName(new QName("maxWait")); if (maxWait != null) { dataBaseConfiguration.setMaxWait(maxWait.getText()); } OMElement testWhileIdle = dbConfig.getFirstChildWithName(new QName("testWhileIdle")); if (testWhileIdle != null) { dataBaseConfiguration.setTestWhileIdle(testWhileIdle.getText()); } OMElement timeBetweenEvictionRunsMillis = dbConfig .getFirstChildWithName(new QName("timeBetweenEvictionRunsMillis")); if (timeBetweenEvictionRunsMillis != null) { dataBaseConfiguration .setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis.getText()); } OMElement minEvictableIdleTimeMillis = dbConfig .getFirstChildWithName(new QName("minEvictableIdleTimeMillis")); if (minEvictableIdleTimeMillis != null) { dataBaseConfiguration .setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis.getText()); } OMElement numTestsPerEvictionRun = dbConfig .getFirstChildWithName(new QName("numTestsPerEvictionRun")); if (numTestsPerEvictionRun != null) { dataBaseConfiguration.setNumTestsPerEvictionRun(numTestsPerEvictionRun.getText()); } OMElement maxActive = dbConfig.getFirstChildWithName(new QName("maxActive")); if (maxActive != null) { dataBaseConfiguration.setMaxActive(maxActive.getText()); } OMElement maxIdle = dbConfig.getFirstChildWithName(new QName("maxIdle")); if (maxIdle != null) { dataBaseConfiguration.setMaxIdle(maxIdle.getText()); } OMElement minIdle = dbConfig.getFirstChildWithName(new QName("minIdle")); if (minIdle != null) { dataBaseConfiguration.setMinIdle(minIdle.getText()); } OMElement validationQuery = dbConfig.getFirstChildWithName(new QName("validationQuery")); if (validationQuery != null) { dataBaseConfiguration.setValidationQuery(validationQuery.getText()); } } registryContext.addDBConfig(dbName, dataBaseConfiguration); } // loading one-time start-up configurations OMElement staticConfigElement = configElement .getFirstChildWithName(new QName("staticConfiguration")); if (staticConfigElement != null) { Iterator staticConfigs = staticConfigElement.getChildElements(); while (staticConfigs.hasNext()) { OMElement staticConfig = (OMElement) staticConfigs.next(); if (staticConfig.getLocalName().equals("versioningProperties")) { String versioningProperties = staticConfig.getText(); StaticConfiguration.setVersioningProperties(versioningProperties.equals("true")); } else if (staticConfig.getLocalName().equals("versioningComments")) { String versioningComments = staticConfig.getText(); StaticConfiguration.setVersioningComments(versioningComments.equals("true")); } else if (staticConfig.getLocalName().equals("versioningTags")) { String versioningTags = staticConfig.getText(); StaticConfiguration.setVersioningTags(versioningTags.equals("true")); } else if (staticConfig.getLocalName().equals("versioningRatings")) { String versioningRatings = staticConfig.getText(); StaticConfiguration.setVersioningRatings(versioningRatings.equals("true")); } else if (staticConfig.getLocalName().equals("versioningAssociations")) { String versioningAssociations = staticConfig.getText(); StaticConfiguration.setVersioningAssociations(versioningAssociations.equals("true")); } else if (staticConfig.getLocalName().equals("profilesPath")) { String profilesPath = staticConfig.getText(); if (!profilesPath.startsWith(RegistryConstants.PATH_SEPARATOR)) { //if user give the path like test or test/ profilesPath = RegistryConstants.PATH_SEPARATOR + profilesPath; } if (profilesPath.endsWith(RegistryConstants.PATH_SEPARATOR)) { profilesPath = profilesPath.substring(0, (profilesPath.length() - 1)); //if user give the path like this /test/ } if (profilesPath != null) { if (profilesPath.startsWith(RegistryConstants.CONFIG_REGISTRY_BASE_PATH)) { registryContext.setProfilesPath(profilesPath); } else { registryContext.setProfilesPath( RegistryConstants.CONFIG_REGISTRY_BASE_PATH + profilesPath); } } } else if (staticConfig.getLocalName().equals("servicePath")) { String servicePath = staticConfig.getText(); if (!servicePath.startsWith(RegistryConstants.PATH_SEPARATOR)) { //if user give the path like test or test/ servicePath = RegistryConstants.PATH_SEPARATOR + servicePath; } if (servicePath.endsWith(RegistryConstants.PATH_SEPARATOR)) { servicePath = servicePath.substring(0, (servicePath.length() - 1)); //if user give the path like this /test/ } if (servicePath != null) { if (servicePath.startsWith(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH)) { registryContext.setServicePath(servicePath); } else { registryContext.setServicePath( RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + servicePath); } } } } } OMElement currentConfigElement = configElement.getFirstChildWithName(new QName("currentDBConfig")); if (currentConfigElement == null) { throw new RegistryException("The current database configuration is not " + "defined."); } String currentConfigName = currentConfigElement.getText(); readRemoteInstances(configElement, registryContext, secretResolver); readMounts(configElement, registryContext); DataBaseConfiguration dbConfiguration = registryContext.selectDBConfig(currentConfigName); registryContext.setDefaultDataBaseConfiguration(dbConfiguration); OMElement versionConfig = configElement .getFirstChildWithName(new QName("versionResourcesOnChange")); if (versionConfig != null && "true".equals(versionConfig.getText())) { registryContext.setVersionOnChange(true); } else { registryContext.setVersionOnChange(false); } initializeHandlers(configElement, registryContext); // process query processor config Iterator queryProcessors = configElement.getChildrenWithName(new QName("queryProcessor")); while (queryProcessors.hasNext()) { QueryProcessorConfiguration queryProcessorConfiguration = new QueryProcessorConfiguration(); OMElement queryProcessorElement = (OMElement) queryProcessors.next(); OMElement queryType = queryProcessorElement.getFirstChildWithName(new QName("queryType")); if (queryType != null) { queryProcessorConfiguration.setQueryType(queryType.getText()); } OMElement processorName = queryProcessorElement.getFirstChildWithName(new QName("processor")); if (processorName != null) { queryProcessorConfiguration.setProcessorClassName(processorName.getText()); } registryContext.addQueryProcessor(queryProcessorConfiguration); } initializeAspects(configElement, registryContext); } } catch (XMLStreamException e) { throw new RegistryException(e.getMessage()); } catch (CarbonException e) { log.error("An error occurred during system variable replacement", e); } }
From source file:org.wso2.carbon.registry.core.utils.RegistryUtils.java
/** * Method to obtain a unique identifier for the database connection. * * @param connection the database connection. * * @return the unique identifier./*from w ww .j a va 2 s. co m*/ */ public static String getConnectionId(Connection connection) { String connectionId = null; try { // The connection URL is unique enough to be used as an identifier since one thread // makes one connection to the given URL according to our model. DatabaseMetaData connectionMetaData = connection.getMetaData(); if (connectionMetaData != null) { String productName = connectionMetaData.getDatabaseProductName(); if (MY_SQL_PRODUCT_NAME.equals(productName)) { /* For MySQL getUserName() method executes 'SELECT USER()' query on DB via mysql connector causing a huge number of 'SELECT USER()' queries to be executed. Hence removing username when the DB in use is MySQL. */ connectionId = connectionMetaData.getURL(); } else { connectionId = (connectionMetaData.getUserName() != null ? connectionMetaData.getUserName().split("@")[0] : connectionMetaData.getUserName()) + "@" + connectionMetaData.getURL(); } } } catch (SQLException e) { log.error("Failed to construct the connectionId.", e); } return connectionId; }
From source file:org.wso2.carbon.repository.core.config.RepositoryConfigurationProcessor.java
/** * Read XML configuration from the passed InputStream, or from the classpath. * * @param in an InputStream containing XML data, or null. * @param repositoryContext the RegistryContext to populate * * @throws RepositoryException if there's a problem */// w w w. j av a2 s.c om public static void populateRepositoryConfig(InputStream in, RepositoryContext repositoryContext, RepositoryService registryService) throws RepositoryException { try { InputStream replacedStream = CarbonUtils.replaceSystemVariablesInXml(in); DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); Document document = documentBuilder.parse(replacedStream); Element documentElement = document.getDocumentElement(); documentElement.normalize(); NodeList rootLists = documentElement.getElementsByTagName("registryRoot"); if (rootLists != null && rootLists.getLength() > 0) { Node node = rootLists.item(0); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { String registryRoot = ((Element) node).getTextContent(); if (registryRoot != null && !registryRoot.equals(RepositoryConstants.ROOT_PATH)) { if (registryRoot.endsWith(RepositoryConstants.PATH_SEPARATOR)) { registryRoot = registryRoot.substring(0, registryRoot.length() - 1); } else if (!registryRoot.startsWith(RepositoryConstants.PATH_SEPARATOR)) { registryRoot = RepositoryConstants.ROOT_PATH + registryRoot; } } else { registryRoot = null; } repositoryContext.setRegistryRoot(registryRoot); } } NodeList readOnlyElements = documentElement.getElementsByTagName("readOnly"); if (readOnlyElements != null && readOnlyElements.getLength() > 0) { Node node = readOnlyElements.item(0); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { String isReadOnly = ((Element) node).getTextContent(); repositoryContext.setReadOnly(CarbonUtils.isReadOnlyNode() || "true".equals(isReadOnly)); } } NodeList enableCacheElements = documentElement.getElementsByTagName("enableCache"); if (enableCacheElements != null && enableCacheElements.getLength() > 0) { Node node = enableCacheElements.item(0); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { String enableCacheElement = ((Element) node).getTextContent(); repositoryContext.setCacheEnabled("true".equals(enableCacheElement)); } } SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false); NodeList dbConfigElements = documentElement.getElementsByTagName("dbConfig"); for (int index = 0; index < dbConfigElements.getLength(); index++) { Node dbConfig = dbConfigElements.item(index); DataBaseConfiguration dataBaseConfiguration = new DataBaseConfiguration(); dataBaseConfiguration.setPasswordManager(secretResolver); if (dbConfig != null && dbConfig.getNodeType() == Node.ELEMENT_NODE) { Element dbConfigElement = (Element) dbConfig; String dbName = dbConfigElement.getAttribute("name"); if (dbName == null) { throw new RepositoryConfigurationException( "The database configuration name cannot be null."); } dataBaseConfiguration.setConfigName(dbName); NodeList dbConfigDataSources = dbConfigElement.getChildNodes(); for (int content = 0; content < dbConfigDataSources.getLength(); content++) { Node dbConfigNode = dbConfigDataSources.item(content); if (dbConfigNode != null && dbConfigNode.getNodeType() == Node.ELEMENT_NODE) { if (dbConfigNode.getNodeName() == "dataSource") { String dataSourceName = dbConfigNode.getTextContent(); dataBaseConfiguration.setDataSourceName(dataSourceName); try { Context context = new InitialContext(); Connection connection = null; try { connection = ((DataSource) context.lookup(dataSourceName)).getConnection(); DatabaseMetaData metaData = connection.getMetaData(); dataBaseConfiguration.setDbUrl(metaData.getURL()); dataBaseConfiguration.setUserName(metaData.getUserName()); } finally { if (connection != null) { connection.close(); } } } catch (NamingException ignored) { log.warn("Unable to look-up JNDI name " + dataSourceName); } catch (SQLException e) { e.printStackTrace(); throw new RepositoryDBException("Unable to connect to Data Source", e); } } else { if (dbConfigNode.getNodeName() == "userName") { dataBaseConfiguration.setUserName(dbConfigNode.getTextContent()); } else if (dbConfigNode.getNodeName() == "password") { dataBaseConfiguration.setPassWord(dbConfigNode.getTextContent()); } else if (dbConfigNode.getNodeName() == "url") { String dbUrl = dbConfigNode.getTextContent(); if (dbUrl != null) { if (dbUrl.contains(CarbonConstants.CARBON_HOME_PARAMETER)) { File carbonHomeDir; carbonHomeDir = new File(CarbonUtils.getCarbonHome()); String path = carbonHomeDir.getPath(); path = path.replaceAll(Pattern.quote("\\"), "/"); if (carbonHomeDir.exists() && carbonHomeDir.isDirectory()) { dbUrl = dbUrl.replaceAll( Pattern.quote(CarbonConstants.CARBON_HOME_PARAMETER), path); } else { log.warn("carbon home invalid"); String[] tempStrings1 = dbUrl.split( Pattern.quote(CarbonConstants.CARBON_HOME_PARAMETER)); String tempUrl = tempStrings1[1]; String[] tempStrings2 = tempUrl.split("/"); for (int i = 0; i < tempStrings2.length - 1; i++) { dbUrl = tempStrings1[0] + tempStrings2[i] + "/"; } dbUrl = dbUrl + tempStrings2[tempStrings2.length - 1]; } } } dataBaseConfiguration.setDbUrl(dbUrl); } else if (dbConfigNode.getNodeName() == "maxWait") { dataBaseConfiguration.setMaxWait(dbConfigNode.getTextContent()); } else if (dbConfigNode.getNodeName() == "maxActive") { dataBaseConfiguration.setMaxActive(dbConfigNode.getTextContent()); } else if (dbConfigNode.getNodeName() == "minIdle") { dataBaseConfiguration.setMinIdle(dbConfigNode.getTextContent()); } else if (dbConfigNode.getNodeName() == "driverName") { dataBaseConfiguration.setDriverName(dbConfigNode.getTextContent()); } } } } repositoryContext.addDBConfig(dbName, dataBaseConfiguration); } } NodeList staticConfigNodes = documentElement.getElementsByTagName("staticConfiguration"); if (staticConfigNodes != null && staticConfigNodes.getLength() > 0) { Node staticConfigNode = staticConfigNodes.item(0); NodeList staticConfigItems = staticConfigNode.getChildNodes(); for (int index = 0; index < staticConfigItems.getLength(); index++) { Node staticConfig = staticConfigItems.item(index); if (staticConfig != null && staticConfig.getNodeType() == Node.ELEMENT_NODE) { if (staticConfig.getNodeName().equals("versioningProperties")) { String versioningProperties = staticConfig.getTextContent(); StaticConfiguration.setVersioningProperties(versioningProperties.equals("true")); } else if (staticConfig.getNodeName().equals("profilesPath")) { String profilesPath = staticConfig.getTextContent(); if (!profilesPath.startsWith(RepositoryConstants.PATH_SEPARATOR)) { profilesPath = RepositoryConstants.PATH_SEPARATOR + profilesPath; } if (profilesPath.endsWith(RepositoryConstants.PATH_SEPARATOR)) { profilesPath = profilesPath.substring(0, (profilesPath.length() - 1)); } if (profilesPath != null) { if (profilesPath.startsWith(RepositoryConstants.CONFIG_REGISTRY_BASE_PATH)) { repositoryContext.setProfilesPath(profilesPath); } else { repositoryContext.setProfilesPath( RepositoryConstants.CONFIG_REGISTRY_BASE_PATH + profilesPath); } } } else if (staticConfig.getNodeName().equals("servicePath")) { String servicePath = staticConfig.getTextContent(); if (!servicePath.startsWith(RepositoryConstants.PATH_SEPARATOR)) { servicePath = RepositoryConstants.PATH_SEPARATOR + servicePath; } if (servicePath.endsWith(RepositoryConstants.PATH_SEPARATOR)) { servicePath = servicePath.substring(0, (servicePath.length() - 1)); } if (servicePath != null) { if (servicePath.startsWith(RepositoryConstants.GOVERNANCE_REGISTRY_BASE_PATH)) { repositoryContext.setServicePath(servicePath); } else { repositoryContext.setServicePath( RepositoryConstants.GOVERNANCE_REGISTRY_BASE_PATH + servicePath); } } } } } } NodeList currentDBConfigs = documentElement.getElementsByTagName("currentDBConfig"); if (currentDBConfigs == null) { throw new RepositoryConfigurationException("The current database configuration is not defined."); } String currentConfigName = currentDBConfigs.item(0).getTextContent(); readRemoteInstances(documentElement, repositoryContext, secretResolver); readMounts(documentElement, repositoryContext); DataBaseConfiguration dbConfiguration = repositoryContext.selectDBConfig(currentConfigName); repositoryContext.setDefaultDataBaseConfiguration(dbConfiguration); NodeList versionConfigList = documentElement.getElementsByTagName("versionResourcesOnChange"); if (versionConfigList != null && versionConfigList.getLength() > 0) { Node versionConfig = versionConfigList.item(0); if (versionConfig != null && "true".equals(versionConfig.getTextContent())) { repositoryContext.setVersionOnChange(true); } else { repositoryContext.setVersionOnChange(false); } } initializeHandlers(documentElement, repositoryContext); // process query processor configuration NodeList queryProcessors = documentElement.getElementsByTagName("queryProcessor"); for (int index = 0; index < queryProcessors.getLength(); index++) { QueryProcessorConfiguration queryProcessorConfiguration = new QueryProcessorConfiguration(); Node queryProcessorNode = queryProcessors.item(index); NodeList queryProcessorChildren = queryProcessorNode.getChildNodes(); for (int childIndex = 0; childIndex < queryProcessorChildren.getLength(); childIndex++) { Node queryProcessorChild = queryProcessorChildren.item(childIndex); if (queryProcessorChild != null && queryProcessorChild.getNodeType() == Node.ELEMENT_NODE) { if (queryProcessorChild.getNodeName() == "queryType") { queryProcessorConfiguration.setQueryType(queryProcessorChild.getTextContent()); } else if (queryProcessorChild.getNodeName() == "processor") { queryProcessorConfiguration.setProcessorClassName(queryProcessorChild.getTextContent()); } } } repositoryContext.addQueryProcessor(queryProcessorConfiguration); } } catch (SAXException e1) { throw new RepositoryInitException(e1.getMessage()); } catch (IOException e1) { throw new RepositoryInitException(e1.getMessage()); } catch (ParserConfigurationException e1) { throw new RepositoryInitException(e1.getMessage()); } catch (CarbonException e) { log.error("An error occurred during system variable replacement", e); } }
From source file:org.wso2.carbon.repository.core.utils.InternalUtils.java
/** * Method to obtain a unique identifier for the database connection. * * @param connection the database connection. * * @return the unique identifier./*from w w w . j a v a2 s .c om*/ */ public static String getConnectionId(Connection connection) { try { // The connection URL is unique enough to be used as an identifier since one thread // makes one connection to the given URL according to our model. DatabaseMetaData connectionMetaData = connection.getMetaData(); if (connectionMetaData != null) { return connectionMetaData.getUserName() + "@" + connectionMetaData.getURL(); } } catch (SQLException ignore) { } return null; }
From source file:org.wso2.carbon.server.admin.service.ServerAdmin.java
public ServerData getServerData() throws Exception { boolean isRestricted = true; MessageContext msgContext = MessageContext.getCurrentMessageContext(); if (msgContext != null) { HttpServletRequest request = (HttpServletRequest) msgContext .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); HttpSession httpSession = request.getSession(false); if (httpSession != null) { String userName = (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN); isRestricted = !getUserRealm().getAuthorizationManager().isUserAuthorized(userName, "/permission/protected/server-admin/homepage", CarbonConstants.UI_PERMISSION_ACTION); }// www.j a va2 s . c om } else { // non SOAP call isRestricted = false; } String location = null; if (!isRestricted) { location = getAxisConfig().getRepository().toString(); } ServerData data = new ServerData(ServerConstants.SERVER_NAME, location, (getTenantDomain() != null && !getTenantDomain().equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)), isRestricted); if (!isRestricted) { Parameter systemStartTime = getAxisConfig().getParameter(CarbonConstants.SERVER_START_TIME); long startTime = 0; if (systemStartTime != null) { startTime = Long.parseLong((String) systemStartTime.getValue()); } Date stTime = new Date(startTime); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss"); data.setServerStartTime(dateFormatter.format(stTime)); data.setServerUpTime(getTime((System.currentTimeMillis() - startTime) / 1000)); Parameter systemStartUpDuration = getAxisConfig().getParameter(CarbonConstants.START_UP_DURATION); if (systemStartUpDuration != null) { data.setServerStartUpDuration((String) systemStartUpDuration.getValue()); } ServerConfigurationService serverConfig = dataHolder.getServerConfig(); String registryType = serverConfig.getFirstProperty("Registry.Type"); if (registryType == null) { registryType = "embedded"; } data.setRegistryType(registryType); // Extract DB related data from RegistryContext if (registryType.equals("embedded")) { try { DataAccessManager dataAccessManager = RegistryContext.getBaseInstance().getDataAccessManager(); if (!(dataAccessManager instanceof JDBCDataAccessManager)) { String msg = "Failed to obtain DB connection. Invalid data access manager."; log.error(msg); throw new AxisFault(msg); } DataSource dataSource = ((JDBCDataAccessManager) dataAccessManager).getDataSource(); Connection dbConnection = dataSource.getConnection(); DatabaseMetaData metaData = dbConnection.getMetaData(); if (metaData != null) { data.setDbName(metaData.getDatabaseProductName()); data.setDbVersion(metaData.getDatabaseProductVersion()); data.setDbDriverName(metaData.getDriverName()); data.setDbDriverVersion(metaData.getDriverVersion()); data.setDbURL(metaData.getURL()); } dbConnection.close(); } catch (SQLException e) { String msg = "Cannot create DB connection"; log.error(msg, e); throw new AxisFault(msg, e); } } else if (registryType.equals("remote")) { data.setRemoteRegistryChroot(serverConfig.getFirstProperty("Registry.Chroot")); data.setRemoteRegistryURL(serverConfig.getFirstProperty("Registry.Url")); } } try { data.setServerIp(NetworkUtils.getLocalHostname()); } catch (SocketException e) { throw new AxisFault(e.getMessage(), e); } return data; }
From source file:swp.bibjsf.persistence.Data.java
/** * Returns the lower-case names of all tables in the database. * * @return list of lower-case names of all tables in the database * @throws SQLException/*ww w .jav a 2s. com*/ * falls ein Fehler beim Zugriff auf die Datenbank auftritt */ private List<String> getTableNames() throws SQLException { logger.debug("get table names"); DatabaseMetaData dbMeta; List<String> result = new ArrayList<String>(); Connection dbConnection = dataSource.getConnection(); try { dbMeta = dbConnection.getMetaData(); logger.debug("URL of database " + dbMeta.getURL()); logger.debug("database version: major=" + dbMeta.getDatabaseMajorVersion() + " minor=" + dbMeta.getDatabaseMinorVersion() + " product_version=" + dbMeta.getDatabaseProductVersion() + " product_name=" + dbMeta.getDatabaseProductName()); ResultSet rs = dbMeta.getTables(null, null, null, new String[] { "TABLE" }); try { while (rs.next()) { String theTableName = rs.getString("TABLE_NAME"); result.add(theTableName.toLowerCase()); } } finally { rs.close(); } return result; } finally { try { dbConnection.close(); } catch (SQLException e) { logger.debug("error while trying to close the database connection."); // ignore, nothing to be done here anyway } } }
From source file:za.co.eon.econtentsolutions.component.abstractlticomponent.AbstractLTIComponentServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . j av a 2 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try (PrintWriter out = response.getWriter()) { Launch launch = tsugi.getLaunch(request, response); if (launch.isComplete()) { launch.getOutput().flashSuccess("LTI Launch validated and redirected"); log.info("LTI Launch validated and redirected..."); return; } if (!launch.isValid()) { out.println("<pre>"); out.println("Launch is not valid but nowhere to redirect"); out.println(launch.getErrorMessage()); out.println("Base String:"); out.println(launch.getBaseString()); out.println("</pre>"); out.close(); throw new RuntimeException(launch.getErrorMessage()); } HttpSession session = request.getSession(); Output o = launch.getOutput(); Properties versions = o.header(out); o.bodyStart(out); o.flashMessages(out); // out.println("<pre>"); // Dump out some stuff from the Request Object out.println(""); out.println( "<a href=\"http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html\" target=\"_blank\">HttpServletRequest</a> data:"); out.println("req.getRequestURL()=" + request.getRequestURL()); out.println("req.getMethod()=" + request.getMethod()); out.println("req.getServletPath()=" + request.getServletPath()); out.println("req.getPathInfo()=" + request.getPathInfo()); out.println("req.getQueryString()=" + request.getQueryString()); out.println(""); out.print("<a href=\""); out.print(launch.getGetUrl(null) + "/zap"); out.println("\">Click here to see if we stay logged in with a GET</a>"); out.println(""); out.println( "Using the <a href=\"http://csev.github.io/tsugi-java/apidocs/index.html\" target=\"_blank\">Tsugi API</a>:"); out.println("Content Title: " + launch.getContext().getTitle()); out.println("Context Settings: " + launch.getContext().getSettings().getSettingsJson()); out.println("User Email: " + launch.getUser().getEmail()); out.println("isInstructor()=" + launch.getUser().isInstructor()); out.println("isTenantAdmin()=" + launch.getUser().isTenantAdmin()); out.println("Link Title: " + launch.getLink().getTitle()); out.println("Link Settings: " + launch.getLink().getSettings().getSettingsJson()); out.println("Sourcedid: " + launch.getResult().getSourceDID()); out.println("Service URL: " + launch.getService().getURL()); out.println(""); out.println("JavaScript library versions:"); out.println(TsugiUtils.dumpProperties(versions)); out.println(""); out.println("Using the provided JDBC connection:"); Connection c = null; try { c = launch.getConnection(); out.println("Connection: " + c); DatabaseMetaData meta = c.getMetaData(); String productName = meta.getDatabaseProductName(); String productVersion = meta.getDatabaseProductVersion(); String URL = meta.getURL(); out.println("Connection product=" + productName + " version=" + productVersion); out.println("Connection URL=" + URL); } catch (Exception ex) { log.error("Unable to get connection metadata", ex); out.println("Unable to get connection metadata:" + ex.getMessage()); } // Do a simple query just to see how it is done if (c != null) { Statement stmt = null; String query = "SELECT plugin_id, plugin_path FROM lms_plugins;"; try { stmt = c.createStatement(); ResultSet rs = stmt.executeQuery(query); int num = 0; while (rs.next()) { String plugin_path = rs.getString("plugin_path"); out.println("plugin_path=" + plugin_path); num++; } out.println("Successfully read " + num + " rows from the database"); } catch (SQLException e) { out.println("Problems reading database"); out.println("INSERT INTO mjjs (name) VALUES ('tsugi');"); e.printStackTrace(); } } // Cheat and look at the internal data Tsugi maintains - this depends on // the JDBC implementation Properties sess_row = (Properties) session.getAttribute("lti_row"); if (sess_row != null) { out.println(""); out.println("Tsugi-managed internal session data (Warning: org.tsugi.impl.jdbc.Tsugi_JDBC only)"); String x = TsugiUtils.dumpProperties(sess_row); out.println(x); } out.println("</pre>"); // Do the Footer o.footerStart(out); out.println("<!-- App footer stuff goes here -->"); o.footerEnd(out); out.close(); } catch (RuntimeException re) { try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>AbstractLTIComponentServlet Error</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>AbstractLTIComponentServlet</h1>"); out.println("<h3 style=\"color: red;\">Error</h3>"); out.println("<p>Servlet AbstractLTIComponentServlet at " + request.getContextPath() + " threw an exception.</p>"); out.println("<p>Exception: " + re.toString() + "<br />"); out.println("Message: " + re.getMessage() + "<br />"); out.println("Stacktrace:</p>"); out.println("<p>" + re.getStackTrace().toString() + "</p>"); out.println("</body>"); out.println("</html>"); } } }