How do I make uCanAccess use Samba authentication, with special characters in username or password? - java-7

TL;DR: What Database.FileFormat constant should I use for an MS Access 2000-2003 database, when creating the Database object?
I have built a SAMBA test application using jCIFS. It allows me to create/overwrite files if given the correct authentication credentials, regardless of on which PC in the domain I use it.
I also have an application that uses uCanAccess/jackcess to connect to an MDB on a network share. However (from what I understand), it uses the credentials of the logged-in user, a number of whom have read-only access. Only system/network administrators have write permission.
The database in question is not password-protected. (I don't need to enter a password when opening it.)
My intention is to have the app ask for the administrator's Samba credentials before it writes to the DB, using those in the uCanAccess connection, so that it doesn't throw a java.nio.channels.NonWritableChannelException, as per the below stack trace:
java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:747)
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:310)
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:247)
at com.healthmarketscience.jackcess.impl.TableImpl.writeDataPage(TableImpl.java:1980)
at com.healthmarketscience.jackcess.impl.TableImpl.addRows(TableImpl.java:2229)
at com.healthmarketscience.jackcess.impl.TableImpl.addRow(TableImpl.java:2067)
at net.ucanaccess.converters.UcanaccessTable.addRow(UcanaccessTable.java:44)
at net.ucanaccess.commands.InsertCommand.insertRow(InsertCommand.java:101)
at net.ucanaccess.commands.InsertCommand.persist(InsertCommand.java:148)
at net.ucanaccess.jdbc.UcanaccessConnection.flushIO(UcanaccessConnection.java:315)
at net.ucanaccess.jdbc.UcanaccessConnection.commit(UcanaccessConnection.java:205)
at net.ucanaccess.jdbc.AbstractExecute.executeBase(AbstractExecute.java:217)
at net.ucanaccess.jdbc.Execute.execute(Execute.java:46)
at net.ucanaccess.jdbc.UcanaccessPreparedStatement.execute(UcanaccessPreparedStatement.java:228)
at myapp.db.Digger.addTransaction(Digger.java:993)
at myapp.tasks.TransactionRunnable.run(TransactionRunnable.java:42)
at java.lang.Thread.run(Thread.java:745)
Update: I have tried using the smbFileChannel class by Gord Thompson and J. T. Alhborn, shown here. My code, based off the main class shown in that answer, looks like this:
// Ask the user for login credentials and the path to the database
String smbURL = (chosenDir.endsWith("/") ? chosenDir : chosenDir + '/')
+ dbName;
System.out.println("DB Path to use for URL: " + smbURL);
URL u = new URL(smbURL);
try (
// construct the SMB DB URL
SmbFileChannel sfc = new SmbFileChannel(smbURL);
Database db = new DatabaseBuilder().setChannel(sfc)
.setFileFormat(Database.FileFormat.GENERIC_JET4).create();
) {
// Model the table
Table tbl = new TableBuilder("Transactions")
.addColumn(new ColumnBuilder("TransactionID", DataType.LONG).setAutoNumber(true))
.addColumn(new ColumnBuilder("ControllerID", DataType.LONG).setAutoNumber(false))
.addColumn(new ColumnBuilder("ReaderID", DataType.LONG).setAutoNumber(false))
.addColumn(new ColumnBuilder("Event", DataType.LONG).setAutoNumber(false))
.addColumn(new ColumnBuilder("Timestamp", DataType.SHORT_DATE_TIME).setAutoNumber(false))
.addColumn(new ColumnBuilder("Number", DataType.LONG).setAutoNumber(false))
.addIndex(new IndexBuilder(IndexBuilder.PRIMARY_KEY_NAME).addColumns("TransactionID").setPrimaryKey())
.toTable(db);
// Add the row
Map<String, Object> values = new HashMap<>();
values.put("ControllerID", cid);
values.put("ReaderID", rid);
values.put("Event", evtNum);
values.put("Timestamp", ts); // Long; must be converted to DataType.SHORT_DATE_TIME
values.put("Number", accNum);
tbl.addRowFromMap(values);
} catch (IOException IOEx) {
System.err.println(
"Failed to write record to Transactions table in database: "
+ IOEx.getMessage()
);
IOEx.printStackTrace(System.err);
} catch (Exception ex) {
System.err.println(
'[' + ex.getClass().getSimpleName() + "]: Failed to write record to "
+ "Transactions table in database: " + ex.getMessage()
);
ex.printStackTrace(System.err);
}
Executing the above code results in the following output:
DB Path to use for URL: smb://machine.vpnName/Storage/me/dbs/DBName.mdb
Failed to write record to Transactions table in database: Logon failure: account currently disabled.
jcifs.smb.SmbAuthException: Logon failure: account currently disabled.
at jcifs.smb.SmbTransport.checkStatus(SmbTransport.java:546)
at jcifs.smb.SmbTransport.send(SmbTransport.java:663)
at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:390)
at jcifs.smb.SmbSession.send(SmbSession.java:218)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:176)
at jcifs.smb.SmbFile.doConnect(SmbFile.java:911)
at jcifs.smb.SmbFile.connect(SmbFile.java:957)
at jcifs.smb.SmbFile.connect0(SmbFile.java:880)
at jcifs.smb.SmbFile.open0(SmbFile.java:975)
at jcifs.smb.SmbFile.open(SmbFile.java:1009)
at jcifs.smb.SmbRandomAccessFile.<init>(SmbRandomAccessFile.java:57)
at jcifs.smb.SmbRandomAccessFile.<init>(SmbRandomAccessFile.java:42)
at samba.SmbFileChannel.<init>(SmbFileChannel.java:30)
at samba.SambaLanWriteTest.writeTest(SambaLanWriteTest.java:130)
at samba.SambaLanWriteTest.main(SambaLanWriteTest.java:181)
I have write access to a test copy of the database file in question when using Windows File Explorer. I am choosing that one when prompted.
Update 2: I realised that I neglected to add my username and password to the smb:// URL, as Thompson's example shows. I changed to code to this:
String smbCred = "smb://" + auth.getUsername() + ":" + auth.getPassword() + "#",
fixer = chosenDir.replace("\\", "/").replace("smb://", smbCred),
smbURL = fixer + dbName;
System.out.println("DB Path to use for URL: " + smbURL);
// URL u = new URL(smbURL);
The next problem I had was that my password contains special illegal characters (such as '#', ':', ';', '=' and '?'). I escaped these by using java.net.URLEncoder.encode() on auth.getUsername() and auth.getPassword() so the code doesn't throw a MalformedURLException when creating the SmbChannel. However, the next exception I encountered is as follows:
Failed to write record to Transactions table in database: File format GENERIC_JET4 [VERSION_4] does not support file creation for null
java.io.IOException: File format GENERIC_JET4 [VERSION_4] does not support file creation for null
at com.healthmarketscience.jackcess.impl.DatabaseImpl.create(DatabaseImpl.java:444)
What Database.FileFormat constant should I use for an MS Access 2000-2003 database, when creating the Database object?

