View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.transaction.xa.jta.connection.dialect;
19  
20  import lombok.SneakyThrows;
21  import org.apache.shardingsphere.transaction.xa.jta.connection.XAConnectionWrapper;
22  
23  import javax.sql.XAConnection;
24  import javax.sql.XADataSource;
25  import java.lang.reflect.Constructor;
26  import java.sql.Connection;
27  import java.sql.SQLException;
28  import java.util.Properties;
29  
30  /**
31   * XA connection wrapper for Oracle.
32   */
33  public final class OracleXAConnectionWrapper implements XAConnectionWrapper {
34      
35      private Class<Connection> jdbcConnectionClass;
36      
37      private Constructor<?> xaConnectionConstructor;
38      
39      @Override
40      public XAConnection wrap(final XADataSource xaDataSource, final Connection connection) throws SQLException {
41          return createXAConnection(connection.unwrap(jdbcConnectionClass));
42      }
43      
44      @Override
45      public void init(final Properties props) {
46          loadReflection();
47      }
48      
49      private void loadReflection() {
50          jdbcConnectionClass = getJDBCConnectionClass();
51          xaConnectionConstructor = getXAConnectionConstructor();
52      }
53      
54      @SuppressWarnings("unchecked")
55      @SneakyThrows(ReflectiveOperationException.class)
56      private Class<Connection> getJDBCConnectionClass() {
57          return (Class<Connection>) Class.forName("oracle.jdbc.internal.OracleConnection");
58      }
59      
60      @SneakyThrows(ReflectiveOperationException.class)
61      private Constructor<?> getXAConnectionConstructor() {
62          return Class.forName("oracle.jdbc.xa.client.OracleXAConnection").getConstructor(Connection.class);
63      }
64      
65      @SneakyThrows(ReflectiveOperationException.class)
66      private XAConnection createXAConnection(final Connection connection) {
67          return (XAConnection) xaConnectionConstructor.newInstance(connection);
68      }
69      
70      @Override
71      public String getDatabaseType() {
72          return "Oracle";
73      }
74  }