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

huangapple go评论117阅读模式
英文:

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

问题

我有一个Oracle连接(存储在java.sql.Connection对象中),这个连接是从一个属性文件(ApplicationResources.properties)中获取的。

我该如何获取关于主机、端口、SID、用户名和密码的信息?(我需要这些信息来通过我的Java应用程序调用特定的数据库函数)

以下是我的代码:

  1. private void connectToDatabase() {
  2. ServiceLocator sl = new ServiceLocator();
  3. InitialContext ic = null;
  4. DataSource dataSource = null;
  5. try {
  6. if (conn == null) {
  7. ic = new InitialContext();
  8. dataSource = (DataSource) ic.lookup(sl.getInfo().getString("JNDI"));
  9. conn = dataSource.getConnection();
  10. conn.setAutoCommit(true);
  11. // 我需要主机、端口、SID和密码信息
  12. System.out.println("USER " + conn.getMetaData().getUserName());
  13. }
  14. } catch (SQLException e) {
  15. logger.error("Error while trying to open database connection.", e);
  16. } catch (NamingException e) {
  17. logger.error("Error while trying to open database connection.", e);
  18. }
  19. if (conn != null)
  20. rastrear.definePredicate(conn);
  21. }
英文:

I have an Oracle connection (in a java.sql.Connection object) that is mounted from a properties file (ApplicationResources.properties).

How do I capture information about host, port, sid, user and password? (I need this information to call a specific database function through my java application)

Below my code:

  1. private void conectaBanco() {
  2. ServiceLocator sl = new ServiceLocator();
  3. InitialContext ic = null;
  4. DataSource dataSource = null;
  5. try {
  6. if (conn == null) {
  7. ic = new InitialContext();
  8. dataSource = (DataSource) ic.lookup(sl.getInfo().getString("JNDI"));
  9. conn = dataSource.getConnection();
  10. conn.setAutoCommit( true );
  11. // I need host, port, sid and password information
  12. System.out.println("USER " + conn.getMetaData().getUserName());
  13. }
  14. } catch (SQLException e) {
  15. logger.error("Erro ao tentar abrir conexao com o banco de dados.", e);
  16. } catch (NamingException e) {
  17. logger.error("Erro ao tentar abrir conexao com o banco de dados.", e);
  18. }
  19. if(conn != null)
  20. rastrear.definePredicate(conn);
  21. }

答案1