It turns out that I needed to use Database.FileFormat.V2000.
After that, it was all plain sailing (although I still need to work out how to get the Long timestamp to convert correctly).

Related

[Snowflake-jdbc]It hangs when get info from resetset object of connection.getMetadata().getColumns(...)

I try to test the jdbc connection of snowflake with codes below
Connection conn = .......
.......
ResultSet rs = conn.getMetaData().getColumns(**null**, "PUBLIC", "TAB1", null); // 1. set parameters to get metadata of table TAB1
while (rs.next()) { // 2. It hangs here if the first parameter is null in above liune; otherwise(set the corrent db name), it works fine
System.out.println( "precision:" + rs.getInt(7)
+ ",col type name:" + rs.getString(6)
+ ",col type:" + rs.getInt(5)
+ ",col name:" + rs.getString(4)
+ ",CHAR_OCTET_LENGTH:" + rs.getInt(16)
+ ",buf LENGTH:" + rs.getString(8)
+ ",SCALE:" + rs.getInt(9));
}
.......
I debug the codes above in Intellij IDEA, and find that the debugger can't get the details of the object, it always shows "Evaluating..."
The JDBC driver I used is snowflake-jdbc-3.12.5.jar
Is it a bug?
When the catalog (database) argument is null, the JDBC code effectively runs the following SQL, which you can verify in your Snowflake account's Query History UIs/Views:
show columns in account;
This is an expensive metadata query to run due to no filters and the wide requested breadth (columns across the entire account).
Depending on how many databases exist in your organization's account, it may require several minutes or upto an hour of execution to return back results, which explains the seeming "hang". On a simple test with about 50k+ tables dispersed across 100+ of databases and schemas, this took at least 15 minutes to return back results.
I debug the codes above in Intellij IDEA, and find that the debugger can't get the details of the object, it always shows "Evaluating..."
This may be a weirdness with your IDE, but in a pinch you can use the Dump Threads (Ctrl + Escape, or Ctrl + Break) option in IDEA to provide a single captured thread dump view. This should help show that the JDBC client thread isn't hanging (as in, its not locked or starved), it is only waiting on the server to send back results.
There is no issue with the 3.12.5 jar.I just tested the same version in Eclipse, I can inspect all the objects . Could be an issue with your IDE.
ResultSet columns = metaData.getColumns(null, null, "TESTTABLE123",null);
while (columns.next()){
System.out.print("Column name and size: "+columns.getString("COLUMN_NAME"));
System.out.print("("+columns.getInt("COLUMN_SIZE")+")");
System.out.println(" ");
System.out.println("COLUMN_DEF : "+columns.getString("COLUMN_DEF"));
System.out.println("Ordinal position: "+columns.getInt("ORDINAL_POSITION"));
System.out.println("Catalog: "+columns.getString("TABLE_CAT"));
System.out.println("Data type (integer value): "+columns.getInt("DATA_TYPE"));
System.out.println("Data type name: "+columns.getString("TYPE_NAME"));
System.out.println(" ");
}

