/
DriverBase.java
467 lines (426 loc) · 21.8 KB
/
DriverBase.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/*
╔════════════════════════════════════════════════════════════════════════════════════╗
║ ║
║ Copyright (c) 2020-24 https://prrvchr.github.io ║
║ ║
║ Permission is hereby granted, free of charge, to any person obtaining ║
║ a copy of this software and associated documentation files (the "Software"), ║
║ to deal in the Software without restriction, including without limitation ║
║ the rights to use, copy, modify, merge, publish, distribute, sublicense, ║
║ and/or sell copies of the Software, and to permit persons to whom the Software ║
║ is furnished to do so, subject to the following conditions: ║
║ ║
║ The above copyright notice and this permission notice shall be included in ║
║ all copies or substantial portions of the Software. ║
║ ║
║ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ║
║ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ║
║ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ║
║ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ║
║ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ║
║ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE ║
║ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ║
║ ║
╚════════════════════════════════════════════════════════════════════════════════════╝
*/
package io.github.prrvchr.uno.sdbc;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ServiceLoader;
import com.sun.star.beans.PropertyValue;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.container.XHierarchicalNameAccess;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.logging.LogLevel;
import com.sun.star.sdbc.DriverPropertyInfo;
import com.sun.star.sdbc.SQLException;
import com.sun.star.sdbc.XConnection;
import com.sun.star.sdbc.XDriver;
import com.sun.star.uno.Any;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XMacroExpander;
import com.sun.star.lib.uno.helper.ComponentBase;
import io.github.prrvchr.uno.helper.ResourceBasedEventLogger;
import io.github.prrvchr.uno.helper.ServiceInfo;
import io.github.prrvchr.uno.helper.SharedResources;
import io.github.prrvchr.uno.helper.UnoHelper;
import io.github.prrvchr.uno.logging.UnoLoggerPool;
import io.github.prrvchr.jdbcdriver.ConnectionService;
import io.github.prrvchr.jdbcdriver.DriverProvider;
import io.github.prrvchr.jdbcdriver.DriverProviderDefault;
import io.github.prrvchr.jdbcdriver.DriverWrapper;
import io.github.prrvchr.jdbcdriver.Resources;
import io.github.prrvchr.jdbcdriver.StandardSQLState;
import io.github.prrvchr.jdbcdriver.helper.DBTools;
public abstract class DriverBase
extends ComponentBase
implements XServiceInfo,
XDriver
{
private final String m_service;
private final String[] m_services;
private XComponentContext m_xContext;
private XHierarchicalNameAccess m_xConfig;
private static final String m_connectProtocol = "jdbc:";
private static final String m_registredProtocol = "xdbc:";
private static final String m_driverClassPath = "JavaDriverClassPath";
private static final String m_driverClass = "JavaDriverClass";
private static final String m_expandSchema = "vnd.sun.star.expand:";
public static final String m_identifier = "io.github.prrvchr.jdbcDriverOOo";
private final boolean m_enhanced;
protected final ResourceBasedEventLogger m_logger;
// The constructor method:
public DriverBase(final XComponentContext context,
final String service,
final String[] services,
boolean enhanced)
throws Exception
{
m_xContext = context;
m_service = service;
m_services = services;
m_enhanced = enhanced;
m_xConfig = _getDriverConfiguration("org.openoffice.Office.DataAccess.Drivers");
System.out.println("sdbc.DriverBase.DriverBase() 1");
SharedResources.registerClient(context, m_identifier, "resource", "Driver");
m_logger = new ResourceBasedEventLogger(context, m_identifier, "resource", "Driver", "io.github.prrvchr.jdbcDriverOOo.Driver");
UnoLoggerPool.initialize(context, m_identifier);
System.out.println("sdbc.DriverBase.DriverBase() 2");
}
private XHierarchicalNameAccess _getDriverConfiguration(String path)
throws Exception
{
return UnoHelper.getConfiguration(m_xContext, path);
}
public final XComponentContext getComponentContext() {
return m_xContext;
}
// com.sun.star.lang.XComponent:
@Override
protected synchronized void postDisposing() {
m_xContext = null;
SharedResources.revokeClient();
UnoHelper.disposeComponent(m_xConfig);
}
// com.sun.star.lang.XServiceInfo:
@Override
public String getImplementationName()
{
return ServiceInfo.getImplementationName(m_service);
}
@Override
public String[] getSupportedServiceNames()
{
return ServiceInfo.getSupportedServiceNames(m_services);
}
@Override
public boolean supportsService(String service)
{
return ServiceInfo.supportsService(m_services, service);
}
// com.sun.star.sdbc.XDriver:
public XConnection connect(String url,
PropertyValue[] info)
throws SQLException
{
ConnectionBase connection = null;
m_logger.logprb(LogLevel.INFO, Resources.STR_LOG_DRIVER_CONNECTING_URL, url);
if (acceptsURL(url)) {
DriverProvider provider = _getDriverProvider(url, info);
String location = url.replaceFirst(m_registredProtocol, m_connectProtocol);
String level = provider.getDriverStringProperty(m_xConfig, "DriverLoggerLevel", "-1");
if (!_isDriverRegistered(location)) {
provider.setSystemProperties(level);
_registerDriver(_getUrlProtocol(url), info);
}
System.out.println("sdbc.DriverBase.connect() 1");
XHierarchicalNameAccess config;
try {
config = UnoHelper.getConfiguration(m_xContext, m_identifier);
}
catch (Exception e) {
throw new SQLException(e.getMessage(), this, StandardSQLState.SQL_GENERAL_ERROR.text(), 0, Any.VOID);
}
try {
provider.setConnection(m_logger, m_xConfig, config, m_enhanced, location, info, level);
}
catch(java.sql.SQLException e) {
int resource = Resources.STR_LOG_NO_SYSTEM_CONNECTION;
String msg = SharedResources.getInstance().getResourceWithSubstitution(resource, location);
throw DBTools.getSQLException(msg, this, StandardSQLState.SQL_UNABLE_TO_CONNECT.text(), 0, e);
}
String service = ConnectionService.CSS_SDBC_CONNECTION.service();
service = UnoHelper.getConfigurationOption(config, "ConnectionService", service);
UnoHelper.disposeComponent(config);
System.out.println("sdbc.DriverBase.connect() 2 Name: " + service);
service = UnoHelper.getDefaultPropertyValue(info, "ConnectionService", service);
System.out.println("sdbc.DriverBase.connect() 3 Service: " + service);
connection = _getConnection(m_xContext, provider, url, info, ConnectionService.fromString(service));
m_logger.logprb(LogLevel.INFO, Resources.STR_LOG_DRIVER_SUCCESS, connection.getProvider().getLogger().getObjectId());
System.out.println("sdbc.DriverBase.connect() 4");
}
return connection;
}
private String _getUrlProtocol(final String url)
{
String protocol = String.join(":", Arrays.copyOfRange(url.split(":"), 0, 2));
return protocol + ":*";
}
private boolean _isDriverRegistered(String url)
{
try {
java.sql.DriverManager.getDriver(url);
return true;
}
catch (java.sql.SQLException e) {}
return false;
}
private void _registerDriver(final String protocol,
final PropertyValue[] info)
throws SQLException
{
System.out.println("sdbc.DriverBase._registerDriver() 1");
final String clazz = _getDriverClass(protocol, info);
URL path = _getDriverClassPath(protocol, info);
System.out.println("sdbc.DriverBase._registerDriver() 2 url: '" + path + "' name: '" + clazz + "'");
if (path != null && !clazz.isBlank()) {
System.out.println("sdbc.DriverBase._registerDriver() 3");
if (!_registerDriver(path, clazz)) {
System.out.println("sdbc.DriverBase._registerDriver() 4");
_registerDriver(clazz);
}
}
System.out.println("sdbc.DriverBase._registerDriver() 5");
}
private String _getDriverClass(final String protocol,
final PropertyValue[] info)
throws SQLException
{
String clazz = null;
try {
System.out.println("sdbc.DriverBase._getDriverClass() 1");
clazz = UnoHelper.getDefaultPropertyValue(info, m_driverClass, "");
System.out.println("sdbc.DriverBase._getDriverClass() 2");
if (clazz.isBlank()) {
final String property = "Installed/" + protocol + "/Properties/" + m_driverClass + "/Value";
if (m_xConfig.hasByHierarchicalName(property)) {
System.out.println("sdbc.DriverBase._getDriverClass() 3");
clazz = (String) m_xConfig.getByHierarchicalName(property);
}
}
return clazz;
}
catch (NoSuchElementException e) {
int resource = Resources.STR_LOG_NO_DRIVER_CLASS;
String msg = SharedResources.getInstance().getResourceWithSubstitution(resource, protocol, clazz);
throw DBTools.getSQLException(msg, this, StandardSQLState.SQL_UNABLE_TO_CONNECT.text(), 0, e);
}
}
private URL _getDriverClassPath(final String protocol,
final PropertyValue[] info)
throws SQLException
{
String url = null;
try {
url = UnoHelper.getDefaultPropertyValue(info, m_driverClassPath, "");
if (url.isBlank()) {
final String property = "Installed/" + protocol + "/Properties/" + m_driverClassPath + "/Value";
if (m_xConfig.hasByHierarchicalName(property)) {
url = (String) m_xConfig.getByHierarchicalName(property);
}
}
if (!url.isBlank()) {
return _getDriverClassPathUrl(expandDriverClassPath(url));
}
return null;
}
catch (NoSuchElementException e) {
int resource = Resources.STR_LOG_NO_DRIVER_CLASS;
String msg = SharedResources.getInstance().getResourceWithSubstitution(resource, protocol, url);
throw DBTools.getSQLException(msg, this, StandardSQLState.SQL_UNABLE_TO_CONNECT.text(), 0, e);
}
}
private String expandDriverClassPath(String url)
{
if (url.startsWith(m_expandSchema)) {
Object service = m_xContext.getValueByName("/singletons/com.sun.star.util.theMacroExpander");
XMacroExpander expander = (XMacroExpander) UnoRuntime.queryInterface(XMacroExpander.class, service);
url = expander.expandMacros(url.replaceFirst(m_expandSchema, ""));
}
return url;
}
private URL _getDriverClassPathUrl(String location)
throws SQLException
{
URL url = null;
try {
url = new URL("jar:" + location + "!/");
}
catch (java.net.MalformedURLException e) {
throw UnoHelper.getSQLException(UnoHelper.getSQLException(e), this);
}
return url;
}
private boolean _registerDriver(URL url, String name)
throws SQLException
{
java.sql.Driver driver = null;
boolean registered = false;
try {
// XXX: Pick your JDBC driver at runtime: https://www.kfu.com/~nsayer/Java/dyn-jdbc.html
Class<?> clazz = Class.forName(name, true, new URLClassLoader(new URL[] {url}, DriverBase.class.getClassLoader()));
driver = new DriverWrapper((java.sql.Driver) clazz.getDeclaredConstructor().newInstance());
}
catch(ClassNotFoundException | NoSuchMethodException |
InstantiationException | InvocationTargetException | IllegalAccessException e) {
throw UnoHelper.getSQLException(UnoHelper.getSQLException(e), this);
}
try {
DriverManager.registerDriver(driver);
registered = true;
System.out.println("sdbc.DriverBase._registerDriver: " + name);
}
catch (java.sql.SQLException e) {
throw UnoHelper.getSQLException(e, this);
}
return registered;
}
private void _registerDriver(String name)
throws SQLException
{
java.sql.Driver driver = null;
try {
driver = (java.sql.Driver) Class.forName(name).getDeclaredConstructor().newInstance();
}
catch(ClassNotFoundException | NoSuchMethodException |
InstantiationException | InvocationTargetException | IllegalAccessException e) {
throw UnoHelper.getSQLException(UnoHelper.getSQLException(e), this);
}
if (driver != null) {
try {
DriverManager.registerDriver(driver);
System.out.println("sdbc.DriverBase._registerDriver(name) 1");
}
catch (java.sql.SQLException e) {
throw UnoHelper.getSQLException(e, this);
}
}
}
public boolean acceptsURL(String url)
throws SQLException
{
return url.startsWith(m_registredProtocol) && hasSubProtocol(url);
}
private boolean hasSubProtocol(String url)
{
String[] protocol = url.split(":");
return (protocol.length > 1 && !protocol[1].isBlank());
}
private String getProtocol(String url)
{
String protocol = m_registredProtocol;
if (hasSubProtocol(url)) {
protocol += url.split(":")[1];
}
return protocol;
}
public DriverPropertyInfo[] getPropertyInfo(String url, PropertyValue[] infos)
throws SQLException
{
if (!acceptsURL(url)) {
String message = SharedResources.getInstance().getResourceWithSubstitution(Resources.STR_URI_SYNTAX_ERROR, url);
throw new SQLException(message, this, StandardSQLState.SQL_GENERAL_ERROR.text(), 0, Any.VOID);
}
List<DriverPropertyInfo> properties = new ArrayList<DriverPropertyInfo>();
try {
String protocol = getProtocol(url);
for (PropertyValue info : infos) {
String path = DriverProvider.getDriverPropertiesInfo(protocol, info.Name);
if (m_xConfig.hasByHierarchicalName(path)) {
String value = null;
Object[] values = null;
switch (info.Name) {
case "AutoIncrementCreation":
value = (String) m_xConfig.getByHierarchicalName(path);
String[] choices = {value, };
properties.add(new DriverPropertyInfo("AutoIncrementCreation", "Auto-increment creation statement.", true, value, choices));
break;
case "RowVersionCreation":
values = (Object[]) m_xConfig.getByHierarchicalName(path);
value = (String) values[0];
properties.add(new DriverPropertyInfo("RowVersionCreation", "Row version creation statement.", true, value, (String[]) values));
break;
case "TypeInfoSettings":
values = (Object[]) m_xConfig.getByHierarchicalName(path);
value = (String) values[0];
properties.add(new DriverPropertyInfo("TypeInfoSettings", "Defines how the type info of the database metadata should be manipulated.", true, "", (String[]) values));
break;
case "TablePrivilegesSettings":
values = (Object[]) m_xConfig.getByHierarchicalName(path);
value = (String) values[0];
properties.add(new DriverPropertyInfo("TablePrivilegesSettings", "Lists privileges supported by the underlying driver.", true, value, (String[]) values));
break;
}
}
}
} catch (NoSuchElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
String[] boolchoices = {"false", "true"};
String row = "GENERATED ALWAYS AS ROW START";
String[] rows = {"GENERATED ALWAYS AS ROW START", "GENERATED ALWAYS AS ROW END"};
// XXX: Name, Description, IsRequired, Value, Choices
properties.add(new DriverPropertyInfo("JavaDriverClass", "The JDBC driver class name.", true, "", new String[0]));
properties.add(new DriverPropertyInfo("JavaDriverClassPath", "The class path where to look for the JDBC driver.", true, "", new String[0]));
properties.add(new DriverPropertyInfo("SystemProperties", "Additional properties to set at java.lang.System before loading the driver.", true, "", new String[0]));
properties.add(new DriverPropertyInfo("ParameterNameSubstitution", "Change named parameters with '?'.", false, "false", boolchoices.clone()));
properties.add(new DriverPropertyInfo("IsAutoRetrievingEnabled", "Retrieve generated values.", false, "false", boolchoices.clone()));
properties.add(new DriverPropertyInfo("AutoRetrievingStatement", "getGeneratedKey() statement.", false, "", new String[0]));
properties.add(new DriverPropertyInfo("GenerateASBeforeCorrelationName", "Generate AS before table correlation names.", false, "true", boolchoices.clone()));
properties.add(new DriverPropertyInfo("IgnoreCurrency", "Ignore the currency field from the ResultsetMetaData.", false, "false", boolchoices.clone()));
properties.add(new DriverPropertyInfo("EscapeDateTime", "Escape date time format.", false, "true", boolchoices.clone()));
properties.add(new DriverPropertyInfo("ImplicitCatalogRestriction", "The catalog which should be used in getTables calls, when the caller passed NULL.", false, "", new String[0]));
properties.add(new DriverPropertyInfo("ImplicitSchemaRestriction", "The schema which should be used in getTables calls, when the caller passed NULL.", false, "", new String[0]));
properties.add(new DriverPropertyInfo("AutoIncrementCreation", "Auto-increment creation statement.", true, "", new String[0]));
properties.add(new DriverPropertyInfo("RowVersionCreation", "Row version creation statement.", true, row, rows.clone()));
properties.add(new DriverPropertyInfo("IgnoreDriverPrivileges", "Ignore the privileges from the database driver.", false, "false", boolchoices.clone()));
properties.add(new DriverPropertyInfo("AddIndexAppendix", "Add an appendix (ASC or DESC) when creating the index.", true, "false", boolchoices.clone()));
properties.add(new DriverPropertyInfo("TypeInfoSettings", "Defines how the type info of the database metadata should be manipulated.", true, "", new String[0]));
properties.add(new DriverPropertyInfo("TablePrivilegesSettings", "Lists privileges supported by the underlying driver.", true, "", new String[0]));
*/
return properties.toArray(new DriverPropertyInfo[0]);
}
public int getMajorVersion()
{
return 1;
}
public int getMinorVersion()
{
return 0;
}
private DriverProvider _getDriverProvider(String url,
PropertyValue[] info)
{
ServiceLoader<DriverProvider> loader = ServiceLoader.load(DriverProvider.class, ConnectionBase.class.getClassLoader());
for (final DriverProvider provider : loader) {
if (provider.acceptsURL(url)) {
return provider;
}
}
return new DriverProviderDefault(url, info);
}
abstract protected ConnectionBase _getConnection(XComponentContext ctx,
DriverProvider provider,
String url,
PropertyValue[] info,
ConnectionService service);
}