简体   繁体   English

如何在java.sql.Connection中检索主机、端口、sid、用户和密码信息

[英]How to retrieve host, port, sid, user and password informations in java.sql.Connection

I have an Oracle connection (in a java.sql.Connection object) that is mounted from a properties file (ApplicationResources.properties).我有一个从属性文件 (ApplicationResources.properties) 挂载的 Oracle 连接(在 java.sql.Connection 对象中)。

How do I capture information about host, port, sid, user and password?如何获取有关主机、端口、sid、用户和密码的信息? (I need this information to call a specific database function through my java application) (我需要这些信息来通过我的 java 应用程序调用特定的数据库函数)

Below my code:在我的代码下面:

private void conectaBanco() {
    ServiceLocator sl = new ServiceLocator();
    InitialContext ic = null;
    DataSource dataSource = null;
    try {
        if (conn == null) {
            ic = new InitialContext();
            dataSource = (DataSource) ic.lookup(sl.getInfo().getString("JNDI"));                
            conn = dataSource.getConnection();
            conn.setAutoCommit( true );
                            
            // I need host, port, sid and password information
            System.out.println("USER " + conn.getMetaData().getUserName());                                                
        }
    } catch (SQLException e) {
        logger.error("Erro ao tentar abrir conexao com o banco de dados.", e);
    } catch (NamingException e) {
        logger.error("Erro ao tentar abrir conexao com o banco de dados.", e);
    }
    
    if(conn != null)
        rastrear.definePredicate(conn);
}

SESSION SID:会话 SID:

SELECT sys_context('USERENV', 'SID') FROM DUAL;

ORACLE_SID: ORACLE_SID:

SELECT sys_context('userenv','instance_name') FROM dual;

HOST (Database machine) :主机(数据库机):

SELECT UTL_INADDR.get_host_name FROM dual;

Password: See http://www.dba-oracle.com/t_password_storage.htm密码:见http://www.dba-oracle.com/t_password_storage.htm

CLIENT SIDE Port:客户端端口:

Select port from v$session;

SERVER OS PID of Oracle server process connected to client process连接到客户端进程的 Oracle 服务器进程的 SERVER OS PID

SELECT p.spid
FROM   v$process p, v$session s
WHERE s.paddr = p.addr and 
sys_context('USERENV', 'SID') = s.sid;

Server side port:服务器端端口:

This is really difficult since the server process port is mapped to a different port then the initial - for example port 12102 in listener.ora/tnsnames.ora get mapped by listener to a arbitrary free one (by the way: thats the reason why often firewalls need to be shutdown and while connections cannot get after mapping through firewall. This can be fixed but this is another story)这真的很困难,因为服务器进程端口被映射到与初始端口不同的端口 - 例如 listener.ora/tnsnames.ora 中的端口 12102 被侦听器映射到任意空闲端口(顺便说一句:这就是为什么经常防火墙需要关闭,而通过防火墙映射后连接无法获得。这可以修复,但这是另一回事)