得分: 0

  1. SESSION SID:
  2. SELECT sys_context('USERENV', 'SID') FROM DUAL;
  3. ORACLE_SID:
  4. SELECT sys_context('userenv','instance_name') FROM dual;
  5. HOST (Database machine) :
  6. SELECT UTL_INADDR.get_host_name FROM dual;
  7. Password: See [http://www.dba-oracle.com/t_password_storage.htm][1]
  8. CLIENT SIDE Port:
  9. Select port from v$session;
  10. SERVER OS PID of Oracle server process connected to client process
  11. SELECT p.spid
  12. FROM v$process p, v$session s
  13. WHERE s.paddr = p.addr and
  14. sys_context('USERENV', 'SID') = s.sid;
  15. Server side port:
  16. 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)
  17. Below code
  18. - grants required privileges
  19. - defines a java stored function "Util.RunThis" which executes on database server a OS command passed into function and return string.
  20. - "Util.RunThis" is mapped to PL/SQL function "RUN_CMD"
  21. - "GET_PORT" is a PL/SQL function returning a numeric value of the used Port of the database server process connected to client session. Inside GET_PORT the SELECT is used to determine database server process pid replacing [SPID] in command below
  22. /usr/sbin/lsof -Pan -p [SPID] -i
  23. - finally invoking a simple select we get the Port of database server process attached to current session
  24. connect / as sysdba
  25. grant select on sys.v_$process to scott;
  26. grant select on sys.v_$session to scott;
  27. begin
  28. dbms_java.grant_permission
  29. ('SCOTT',
  30. 'SYS:java.io.FilePermission',
  31. '<<ALL FILES>>',
  32. 'execute');
  33. end;
  34. /
  35. connect scott/tiger@foo.com
  36. create or replace and compile java source named "Util"
  37. as
  38. import java.io.*;
  39. import java.lang.*;
  40. import java.nio.charset.Charset;
  41. import java.nio.*;
  42. public class Util extends Object
  43. {
  44. public static String RunThis(String args)
  45. {
  46. Runtime rt = Runtime.getRuntime();
  47. String rc = args;
  48. try
  49. {
  50. Process p = rt.exec(args);
  51. int bufSize = 4096;
  52. BufferedInputStream bis =
  53. new BufferedInputStream(p.getInputStream(), bufSize);
  54. int len;
  55. byte buffer[] = new byte[bufSize];
  56. // Echo back what the program spit out
  57. while ((len = bis.read(buffer, 0, bufSize)) != -1)
  58. {
  59. String xxx = new String(buffer, Charset.forName("UTF-8"));
  60. rc = rc + xxx;
  61. }
  62. p.waitFor();
  63. rc = rc + "ABC";
  64. }
  65. catch (Exception e)
  66. {
  67. e.printStackTrace();
  68. rc = "Exception!!!";
  69. }
  70. finally
  71. {
  72. return rc;
  73. }
  74. }
  75. }
  76. /
  77. create or replace function RUN_CMD( p_cmd in varchar2) return VARCHAR2
  78. as language java
  79. name 'Util.RunThis(java.lang.String) return java.lang.String';
  80. /
  81. create or replace function GET_PORT return number
  82. as
  83. SPID NUMBER;
  84. retval varchar2(32000);
  85. y varchar2(1024);
  86. cmd VARCHAR2(256);
  87. begin
  88. SELECT
  89. p.spid
  90. INTO
  91. SPID
  92. FROM
  93. sys.v_$process p,
  94. sys.v_$session s
  95. WHERE
  96. s.paddr = p.addr and
  97. sys_context('USERENV', 'SID') = s.sid;
  98. cmd := '/usr/sbin/lsof -Pan -p [SPID] -i';
  99. /* raw string data returned from Shell executing cmd */
  100. retval := run_cmd(replace(cmd,'[SPID]', SPID));
  101. /* get last occurance of : marking redirected port */
  102. y := substr(retval,INSTR(retval,':', -1)+1,1024);
  103. /* return the numeric port by stripping info like " (ESTABLISHED)" */
  104. return to_number(substr(y,1,INSTR(y, ' ')-1));
  105. end;
  106. /
  107. show errors
  108. select get_port from dual;
  109. /*-------------------- OUTPUT -------------------------- */
  110. SQL> connect / as sysdba
  111. grant select on sys.v_$process to scott;
  112. grant select on sys.v_$session to scott;
  113. begin
  114. dbms_java.grant_permission
  115. ('SCOTT',
  116. 'SYS:java.io.FilePermission',
  117. '<<ALL FILES>>',
  118. 'execute');
  119. end;
  120. /Connected.
  121. SQL> SQL>
  122. Grant succeeded.
  123. SQL> SQL>
  124. Grant succeeded.
  125. SQL> SQL> 2 3 4 5 6 7 8
  126. PL/SQL procedure successfully completed.
  127. SQL> connect scott/tiger@foo.com
  128. Connected.
  129. SQL> create or replace and compile java source named "Util"
  130. 2 as
  131. import java.io.*;
  132. import java.lang.*;
  133. import java.nio.charset.Charset;
  134. 3 4 5 6 import java.nio.*;
  135. 7 public class Util extends Object
  136. 8 {
  137. 9 public static String RunThis(String args)
  138. {
  139. Runtime rt = Runtime.getRuntime();
  140. 10 11 12 String rc = args;
  141. 13
  142. 14 try
  143. 15 {
  144. 16
  145. 17 Process p = rt.exec(args);
  146. 18 19 int bufSize = 4096;
  147. 20 BufferedInputStream bis =
  148. 21 new BufferedInputStream(p.getInputStream(), bufSize);
  149. 22 int len;
  150. byte buffer[] = new byte[bufSize];
  151. 23 24
  152. // Echo back what the program spit out
  153. while ((len = bis.read(buffer, 0, bufSize)) != -1)
  154. 25 26 27 {
  155. 28 String xxx = new String(buffer, Charset.forName("UTF-8"));
  156. 29 rc = rc + xxx;
  157. 30 }
  158. p.waitFor();
  159. 31 32
  160. rc = rc + "ABC";
  161. 33 34 35 }
  162. 36 catch (Exception e)
  163. 37 {
  164. 38 e.printStackTrace();
  165. 39 rc = "Exception!!!" ;
  166. 40 }
  167. 41
  168. 42 finally
  169. 43 {
  170. 44 return rc;
  171. 45 }
  172. }
  173. 46 47 }
  174. / 48
  175. Java created.
  176. SQL> create or replace function RUN_CMD( p_cmd in varchar2) return VARCHAR2
  177. as language java
  178. name 'Util.RunThis(java.lang.String) return java.lang.String';
  179. / 2 3 4
  180. Function created.
  181. <details>
  182. <summary>英文:</summary>
  183. SESSION SID:
  184. SELECT sys_context(&#39;USERENV&#39;, &#39;SID&#39;) FROM DUAL;
  185. ORACLE_SID:
  186. SELECT sys_context(&#39;userenv&#39;,&#39;instance_name&#39;) FROM dual;
  187. HOST (Database machine) :
  188. SELECT UTL_INADDR.get_host_name FROM dual;
  189. Password: See [http://www.dba-oracle.com/t_password_storage.htm][1]
  190. CLIENT SIDE Port:
  191. Select port from v$session;
  192. SERVER OS PID of Oracle server process connected to client process
  193. SELECT p.spid
  194. FROM v$process p, v$session s
  195. WHERE s.paddr = p.addr and
  196. sys_context(&#39;USERENV&#39;, &#39;SID&#39;) = s.sid;
  197. Server side port:
  198. 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)
  199. Below code
  200. - grants required privileges
  201. - defines a java stored function &quot;Util.RunThis&quot; which executes on database server a OS command passed into function and return string.
  202. - &quot;Util.RunThis&quot; is mapped to PL/SQL function &quot;RUN_CMD&quot;
  203. - &quot;GET_PORT&quot; is a PL/SQL function returning a numeric value of the used Port of the database server process connected to client session. Inside GET_PORT the SELECT is used to determine database server process pid replacing [SPID] in command below
  204. /usr/sbin/lsof -Pan -p [SPID] -i
  205. - finally invoking a simple select we get the Port of database server process attached to current session
  206. connect / as sysdba
  207. grant select on sys.v_$process to scott;
  208. grant select on sys.v_$session to scott;
  209. begin
  210. dbms_java.grant_permission
  211. (&#39;SCOTT&#39;,
  212. &#39;SYS:java.io.FilePermission&#39;,
  213. &#39;&lt;&lt;ALL FILES&gt;&gt;&#39;,
  214. &#39;execute&#39;);
  215. end;
  216. /
  217. connect scott/tiger@foo.com
  218. create or replace and compile java source named &quot;Util&quot;
  219. as
  220. import java.io.*;
  221. import java.lang.*;
  222. import java.nio.charset.Charset;
  223. import java.nio.*;
  224. public class Util extends Object
  225. {
  226. public static String RunThis(String args)
  227. {
  228. Runtime rt = Runtime.getRuntime();
  229. String rc = args;
  230. try
  231. {
  232. Process p = rt.exec(args);
  233. int bufSize = 4096;
  234. BufferedInputStream bis =
  235. new BufferedInputStream(p.getInputStream(), bufSize);
  236. int len;
  237. byte buffer[] = new byte[bufSize];
  238. // Echo back what the program spit out
  239. while ((len = bis.read(buffer, 0, bufSize)) != -1)
  240. {
  241. String xxx = new String(buffer, Charset.forName(&quot;UTF-8&quot;));
  242. rc = rc + xxx;
  243. }
  244. p.waitFor();
  245. rc = rc + &quot;ABC&quot;;
  246. }
  247. catch (Exception e)
  248. {
  249. e.printStackTrace();
  250. rc = &quot;Exception!!!&quot; ;
  251. }
  252. finally
  253. {
  254. return rc;
  255. }
  256. }
  257. }
  258. /
  259. create or replace function RUN_CMD( p_cmd in varchar2) return VARCHAR2
  260. as language java
  261. name &#39;Util.RunThis(java.lang.String) return java.lang.String&#39;;
  262. /
  263. create or replace function GET_PORT return number
  264. as
  265. SPID NUMBER;
  266. retval varchar2(32000);
  267. y varchar2(1024);
  268. cmd VARCHAR2(256);
  269. begin
  270. SELECT
  271. p.spid
  272. INTO
  273. SPID
  274. FROM
  275. sys.v_$process p,
  276. sys.v_$session s
  277. WHERE
  278. s.paddr = p.addr and
  279. sys_context(&#39;USERENV&#39;, &#39;SID&#39;) = s.sid;
  280. cmd := &#39;/usr/sbin/lsof -Pan -p [SPID] -i&#39;;
  281. /* raw string data returned from Shell executing cmd */
  282. retval := run_cmd(replace(cmd,&#39;[SPID]&#39;, SPID));
  283. /* get last occurance of : marking redirected port */
  284. y := substr(retval,INSTR(retval,&#39;:&#39;, -1)+1,1024);
  285. /* return the numeric port by stripping info like &quot; (ESTABLISHED)&quot; */
  286. return to_number(substr(y,1,INSTR(y, &#39; &#39;)-1));
  287. end;
  288. /
  289. show errors
  290. select get_port from dual;
  291. /*-------------------- OUTPUT -------------------------- */
  292. SQL&gt; connect / as sysdba
  293. grant select on sys.v_$process to scott;
  294. grant select on sys.v_$session to scott;
  295. begin
  296. dbms_java.grant_permission
  297. (&#39;SCOTT&#39;,
  298. &#39;SYS:java.io.FilePermission&#39;,
  299. &#39;&lt;&lt;ALL FILES&gt;&gt;&#39;,
  300. &#39;execute&#39;);
  301. end;
  302. /Connected.
  303. SQL&gt; SQL&gt;
  304. Grant succeeded.
  305. SQL&gt; SQL&gt;
  306. Grant succeeded.
  307. SQL&gt; SQL&gt; 2 3 4 5 6 7 8
  308. PL/SQL procedure successfully completed.
  309. SQL&gt; connect scott/tiger@foo.com
  310. Connected.
  311. SQL&gt; create or replace and compile java source named &quot;Util&quot;
  312. 2 as
  313. import java.io.*;
  314. import java.lang.*;
  315. import java.nio.charset.Charset;
  316. 3 4 5 6 import java.nio.*;
  317. 7 public class Util extends Object
  318. 8 {
  319. 9 public static String RunThis(String args)
  320. {
  321. Runtime rt = Runtime.getRuntime();
  322. 10 11 12 String rc = args;
  323. 13
  324. 14 try
  325. 15 {
  326. 16
  327. 17 Process p = rt.exec(args);
  328. 18 19 int bufSize = 4096;
  329. 20 BufferedInputStream bis =
  330. 21 new BufferedInputStream(p.getInputStream(), bufSize);
  331. 22 int len;
  332. byte buffer[] = new byte[bufSize];
  333. 23 24
  334. // Echo back what the program spit out
  335. while ((len = bis.read(buffer, 0, bufSize)) != -1)
  336. 25 26 27 {
  337. 28 String xxx = new String(buffer, Charset.forName(&quot;UTF-8&quot;));
  338. 29 rc = rc + xxx;
  339. 30 }
  340. p.waitFor();
  341. 31 32
  342. rc = rc + &quot;ABC&quot;;
  343. 33 34 35 }
  344. 36 catch (Exception e)
  345. 37 {
  346. 38 e.printStackTrace();
  347. 39 rc = &quot;Exception!!!&quot; ;
  348. 40 }
  349. 41
  350. 42 finally
  351. 43 {
  352. 44 return rc;
  353. 45 }
  354. }
  355. 46 47 }
  356. / 48
  357. Java created.
  358. SQL&gt; create or replace function RUN_CMD( p_cmd in varchar2) return VARCHAR2
  359. as language java
  360. name &#39;Util.RunThis(java.lang.String) return java.lang.String&#39;;
  361. / 2 3 4
  362. Function created.
  363. SQL&gt; create or replace function GET_PORT return number
  364. as
  365. SPID NUMBER;
  366. retval varchar2(32000);
  367. 2 3 4 5 y varchar2(1024);
  368. cmd VARCHAR2(256);
  369. begin
  370. 6 7 8 SELECT
  371. p.spid
  372. INTO
  373. 9 10 11 SPID
  374. FROM
  375. sys.v_$process p,
  376. sys.v_$session s
  377. WHERE
  378. 12 13 14 15 16 s.paddr = p.addr and
  379. sys_context(&#39;USERENV&#39;, &#39;SID&#39;) = s.sid;
  380. cmd := &#39;/usr/sbin/lsof -Pan -p [SPID] -i&#39;;
  381. 17 18 19 20 21 /* raw string data returned from Shell executing cmd */
  382. retval := run_cmd(replace(cmd,&#39;[SPID]&#39;, SPID));
  383. 22 23 24 /* get last occurance of : marking redirected port */
  384. y := substr(retval,INSTR(retval,&#39;:&#39;, -1)+1,1024);
  385. /* return the numeric port by stripping info like &quot; (ESTABLISHED)&quot; */
  386. 25 26 27 28 return to_number(substr(y,1,INSTR(y, &#39; &#39;)-1));
  387. end;
  388. /
  389. show errors 29 30
  390. Function created.
  391. SQL&gt;
  392. No errors.
  393. SQL&gt; select get_port from dual;
  394. GET_PORT
  395. ----------
  396. 36586
  397. [1]: http://www.dba-oracle.com/t_password_storage.htm
  398. </details>
  399. # 答案2
  400. **得分**: 0
  401. 我通过在我的Weblogic配置JDBC上添加附加参数(主机、用户、端口、SID - 密码会自动返回)来解决了这个问题。我通过下面的代码获得了这些值:
  402. ```java
  403. import weblogic.jdbc.wrapper.PoolConnection;
  404. import java.util.Properties;
  405. (...)
  406. public Properties retornaPropriedadesConexao(){
  407. PoolConnection pc = (PoolConnection)conn;
  408. Properties p = pc.getConnectionEnv().getDriverProperties();
  409. return p;
  410. }
英文:

I solve this problem adding on my Weblogic configuration JDBC the additional parameters (host, user, port, sid - the password is returned automaticaly).
And I got this values throw this code below:

  1. import weblogic.jdbc.wrapper.PoolConnection;
  2. import java.util.Properties;
  3. (...)
  4. public Properties retornaPropriedadesConexao(){
  5. PoolConnection pc = (PoolConnection)conn;
  6. Properties p = pc.getConnectionEnv().getDriverProperties();
  7. return p;
  8. }

huangapple
  • 本文由 发表于 2020年10月7日 22:25:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64246169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定