how do I extract attachments from integrity PTC items using Java API

I'm trying to extract attachments from integrity PTC items that are on a linux server from my Windows PC but it keeps giving me errors. The exact same command worked in command line
IntegrationPoint integrationPoint =
IntegrationPointFactory.getInstance().createIntegrationPoint(
hostName,
port,
APIVersion.API_4_16);
System.out.println("Start download Attachment");
// Start the Integrity client.
integrationPoint.setAutoStartIntegrityClient(true);
// Connect to the Integrity server.
Session session = integrationPoint.createSession(username, password);
Command command = new Command(Command.IM, "extractattachments");
command.addOption(new Option("issue", itemID));
command.addOption(new Option("field", "Text Attachments"));
command.addSelection(attachment);
Response response = session.createCmdRunner().execute(command);
I'm getting an error that says
Error encountered trying to get the next name: File paths must be rooted in /export/home/ptc/Integrity/ILMServer11.0/data/tmp: Current file is /export/home/ptc/Integrity/ILMServer11.0/bin/C:\Workspace\document/bear.jpg
Anytime I add cwd to the command it just appends whatever I put after the /bin/ It says it's a InvalidCommandSelectionException and a CommandException
You're missing the outputFile option on the extractattachments command.
This code worked the way I expected it to ...
IntegrationPointFactory ipfact = IntegrationPointFactory.getInstance();
IntegrationPoint ip = ipfact.createIntegrationPoint(hostname, port, APIVersion.API_4_16);
Session session = ip.createNamedSession("test", APIVersion.API_4_16, user, passwd);
CmdRunner cr = session.createCmdRunner();
Command cmd = new Command(Command.IM, "extractattachments");
cmd.addSelection(attachmentName);
cmd.addOption(new Option("issue", issueid));
cmd.addOption(new FileOption("outputFile", "d:/data/" + attachmentName));
cr.execute(cmd);
cr.release();
ip.release();

How to use backup semantics (seBackup privilege) over the network?

I am trying to enumerate a directory on a remote file server.
I want to use backup-semantics in order to not require administrator credentials.
On the test server, I have created a share:
Share permissions: everyone full control
NTFS permissions: only SYSTEM (I removed all others)
I am currently using this code:
static void accessWithBackupSemantics() {
NetResource netResource = new NetResource() {
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplayType.Share,
Usage = ResourceUsage.Connectable,
RemoteName = #"\\target-srv\TargetShare"
};
// open "net use" connection
int netResult = Native.WNetAddConnection2(netResource,
#"***password***",
#"DOMAIN\backup_op_user",
0);
if (netResult == 0 || netResult == 1219) {
// enable privileges
// (this is taken from AplhaFS)
using (new PrivilegeEnabler(Privilege.Backup)) {
try {
// try open remote directory
SafeFileHandle fsHandle = Native.CreateFile(
#"\\target-srv\TargetShare",
EFileAccess.GenericRead,
EFileShare.Read | EFileShare.Write,
IntPtr.Zero,
ECreationDisposition.OpenExisting,
EFileAttributes.BackupSemantics,
IntPtr.Zero);
Console.WriteLine("Handle is valid: " + !fsHandle.IsInvalid);
}
catch (Exception ex) {}
finally {
Native.WNetCancelConnection2(netResource.RemoteName, 0, true);
}
}
}
}
PrivilegeEnabler class is taken from AlphaFS
Native win32 structures and flags are taken from pinvoke.net/kernel32.createfile
This works if I specify "DOMAIN\Administrator" in the username, but does not work (the error is 5 - access denied) if I try to use a domain account that is a member of the local "Backup Operators" on target-srv server.
I have also examined the security event log on target-srv, for every connection created with WNetAddConnection2 a "Special Logon" event is written. The details of this event include the list of privileges that the logon account was given.
In both cases (when I connect with administrator or with backup_op_user) - seBackupPrivilege is indeed listed.
I tried to give extra privileges to the "Backup Operators" so the list has all the privileges that the Administrator has - but it made no change.
Questions:
What is the right way to use Backup-Semantics over the network?
How come it works with Administrator and not with a member of "Backup Operators" - are there additional implicit permissions for the Admin?
I have seen many examples of local use of Backup-Semantics, but not one that can be used over the network - please don't reply with links to examples of local usage.

db2 Invalid parameter: Unknown column name SERVER_POOL_NAME . ERRORCODE=-4460, SQLSTATE=null

I am using SQL 'select' to access a db2 table with schemaname.tablename as follows:
select 'colname' from schemaname.tablename
The tablename has 'colname' = SERVER_POOL_NAME for sure . yet I get the following error :
"Invalid parameter: Unknown column name SERVER_POOL_NAME . ERRORCODE=-4460, SQLSTATE=null"
I am using db2 v10.1 FP0 jdbc driver version 3.63.123. JDBC 3.0 spec
The application is run as db2 administrator and also Windows 2008 admin
I saw a discussion about this issue at : db2jcc4.jar Invalid parameter: Unknown column name
But i do not know where the connection parameter 'useJDBC4ColumnNameAndLabelSemantics should be set ( to value =2)
I saw the parameter should appear in com.ibm.db2.jcc.DB2BaseDataSource ( see: http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/index.jsp?topic=%2Fcom.ibm.db2.luw.apdv.java.doc%2Fsrc%2Ftpc%2Fimjcc_r0052607.html)
But i do not find this file on my DB2 installation . maybe it is packed in a .jar file
Any advice ?
There is a link on the page you're referring to, showing you the ways to set properties. Specifically, you can populate a Properties object with desired values and supply it to the getConnection() call:
String url = "jdbc:db2://host:50000/yourdb";
Properties props = new Properties();
props.setProperty("useJDBC4ColumnNameAndLabelSemantics", "2");
// set other required properties
Connection c = DriverManager.getConnection(url, props);
Alternatively, you can embed property name/value pairs in the JDBC URL itself:
String url = "jdbc:db2://host:50000/yourdb:useJDBC4ColumnNameAndLabelSemantics=2;";
// set other required properties
Connection c = DriverManager.getConnection(url);
Note that each name/value pair must be terminated by a semicolon, even the last one.

Password Changer using VAccess

Hey I am working on a password changer. User logs in ( successfully), loads a global var with user initials, then launch a password expired form. I try and use those initials on the password expired form to retrieve user info from DB.
vaUserLog.FieldValue("USERINIT") = UserInitials
vaUserLog.GetEqual
vaStat = vaUserLog.Status
vaStat keeps giving me an error of 4. I am using pervasive v9. Connection with VA looks like:
With vaUserLog
.RefreshLocations = True
.DdfPath = DataPath
.TableName = "USERLOG"
.Location = "USERLOG.MKD"
.Open
If .Status <> 0 Then
ErrMsg = "Error Opening File " + .TableName + " - Status " + str$(.Status) + vbCrLf + "Contact IT Department"
End If
End With
In DB table, USERINIT is Char, 3. UserInitials is a String.
Probably missing something small but can't think right now. Any help is appreciate. Lemme know if you require more info.
Cheers
Status 4 means that the record could not be found. In your case, it could be the case of the value being searched is wrong, there's a different padding (spaces versus binary zero), or that the UserInitials value just isn't in the data file.
You can use MKDE Tracing to see what's actually being passed to the PSQL engine. Once you've done that, make sure the value you're using works through the Function Executor where you can open the file and perform a GetEqual.
Here are my suggestions:
- Make sure you're pointing to the right data files.
- Make sure you're passing the right value into the GetEqual (by setting the FieldValue).

Resources