Below code下面的代码

  • grants required privileges授予所需的权限

  • defines a java stored function "Util.RunThis" which executes on database server a OS command passed into function and return string.定义了一个 java 存储函数“Util.RunThis”,它在数据库服务器上执行传递给函数并返回字符串的操作系统命令。

  • "Util.RunThis" is mapped to PL/SQL function "RUN_CMD" "Util.RunThis" 映射到 PL/SQL 函数 "RUN_CMD"

  • "GET_PORT" is a PL/SQL function returning a numeric value of the used Port of the database server process connected to client session. “GET_PORT”是一个 PL/SQL 函数,它返回连接到客户端会话的数据库服务器进程使用的端口的数值。 Inside GET_PORT the SELECT is used to determine database server process pid replacing [SPID] in command below在 GET_PORT 中,SELECT 用于确定数据库服务器进程 pid 替换下面命令中的 [SPID]

     /usr/sbin/lsof -Pan -p [SPID] -i
  • finally invoking a simple select we get the Port of database server process attached to current session最后调用一个简单的选择我们得到附加到当前会话的数据库服务器进程的端口

     connect / as sysdba grant select on sys.v_$process to scott; grant select on sys.v_$session to scott; begin dbms_java.grant_permission ('SCOTT', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'execute'); end; / connect scott/tiger@foo.com create or replace and compile java source named "Util" as import java.io.*; import java.lang.*; import java.nio.charset.Charset; import java.nio.*; public class Util extends Object { public static String RunThis(String args) { Runtime rt = Runtime.getRuntime(); String rc = args; try { Process p = rt.exec(args); int bufSize = 4096; BufferedInputStream bis = new BufferedInputStream(p.getInputStream(), bufSize); int len; byte buffer[] = new byte[bufSize]; // Echo back what the program spit out while ((len = bis.read(buffer, 0, bufSize)) != -1) { String xxx = new String(buffer, Charset.forName("UTF-8")); rc = rc + xxx; } p.waitFor(); rc = rc + "ABC"; } catch (Exception e) { e.printStackTrace(); rc = "Exception!!!" ; } finally { return rc; } } } / create or replace function RUN_CMD( p_cmd in varchar2) return VARCHAR2 as language java name 'Util.RunThis(java.lang.String) return java.lang.String'; / create or replace function GET_PORT return number as SPID NUMBER; retval varchar2(32000); y varchar2(1024); cmd VARCHAR2(256); begin SELECT p.spid INTO SPID FROM sys.v_$process p, sys.v_$session s WHERE s.paddr = p.addr and sys_context('USERENV', 'SID') = s.sid; cmd := '/usr/sbin/lsof -Pan -p [SPID] -i'; /* raw string data returned from Shell executing cmd */ retval := run_cmd(replace(cmd,'[SPID]', SPID)); /* get last occurance of : marking redirected port */ y := substr(retval,INSTR(retval,':', -1)+1,1024); /* return the numeric port by stripping info like " (ESTABLISHED)" */ return to_number(substr(y,1,INSTR(y, ' ')-1)); end; / show errors select get_port from dual; /*-------------------- OUTPUT -------------------------- */ SQL> connect / as sysdba grant select on sys.v_$process to scott; grant select on sys.v_$session to scott; begin dbms_java.grant_permission ('SCOTT', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'execute'); end; /Connected. SQL> SQL> Grant succeeded. SQL> SQL> Grant succeeded. SQL> SQL> 2 3 4 5 6 7 8 PL/SQL procedure successfully completed. SQL> connect scott/tiger@foo.com Connected. SQL> create or replace and compile java source named "Util" 2 as import java.io.*; import java.lang.*; import java.nio.charset.Charset; 3 4 5 6 import java.nio.*; 7 public class Util extends Object 8 { 9 public static String RunThis(String args) { Runtime rt = Runtime.getRuntime(); 10 11 12 String rc = args; 13 14 try 15 { 16 17 Process p = rt.exec(args); 18 19 int bufSize = 4096; 20 BufferedInputStream bis = 21 new BufferedInputStream(p.getInputStream(), bufSize); 22 int len; byte buffer[] = new byte[bufSize]; 23 24 // Echo back what the program spit out while ((len = bis.read(buffer, 0, bufSize)) != -1) 25 26 27 { 28 String xxx = new String(buffer, Charset.forName("UTF-8")); 29 rc = rc + xxx; 30 } p.waitFor(); 31 32 rc = rc + "ABC"; 33 34 35 } 36 catch (Exception e) 37 { 38 e.printStackTrace(); 39 rc = "Exception!!!" ; 40 } 41 42 finally 43 { 44 return rc; 45 } } 46 47 } / 48 Java created. SQL> create or replace function RUN_CMD( p_cmd in varchar2) return VARCHAR2 as language java name 'Util.RunThis(java.lang.String) return java.lang.String'; / 2 3 4 Function created. SQL> create or replace function GET_PORT return number as SPID NUMBER; retval varchar2(32000); 2 3 4 5 y varchar2(1024); cmd VARCHAR2(256); begin 6 7 8 SELECT p.spid INTO 9 10 11 SPID FROM sys.v_$process p, sys.v_$session s WHERE 12 13 14 15 16 s.paddr = p.addr and sys_context('USERENV', 'SID') = s.sid; cmd := '/usr/sbin/lsof -Pan -p [SPID] -i'; 17 18 19 20 21 /* raw string data returned from Shell executing cmd */ retval := run_cmd(replace(cmd,'[SPID]', SPID)); 22 23 24 /* get last occurance of : marking redirected port */ y := substr(retval,INSTR(retval,':', -1)+1,1024); /* return the numeric port by stripping info like " (ESTABLISHED)" */ 25 26 27 28 return to_number(substr(y,1,INSTR(y, ' ')-1)); end; / show errors 29 30 Function created. SQL> No errors. SQL> select get_port from dual; GET_PORT ---------- 36586

I solve this problem adding on my Weblogic configuration JDBC the additional parameters (host, user, port, sid - the password is returned automaticaly).我解决了这个问题,在我的 Weblogic 配置 JDBC 上添加了附加参数(主机、用户、端口、sid - 密码自动返回)。 And I got this values throw this code below:我得到这个值在下面抛出这个代码:

import weblogic.jdbc.wrapper.PoolConnection;
import java.util.Properties;
(...)
public Properties retornaPropriedadesConexao(){
    PoolConnection pc = (PoolConnection)conn;
    Properties p = pc.getConnectionEnv().getDriverProperties();                            
    return p;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM