<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Database &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/database/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 27 Dec 2017 21:53:54 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Using SQLite in Matlab</title>
		<link>https://undocumentedmatlab.com/articles/using-sqlite-in-matlab?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-sqlite-in-matlab</link>
					<comments>https://undocumentedmatlab.com/articles/using-sqlite-in-matlab#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 27 Dec 2017 21:53:54 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[JDBC]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7255</guid>

					<description><![CDATA[<p>SQLite databases can be accessed in a variety of different ways in Matlab. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/using-sqlite-in-matlab">Using SQLite in Matlab</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql" rel="bookmark" title="Secure SSL connection between Matlab and PostgreSQL">Secure SSL connection between Matlab and PostgreSQL </a> <small>It is tricky, but quite possible, to use SSL to connect Matlab to a PostgreSQL database. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries" rel="bookmark" title="Speeding up Matlab-JDBC SQL queries">Speeding up Matlab-JDBC SQL queries </a> <small>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/sending-html-emails-from-matlab" rel="bookmark" title="Sending HTML emails from Matlab">Sending HTML emails from Matlab </a> <small>Matlab's sendmail only sends simple text messages by default; a simple hack can cause it to send HTML-formatted messages. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>MathWorks invests a huge amount of effort in recent years on supporting large distributed databases. The business case for this focus is entirely understandable, but many Matlab users have much simpler needs, which are often served by the light-weight open-source <a href="http://sqlite.org" rel="nofollow" target="_blank">SQLite database</a> (which claims to be the most widely-used database worldwide). Although SQLite is very widely used, and despite the fact that built-in support for SQLite is included in Matlab (for its internal use), MathWorks has chosen not to expose any functionality or wrapper function that would enable end-users to access it. In any case, I recently came across a need to do just that, when a consulting client asked me to create an interactive data-browser for their SQLite database that would integrate with their Matlab program:<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/DataBrowser_2.png" alt="SQLite data browser" title="SQLite data browser" width="80%" style="max-width:716px;" /></center><br />
In today&#8217;s post I will discuss several possible mechanisms to integrate SQLite in Matlab code, and you can take your pick among them. Except for the Database Toolbox, all the alternatives are free (open-source) libraries (even the commercial Database Toolbox relies on one of the open-source libraries, by the way).<br />
<span id="more-7255"></span></p>
<h3 id="sqlite4java">sqlite4java</h3>
<p><code>sqlite4java</code> is a Java package by <a href="http://almworks.com" rel="nofollow" target="_blank">ALM Works</a> that is bundled with Matlab for the past several years (in the <i>%matlabroot%/java/jarext/sqlite4java/</i> folder). This is a lightweight open-source package that provides a minimalist and fast (although not very convenient) interface to SQLite. You can either use the package that comes with your Matlab installation, or download and use the latest version from <a href="https://bitbucket.org/almworks/sqlite4java" rel="nofollow" target="_blank">the project repository</a>, where you can also find documentation.<br />
Mark Mikofski <a href="http://poquitopicante.blogspot.co.il/2015/03/sqlite-in-matlab.html" rel="nofollow" target="_blank">exposed</a> this hidden nugget back in 2015, and you are welcome to view his post for additional details. Here&#8217;s a sample usage:</p>
<pre lang="matlab">
% Open the DB data file
db = com.almworks.sqlite4java.SQLiteConnection(java.io.File('C:\Yair\Data\IGdb 2017-11-13.sqlite'));
db.open;
% Prepare an SQL query statement
stmt = db.prepare(['select * from data_table where ' conditionStr]);
% Step through the result set rows
row = 1;
while stmt.step
   numericValues(row) = stmt.columnInt(0);    % column #0
   stringValues{row}  = stmt.columnString(1); % column #1
end
% Cleanup
stmt.dispose
db.dispose
</pre>
<p>Note that since <code>sqlite4java</code> uses a proprietary interface (similar, but not identical, to JDBC), it can take a bit of time to get used to it. I am generally a big fan of preferring built-in components over externally-installed ones, but in this particular case I prefer other alternatives.</p>
<h3 id="JDBC">JDBC</h3>
<p><a href="http://www.oracle.com/technetwork/java/javase/jdbc/index.html" rel="nofollow" target="_blank">JDBC</a> (Java Database Connectivity) is the industry standard for connectivity to databases. Practically all databases nowadays have at least one JDBC connector, and many DBs have multiple JDBC drivers created by different groups. As long as they all adhere to the JDBC interface standard, these drivers are all equivalent and you can choose between them based on availability, cost, support, license, performance and other similar factors. SQLite is no exception to this rule, and has several JDBC driver implementations, including xerial&#8217;s <a href="https://bitbucket.org/xerial/sqlite-jdbc" rel="nofollow" target="_blank"><code>sqlite-jdbc</code></a> (also <a href="http://poquitopicante.blogspot.co.il/2015/03/sqlite-in-matlab.html" rel="nofollow" target="_blank">discussed by Mark Mikofski</a>) and <a href="https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/sqlitebot/sqlitejdbc-v056.jar" rel="nofollow" target="_blank"><code>sqlitejdbc</code></a>. If you ask me,<br />
 <code>sqlite-jdbc</code> is better as it is being maintained with new versions released periodically.<br />
The example above would look something like this with <code>sqlite-jdbc</code>:</p>
<pre lang="matlab">
% Add the downloaded JAR library file to the dynamic Java classpath
javaaddpath('C:\path\to\sqlite\sqlite-jdbc-3.21.0.jar')
% Open the DB file
jdbc = org.sqlite.JDBC;
props = java.util.Properties;
conn = jdbc.createConnection('jdbc:sqlite:C:\Yair\Data\IGdb 2017-11-13.sqlite',props);  % org.sqlite.SQLiteConnection object
% Prepare and run an SQL query statement
sqlStr = ['select * from data_table where ' conditionStr];
stmt = conn.createStatement;     % org.sqlite.jdbc4.JDBC4Statement object
rs = stmt.executeQuery(sqlStr);  % org.sqlite.jdbc4.JDBC4ResultSet object
% Step through the result set rows
rows = 1;
while rs.next
   numericValues(row) = rs.getLong('ID');
   stringValues{row}  = rs.getString('Name');
end
% Cleanup
rs.close
stmt.close
conn.close
</pre>
<h3 id="toolbox">Database toolbox</h3>
<p>In addition to all the above, MathWorks sells the Database Toolbox which has an <a href="https://www.mathworks.com/help/database/ug/working-with-the-matlab-interface-to-sqlite.html" rel="nofollow" target="_blank">integral SQLite connector</a>, in two flavors &#8211; native and JDBC (the JDBC connector is simply <code>sqlite-jdbc</code> that I mentioned above, see a <a href="https://gist.github.com/cbcunc/e2bc3ef170544e4bf0f0" rel="nofollow" target="_blank">short discussion here</a>).<br />
I assume that the availability of this feature in the DB toolbox is the reason why MathWorks has never created a documented wrapper function for the bundled <code>sqlite4java</code>. I could certainly understand this from a business perspective. Still, with so many free alternatives available as discussed in this post, I see not reason to purchase the toolbox merely for its SQLite connector. Then again, if you need to connect to several different database types, not just SQLite, then getting the toolbox might make sense.</p>
<h3 id="mksqlite">mksqlite</h3>
<p>My personal favorite is actually none of these Java-based connectors (surprise, surprise), but rather the open-source <a href="http://mksqlite.sourceforge.net" rel="nofollow" target="_blank"><code>mksqlite</code> connector</a> by <a href="http://www.kortmann.de" rel="nofollow" target="_blank">Martin Kortmann</a> and <a href="https://github.com/AndreasMartin72" rel="nofollow" target="_blank">Andreas Martin</a>. This is a native (Mex-file) connector that acts as a direct Matlab function. The syntax is pretty straight-forward and supports SQL queries. IMHO, its usage is a much simpler than with any of the other alternatives:</p>
<pre lang="matlab">
% Open the DB file
mksqlite('open', 'C:\Yair\Data\IGdb 2017-11-13.sqlite');
% Query the database
results = mksqlite(['select * from data_table where ' conditionStr]);
numericValues = [results.ID];
stringValues  = {results.Name};
% Cleanup
mksqlite('close');
</pre>
<p>Can it be any simpler than this!?<br />
However, the main benefit of <code>mksqlite</code> over the other connectors is not its simplicity but the connector&#8217;s speed. This speed is due to the fact that the query is vectorized and we do not need to loop over all the separate data rows and fields. With the other connectors, it is actually not the loop that takes so long in Matlab, but rather the overheads and inefficiencies of numerous library calls to fetch one single value at a time from the result-set &#8211; this is avoided in <code>mksqlite</code> where there is only a single call. This results in lightning speed: A couple of years ago I consulted to a client who used a JDBC connector to an SQLite database; by switching from a JDBC connector to <code>mksqlite</code>, I reduced the execution time from 7 secs to 70 msecs &#8211; a 100x speedup! In that specific case, this made the difference between an unusable program and a highly interactive/responsive one.</p>
<h3 id="alternatives">Other alternatives</h3>
<p>In addition to all the above, we can also use a <a href="http://www.codingtricks.biz/working-with-sqlite-database-in-matlab/" rel="nofollow" target="_blank">.NET-based connector</a> or a <a href="https://www.pythoncentral.io/introduction-to-sqlite-in-python/" rel="nofollow" target="_blank">Python one</a> &#8211; I leave these as an exercise for the reader&#8230;<br />
Have I forgotten some important alternative? Or perhaps you have have some related tip you&#8217;d like to share? If so, then please leave a comment below.<br />
Happy New Year everybody!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/using-sqlite-in-matlab">Using SQLite in Matlab</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql" rel="bookmark" title="Secure SSL connection between Matlab and PostgreSQL">Secure SSL connection between Matlab and PostgreSQL </a> <small>It is tricky, but quite possible, to use SSL to connect Matlab to a PostgreSQL database. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries" rel="bookmark" title="Speeding up Matlab-JDBC SQL queries">Speeding up Matlab-JDBC SQL queries </a> <small>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/sending-html-emails-from-matlab" rel="bookmark" title="Sending HTML emails from Matlab">Sending HTML emails from Matlab </a> <small>Matlab's sendmail only sends simple text messages by default; a simple hack can cause it to send HTML-formatted messages. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/using-sqlite-in-matlab/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Speeding up Matlab-JDBC SQL queries</title>
		<link>https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=speeding-up-matlab-jdbc-sql-queries</link>
					<comments>https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 16 Nov 2016 11:43:17 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Toolbox]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Performance]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6742</guid>

					<description><![CDATA[<p>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries">Speeding up Matlab-JDBC SQL queries</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 2">Speeding-up builtin Matlab functions &#8211; part 2 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-1" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 1">Speeding-up builtin Matlab functions &#8211; part 1 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-compiled-apps-startup" rel="bookmark" title="Speeding up compiled apps startup">Speeding up compiled apps startup </a> <small>The MCR_CACHE_ROOT environment variable can reportedly help to speed-up deployed Matlab executables....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-java-collections-in-matlab" rel="bookmark" title="Using Java Collections in Matlab">Using Java Collections in Matlab </a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Many of my consulting projects involve interfacing a Matlab program to an SQL database. In such cases, using MathWorks&#8217; Database Toolbox is a viable solution. Users who don&#8217;t have the toolbox can also easily connect directly to the database using either the standard ODBC bridge (which is horrible for performance and stability), or a direct <a href="https://docs.oracle.com/javase/tutorial/jdbc/" rel="nofollow" target="_blank">JDBC connection</a> (which is also what the Database Toolbox uses under the hood). I explained this Matlab-JDBC interface in detail in chapter 2 of my <a href="/books/matlab-java" target="_blank">Matlab-Java programming book</a>. A bare-bones implementation of an SQL SELECT query follows (data update queries are a bit different and will not be discussed here):</p>
<pre lang="matlab">
% Load the appropriate JDBC driver class into Matlab's memory
% (but not directly, to bypass JIT pre-processing - we must do it in run-time!)
driver = eval('com.mysql.jdbc.Driver');  % or com.microsoft.sqlserver.jdbc.SQLServerDriver or whatever
% Connect to DB
dbPort = '3306'; % mySQL=3306; SQLServer=1433; Oracle=...
connectionStr = ['jdbc:mysql://' dbURL ':' dbPort '/' schemaName];  % or ['jdbc:sqlserver://' dbURL ':' dbPort ';database=' schemaName ';'] or whatever
dbConnObj = java.sql.DriverManager.getConnection(connectionStr, username, password);
% Send an SQL query statement to the DB and get the ResultSet
stmt = dbConnObj.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
try stmt.setFetchSize(1000); catch, end  % the default fetch size is ridiculously small in many DBs
rs = stmt.executeQuery(sqlQueryStr);
% Get the column names and data-types from the ResultSet's meta-data
MetaData = rs.getMetaData;
numCols = MetaData.getColumnCount;
data = cell(0,numCols);  % initialize
for colIdx = numCols : -1 : 1
    ColumnNames{colIdx} = char(MetaData.getColumnLabel(colIdx));
    ColumnType{colIdx}  = char(MetaData.getColumnClassName(colIdx));  % http://docs.oracle.com/javase/7/docs/api/java/sql/Types.html
end
ColumnType = regexprep(ColumnType,'.*\.','');
% Get the data from the ResultSet into a Matlab cell array
rowIdx = 1;
while rs.next  % loop over all ResultSet rows (records)
    for colIdx = 1 : numCols  % loop over all columns in the row
        switch ColumnType{colIdx}
            case {'Float','Double'}
                data{rowIdx,colIdx} = rs.getDouble(colIdx);
            case {'Long','Integer','Short','BigDecimal'}
                data{rowIdx,colIdx} = double(rs.getDouble(colIdx));
            case 'Boolean'
                data{rowIdx,colIdx} = logical(rs.getBoolean(colIdx));
            otherwise %case {'String','Date','Time','Timestamp'}
                data{rowIdx,colIdx} = char(rs.getString(colIdx));
        end
    end
    rowIdx = rowIdx + 1;
end
% Close the connection and clear resources
try rs.close();   catch, end
try stmt.close(); catch, end
try dbConnObj.closeAllStatements(); catch, end
try dbConnObj.close(); catch, end  % comment this to keep the dbConnObj open and reuse it for subsequent queries
</pre>
<p>Naturally, in a real-world implementation you also need to handle database timeouts and various other errors, handle data-manipulation queries (not just SELECTs), etc.<br />
Anyway, this works well in general, but when you try to fetch a ResultSet that has many thousands of records you start to feel the pain &#8211; The SQL statement may execute much faster on the DB server (the time it takes for the <code>stmt.executeQuery</code> call), yet the subsequent double-loop processing to fetch the data from the Java <code>ResultSet</code> object into a Matlab cell array takes much longer.<br />
In one of my recent projects, performance was of paramount importance, and the DB query speed from the code above was simply not good enough. <span id="more-6742"></span> You might think that this was due to the fact that the <code>data</code> cell array is not pre-allocated, but this turns out to be incorrect: the speed remains nearly unaffected when you pre-allocate <code>data</code> properly. It turns out that the main problem is due to Matlab&#8217;s non-negligible overhead in calling methods of Java objects. Since the JDBC interface only enables retrieving a single data item at a time (in other words, bulk retrieval is not possible), we have a double loop over all the data&#8217;s rows and columns, in each case calling the appropriate Java method to retrieve the data based on the column&#8217;s type. The Java methods themselves are extremely efficient, but when you add Matlab&#8217;s invocation overheads the total processing time is much much slower.<br />
So what can be done? As <a href="http://stackoverflow.com/questions/23244179/how-to-speed-up-table-retrieval-with-matlab-and-jdbc" rel="nofollow" target="_blank">Andrew Janke explained</a> in much detail, we basically need to push our double loop down into the Java level, so that Matlab receives arrays of primitive values, which can then be processed in a vectorized manner in Matlab.<br />
So let&#8217;s create a simple Java class to do this:</p>
<pre lang="Java">
// Copyright (c) Yair Altman UndocumentedMatlab.com
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
public class JDBC_Fetch {
	public static int DEFAULT_MAX_ROWS = 100000;   // default cache size = 100K rows (if DB does not support non-forward-only ResultSets)
	public static Object[] getData(ResultSet rs) throws SQLException {
		try {
			if (rs.last()) {  // data is available
				int numRows = rs.getRow();    // row # of the last row
				rs.beforeFirst();             // get back to the top of the ResultSet
				return getData(rs, numRows);  // fetch the data
			} else {  // no data in the ResultSet
				return null;
			}
		} catch (Exception e) {
			return getData(rs, DEFAULT_MAX_ROWS);
		}
	}
	public static Object[] getData(ResultSet rs, int maxRows) throws SQLException {
		// Read column number and types from the ResultSet's meta-data
		ResultSetMetaData metaData = rs.getMetaData();
		int numCols = metaData.getColumnCount();
		int[] colTypes = new int[numCols+1];
		int numDoubleCols = 0;
		int numBooleanCols = 0;
		int numStringCols = 0;
		for (int colIdx = 1; colIdx <= numCols; colIdx++) {
			int colType = metaData.getColumnType(colIdx);
			switch (colType) {
				case Types.FLOAT:
				case Types.DOUBLE:
				case Types.REAL:
					colTypes[colIdx] = 1;  // double
					numDoubleCols++;
					break;
				case Types.DECIMAL:
				case Types.INTEGER:
				case Types.TINYINT:
				case Types.SMALLINT:
				case Types.BIGINT:
					colTypes[colIdx] = 1;  // double
					numDoubleCols++;
					break;
				case Types.BIT:
				case Types.BOOLEAN:
					colTypes[colIdx] = 2;  // boolean
					numBooleanCols++;
					break;
				default: // 'String','Date','Time','Timestamp',...
					colTypes[colIdx] = 3;  // string
					numStringCols++;
			}
		}
		// Loop over all ResultSet rows, reading the data into the 2D matrix caches
		int rowIdx = 0;
		double [][] dataCacheDouble  = new double [numDoubleCols] [maxRows];
		boolean[][] dataCacheBoolean = new boolean[numBooleanCols][maxRows];
		String [][] dataCacheString  = new String [numStringCols] [maxRows];
		while (rs.next() &#038;&#038; rowIdx < maxRows) {
			int doubleColIdx = 0;
			int booleanColIdx = 0;
			int stringColIdx = 0;
			for (int colIdx = 1; colIdx <= numCols; colIdx++) {
				try {
					switch (colTypes[colIdx]) {
						case 1:  dataCacheDouble[doubleColIdx++][rowIdx]   = rs.getDouble(colIdx);   break;  // numeric
						case 2:  dataCacheBoolean[booleanColIdx++][rowIdx] = rs.getBoolean(colIdx);  break;  // boolean
						default: dataCacheString[stringColIdx++][rowIdx]   = rs.getString(colIdx);   break;  // string
					}
				} catch (Exception e) {
					System.out.println(e);
					System.out.println(" in row #" + rowIdx + ", col #" + colIdx);
				}
			}
			rowIdx++;
		}
		// Return only the actual data in the ResultSet
		int doubleColIdx = 0;
		int booleanColIdx = 0;
		int stringColIdx = 0;
		Object[] data = new Object[numCols];
		for (int colIdx = 1; colIdx <= numCols; colIdx++) {
			switch (colTypes[colIdx]) {
				case 1:   data[colIdx-1] = dataCacheDouble[doubleColIdx++];    break;  // numeric
				case 2:   data[colIdx-1] = dataCacheBoolean[booleanColIdx++];  break;  // boolean
				default:  data[colIdx-1] = dataCacheString[stringColIdx++];            // string
			}
		}
		return data;
	}
}
</pre>
<p>So now we have a <code>JDBC_Fetch</code> class that we can use in our Matlab code, replacing the slow double loop with a single call to <code>JDBC_Fetch.getData()</code>, followed by vectorized conversion into a Matlab cell array (matrix):</p>
<pre lang="matlab">
% Get the data from the ResultSet using the JDBC_Fetch wrapper
data = cell(JDBC_Fetch.getData(rs));
for colIdx = 1 : numCols
   switch ColumnType{colIdx}
      case {'Float','Double'}
          data{colIdx} = num2cell(data{colIdx});
      case {'Long','Integer','Short','BigDecimal'}
          data{colIdx} = num2cell(data{colIdx});
      case 'Boolean'
          data{colIdx} = num2cell(data{colIdx});
      otherwise %case {'String','Date','Time','Timestamp'}
          %data{colIdx} = cell(data{colIdx});  % no need to do anything here!
   end
end
data = [data{:}];
</pre>
<p>On my specific program the resulting speedup was 15x (this is not a typo: <b>15 times faster</b>). My fetches are no longer limited by the Matlab post-processing, but rather by the DB's processing of the SQL statement (where DB indexes, clustering, SQL tuning etc. come into play).<br />
Additional speedups can be achieved by parsing dates at the Java level (rather than returning strings), as well as several other tweaks in the Java and Matlab code (refer to Andrew Janke's post for some ideas). But certainly the main benefit (the 80% of the gain that was achieved in 20% of the worktime) is due to the above push of the main double processing loop down into the Java level, leaving Matlab with just a single Java call to <code>JDBC_Fetch</code>.<br />
Many additional ideas of speeding up database queries and Matlab programs in general can be found in my second book, <a href="/books/matlab-performance" target="_blank"><i><b>Accelerating Matlab Performance</b></i></a>.<br />
If you'd like me to help you speed up your Matlab program, please email me (altmany at gmail), or fill out the query form on my <a href="/consulting" target="_blank">consulting page</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries">Speeding up Matlab-JDBC SQL queries</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-2" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 2">Speeding-up builtin Matlab functions &#8211; part 2 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-builtin-matlab-functions-part-1" rel="bookmark" title="Speeding-up builtin Matlab functions &#8211; part 1">Speeding-up builtin Matlab functions &#8211; part 1 </a> <small>Built-in Matlab functions can often be profiled and optimized for improved run-time performance. This article shows a typical example. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-compiled-apps-startup" rel="bookmark" title="Speeding up compiled apps startup">Speeding up compiled apps startup </a> <small>The MCR_CACHE_ROOT environment variable can reportedly help to speed-up deployed Matlab executables....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-java-collections-in-matlab" rel="bookmark" title="Using Java Collections in Matlab">Using Java Collections in Matlab </a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>Secure SSL connection between Matlab and PostgreSQL</title>
		<link>https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=secure-ssl-connection-between-matlab-and-postgresql</link>
					<comments>https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Fri, 18 Mar 2016 10:39:49 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Jeff Mandel]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6318</guid>

					<description><![CDATA[<p>It is tricky, but quite possible, to use SSL to connect Matlab to a PostgreSQL database. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql">Secure SSL connection between Matlab and PostgreSQL</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries" rel="bookmark" title="Speeding up Matlab-JDBC SQL queries">Speeding up Matlab-JDBC SQL queries </a> <small>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-sqlite-in-matlab" rel="bookmark" title="Using SQLite in Matlab">Using SQLite in Matlab </a> <small>SQLite databases can be accessed in a variety of different ways in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver" rel="bookmark" title="Fixing Matlab&#039;s actxserver">Fixing Matlab&#039;s actxserver </a> <small>Matlab's COM (ActiveX) server behavior can be fixed in a couple of useful manners. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2" rel="bookmark" title="Matlab compilation quirks &#8211; take 2">Matlab compilation quirks &#8211; take 2 </a> <small>A few hard-to-trace quirks with Matlab compiler outputs are explained. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I&#8217;d like to introduce guest blogger <a href="http://www.med.upenn.edu/apps/faculty/index.php/g275/p40141" rel="nofollow" target="_blank">Jeff Mandel</a> of the Perelman School of Medicine at the University of Pennsylvania. Today Jeff will discuss a how-to guide for setting up an SSL connection between Matlab and a PostgreSQL database. While this specific topic may be of interest to only a few readers, it involves hard-to-trace problems that are not well documented anywhere. The techniques discussed below may also be applicable, with necessary modifications, to other SSL targets and may thus be of use to a wider group of Matlab users.</i><br />
<span class="alignright"><a href="http://postgresql.org" target="_blank"><img decoding="async" src="https://undocumentedmatlab.com/images/PostgreSQL.gif" alt="PostgreSQL database" title="PostgreSQL database" width="200" height="200" /></a></span><br />
I&#8217;m developing software for pharmacokinetic control, and needed secure access to a central database from users at remote sites. The client software is written in Matlab, and while I have targeted MacOS, this could be adapted to Windows fairly easily. Hopefully, this will save someone the week it took me to figure all this out.<br />
My environment:</p>
<ul>
<li>PostgreSQL 9.4 installed on the server (Windows 7 PC, but Linux would be equally good)</li>
<li>DynDNS CNAME pointing at the server (diseserver.mydomain.org)</li>
<li>CACert.org registration for domain mydomain.org</li>
<li>Matlab 2015b running on El Capitan</li>
</ul>
<p>Here are the neccesary steps:<br />
<span id="more-6318"></span></p>
<ol>
<li>First, we need a certificate for the server. We can generate this with <a href="http://www.openssl.org" rel="nofollow" target="_blank">OpenSSL</a>:
<pre lang="bash">$openssl req -out diseserver.csr -new -newkey rsa:2048 -nodes -keyout diseserver.key</pre>
<p>Specify any information you want on the key, but ensure <code>CN=diseserver.mydomain.org</code>.</li>
<li>Paste the resulting <i>diseserver.csr</i> file into a new key request at <a href="http://cacert.org" rel="nofollow" target="_blank">CACert.org</a>. Save the resulting certificate as <i>diseserver.crt</i> on your machine.</li>
<li>While still at CACert.org, grab the Class 1 root certificate and save it as <i>root.crt</i>.</li>
<li>Put the files <i>diseserver.key</i>, <i>diseserver.crt</i>, and <i>root.crt</i> in the PostgreSQL data directory.</li>
<li>Edit your <i>postgresql.conf</i> file:
<pre lang="bash">
ssl = on
ssl_cert_file = 'diseserver.crt'  # (change requires restart)
ssl_key_file  = 'diseserver.key'  # (change requires restart)
ssl_ca_file   = 'root.crt'        # (change requires restart)
</pre>
</li>
<li>Restart the PostgreSQL server. The server will now permit SSL connections, a necessary pre-condition for certificate authentication.</li>
<li>We now add 2 lines to <i>pg_hba.conf</i>:
<pre lang="text">
hostnossl  all    all   0.0.0.0/0   reject
hostssl	 mytable  all   0.0.0.0/0   cert map=ssl clientcert=1
</pre>
<p>The first line causes all non-SSL connections to be rejected. The second allows certificate logins for mytable using the map ssl that is defined in <i>pg_ident.conf</i>:</p>
<pre lang="matlab">ssl  /^(.*).mydomain\.org$ \1</pre>
<p>this line extracts the username prefix from <code>CN=username.mydomain.org</code>.</li>
<li>Now we need to generate client certificates. PostgreSQL expects these to be in <i>~/.postgresql</i> (Windows <i>%appdata%\postgresql\</i>):
<pre lang="bash">
$mkdir ~/.postgresql
$cd ~/.postgresql
$openssl req -out postgresql.csr -new -newkey rsa:2048 -nodes -keyout postgresql.key
</pre>
<p>for this key, make <code>CN=username.mydomain.org</code>.</li>
<li>Again, paste the resulting <i>postgresql.csr</i> file into CACert.org, saving the certificate as <i>postgresql.crt</i>.</li>
<li>Test this:
<pre lang="bash">$psql "sslmode=verify-full host=diseserver.mydomain.org dbname=effect user=username"</pre>
<p>The server should respond:</p>
<pre lang="text">
psql (9.4.6, server 9.4.1)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
</pre>
</li>
<li>Next we need to convert our key into pkcs8 format so that Java can read it:
<pre lang="bash">$openssl pkcs8 -topk8 -inform PEM -outform DER -in postgresql.key -out postgresql.pk8 -nocrypt</pre>
</li>
<li>Next, ensure that we have the correct version of the JDBC driver (Java-to-database connector). From the Mac command line:
<pre lang="bash">
$java -version
java version "1.8.0_05"
</pre>
<p>and in Matlab:</p>
<pre lang="matlab">
>> version -java
ans =
Java 1.7.0_75-b13 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
</pre>
<p>This shows that although we have Java 8 installed on El Capitan (at the OS level), Matlab uses a private Java 7 version. So we need the correct version of the jdbc on our <a href="/articles/static-java-classpath-hacks" target="_blank">static java classpath that is used by Matlab</a>:</p>
<pre lang="text">~/Matlab/postgresql-9.4.1208.jre7.jar</pre>
</li>
<li>The next part is very poorly documented in both the MathWorks and the PostgreSQL documentation, but I found it in Russel Gray&#8217;s <a href="https://basildoncoder.com/blog/postgresql-jdbc-client-certificates.html" rel="nofollow" target="_blank"><i>Basildon Coder</i></a> blog: We need to use the jdbc postgresql driver to check the client certificate. To do this, we need a custom SSLSocketFactory &#8211; LibPQFactory. This will grab our certificate and key from <i>~/.postgresql</i> and present them to the server. The url is (note the trailing &#038;):
<pre lang="text">jdbc:postgresql://diseserver.mydomain.org/mytable?ssl=true&sslfactory=org.postgresql.ssl.jdbc4.LibPQFactory&sslmode=verify-full&</pre>
</li>
<li>Next we need the username. Rather than hard-coding this in the source code, we get the system username:
<pre lang="matlab">>> username = java.lang.System.getProperty('user.name');</pre>
</li>
<li>Bundle this all up in a Matlab function, stripping the trailing CR from the username:
<pre lang="matlab">
function dbtest
   driver = 'org.postgresql.Driver';
   [~,username] = system('whoami');
   url = 'jdbc:postgresql://diseserver.mydomain.org/mytable?ssl=true&sslfactory=org.postgresql.ssl.jdbc4.LibPQFactory&sslmode=verify-full&';
   myconn = database('mytable', username, '', driver, url);
   if ~isempty(myconn.Message)
      fprintf(2,'%s\n', myconn.Message);
   else
      fprintf(1, 'Connected!\n');
   end
end
</pre>
</li>
</ol>
<p>Now we can connect from the Matlab command line or a Matlab program.<br />
What if we&#8217;re deployed? We also need to add the contents of our <i>.postgresql</i> directory, plus the jdbc jar file to our deployed app:</p>
<pre lang="matlab">>> mcc -m dbtest.m -a ~/.postgresql -a ~/Matlab/postgresql-9.4.1208.jre7.jar</pre>
<p>Let&#8217;s test the compiled program from the OS command line:</p>
<pre lang="bash">
$./run_dbtest.sh /Applications/Matlab/Matlab_Runtime/v90
Connected!
</pre>
<p>Note that the key and certificates are part of the encrypted bundle produced by Matlab&#8217;s <i><b>mcc</b></i> compiler.<br />
I hope this helps someone!<br />
<i><u>Yair&#8217;s note</u>: the Matlab code above uses Matlab&#8217;s Database Toolbox (specifically, the <b>database</b> function) to connect to the database. In future posts I plan to show how we can connect Matlab directly to a database via JDBC. This topic is covered in detail in chapter 2 of my <a href="/books/matlab-java" rel="nofollow" target="_blank">Matlab-Java programming secrets book</a>.<br />
p.s. &#8211; this blog celebrates a 7-year anniversary tomorrow: I published my very first post here on March 19, 2009, showing <a href="/articles/changing-matlab-command-window-colors" target="_blank">how to change Matlab&#8217;s command-window colors</a> (a post that later led to the now-famous <a href="/articles/cprintf" target="_blank"><b>cprintf</b> utility</a>). It&#8217;s been a long and very interesting ride indeed, but I have no plans to retire anytime soon 🙂</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql">Secure SSL connection between Matlab and PostgreSQL</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries" rel="bookmark" title="Speeding up Matlab-JDBC SQL queries">Speeding up Matlab-JDBC SQL queries </a> <small>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-sqlite-in-matlab" rel="bookmark" title="Using SQLite in Matlab">Using SQLite in Matlab </a> <small>SQLite databases can be accessed in a variety of different ways in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver" rel="bookmark" title="Fixing Matlab&#039;s actxserver">Fixing Matlab&#039;s actxserver </a> <small>Matlab's COM (ActiveX) server behavior can be fixed in a couple of useful manners. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2" rel="bookmark" title="Matlab compilation quirks &#8211; take 2">Matlab compilation quirks &#8211; take 2 </a> <small>A few hard-to-trace quirks with Matlab compiler outputs are explained. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Static Java classpath hacks</title>
		<link>https://undocumentedmatlab.com/articles/static-java-classpath-hacks?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=static-java-classpath-hacks</link>
					<comments>https://undocumentedmatlab.com/articles/static-java-classpath-hacks#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 29 Jul 2015 08:00:05 +0000</pubDate>
				<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Database]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5945</guid>

					<description><![CDATA[<p>Several hacks that facilitate using the static Java classpath in Matlab are explained. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/static-java-classpath-hacks">Static Java classpath hacks</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-interface-using-static-control" rel="bookmark" title="Matlab-Java interface using a static control">Matlab-Java interface using a static control </a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/java-class-access-pitfalls" rel="bookmark" title="Java class access pitfalls">Java class access pitfalls </a> <small>There are several potential pitfalls when accessing Matlab classes from Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-internal-java-class-members" rel="bookmark" title="Accessing internal Java class members">Accessing internal Java class members </a> <small>Java inner classes and enumerations can be used in Matlab with a bit of tweaking. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/listbox-selection-hacks" rel="bookmark" title="Listbox selection hacks">Listbox selection hacks </a> <small>Matlab listbox selection can be customized in a variety of undocumented ways. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few days ago I encountered a situation where I needed to incorporate a JAR file into Matlab&#8217;s static Java classpath. I came across several relevant hacks that I thought could be useful for others:</p>
<ul>
<li><a href="#documented">The documented approach</a></li>
<li><a href="#retrofit">Fixing javaclasspath.txt in run-time</a></li>
<li><a href="#preload">Preloading Java class files in javaclasspath.txt</a></li>
<li><a href="#dynamic">Loading Java class files into the static classpath in run-time (!)</a></li>
<li><a href="#analyze">Analyzing loaded Java classes in run-time</a></li>
</ul>
<h3 id="documented">The documented approach</h3>
<p>In most use-cases, adding Java classes (or ZIP/JAR files) to the dynamic Java classpath is good enough. This can easily be done in run-time using the <i><b>javaaddpath</b></i> function. In certain cases, for example where the <a target="_blank" href="/articles/matlab-callbacks-for-java-events">Java code uses asynchronous events</a>, the Java files need to be added to the <i>static</i>, rather than the <i>dynamic</i>, Java classpath. In other cases, the Java code misbehaves when loaded using Matlab&#8217;s dynamic Java classloader, rather than the system classloader (which is used for the static classpath (<a target="_blank" rel="nofollow" href="http://blogs.mathworks.com/community/2009/07/06/calling-java-from-matlab/#comment-6860">some additional info</a>). One example of this are the JAR/ZIP files used to connect to various databases (each database has its own Java JDBC connector, but they all need to reside in the static Java classpath to work properly).<br />
Adding class-file folders or ZIP/JAR files to the static Java classpath can be done in several manners: we can update the Matlab installation&#8217;s <i>classpath.txt</i> file, or (<a target="_blank" href="/articles/matlab-installation-take-2#R2012b">starting in R2012b</a>) a user-prepared <i>javaclasspath.txt</i> file. Either of these files can be placed in the Matlab (or deployed application&#8217;s) startup folder, or the user&#8217;s Matlab preferences folder (<i><b>prefdir</b></i>). This is all <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/matlab_external/bringing-java-classes-and-methods-into-matlab-workspace.html">documented</a>.<br />
There are several important drawbacks to this approach:<br />
<span id="more-5945"></span></p>
<ol>
<li>Both <i>classpath.txt</i> and <i>javaclasspath.txt</i> do not accept relative paths, only full path-names. In other words, we cannot specify <i>../../libs/mylib.jar</i> but only <i>C:\Yair\libs\mylib.jar</i> or similar variants. We can use the <code>$matlabroot</code>, <code>$arch</code>, and <code>$jre_home</code> place-holder macros, but not user folders. We can easily do this in our personal computer where the full path is known, but this is difficult to ensure if we deploy the application onto other computers.<br />
Matlab&#8217;s compiler <a target="_blank" rel="nofollow" href="http://uk.mathworks.com/matlabcentral/answers/97072-how-should-i-include-a-jar-file-in-my-compiled-application-with-matlab-compiler-4-1-r14sp1#answer_106422">only supports</a> adding Java classes and JARs to the dynamic classpath, but not to the static one &#8211; we need to manually add a <i>classpath.txt</i> or <i>javaclasspath.txt</i> to the deployment folder, complete with the deployment target&#8217;s correct full path. Naturally this is problematic when we wish to grant the user the flexibility of installing the deployed application anywhere on their computer disk.</li>
<li>The <i>javaclasspath.txt</i> file is only supported on R2012b onward. The <i>classpath.txt</i> file is supported in both old and new releases, but (1) modifying it in Matlab&#8217;s installation folder may require system privileges, and (2) require update upon each and every Matlab reinstallation or upgrade. A <i>classpath.txt</i> file from one Matlab release will <b>NOT</b> be compatible with another Matlab release &#8211; if we try using an incorrect file Matlab will crash or hang. If you are not using just a single matlab release, this quickly turns into a maintenance nightmare.</li>
<li>The <i>javaclasspath.txt</i> file loads the user-specified classes <b>after</b> those loaded in Matlab&#8217;s pre-defined <i>classpath.txt</i>. If we edit The <i>classpath.txt</i> file, we can place our classes at the top of the file, but this again entails the maintenance nightmare described above</li>
</ol>
<p>Luckily, there are a few hacks that can alleviate some of the pain when dealing with deployed applications that use static Java classes:</p>
<h3 id="retrofit">Fixing javaclasspath.txt in run-time</h3>
<p>At the very top of our main function, we could fix (or create) the <i>javaclasspath.txt</i> file to include the current folder&#8217;s actual full path, and then relaunch the application and exit the current session. The newly-launched application will use this <i>javaclasspath.txt</i> file and everything should work well from that moment onward. Here&#8217;s a bare-bones implementation example:</p>
<pre lang='matlab'>
function mainProgram()
   if ~exist('javaclasspath.txt','file')
      try
         fid = fopen('javaclasspath.txt', 'wt');
         fprintf(fid, [pwd '/classesFolder/']);  % add folder of *.class files
         fprintf(fid, [pwd '/subFolder/classes.jar']);  % add jar/zip file
         fclose(fid);
         system(['./' mfilename ' &']);
      catch err
         msg = sprintf('Could not create %s/javaclasspath.txt - error was: %s', pwd, err.message);
         uiwait(msgbox(msg, 'Error', 'warn'));  % need uiwait since otherwise exit below will delete the msgbox
      end
      exit
   end
   % If we reached this point, then everything is ok - proceed normally
   ...
</pre>
<p>A related solution is to recreate the <i>classpath.txt</i> file using the build-generation script, as <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/9220675/matlab-compiler-mcc-errors-on-imports-for-java-classes-from-dynamic-java-classpath#comment-11633978">described by Andrew Janke</a>.</p>
<h3 id="preload">Preloading Java class files in javaclasspath.txt</h3>
<p>Class folders and JAR/ZIP files can be loaded <b>before</b> those in <i>classpath.txt</i>, without having to modify the system&#8217;s <i>classpath.txt</i>, as <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/16366059/best-way-to-override-matlabs-default-static-javaclasspath#answer-16427288">exposed by Christopher Barber</a>. All we need to do is to add a line containing the <code>&lt;before&gt;</code> string as a separate line in our <i>javaclasspath.txt</i> user-file. All entries beneath this line will be loaded into the front (rather than the end) of the static Java classpath. For example:</p>
<pre lang='text'>
# This will be placed at the end of the static Java classpath
C:\placed\at\the\end\of\the\static\classpath\mylib1.jar
<before>
# This will be placed at the beginning of the static Java classpath
C:\placed\at\the\top\of\the\static\classpath\mylib2.jar
</pre>
<h3 id="dynamic">Loading Java class files into the static classpath in run-time (!)</h3>
<p>The crown jewels in Java static classpath hacking belong without a doubt to power-users Andrew Janke and Amro. Based on <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/16366059/best-way-to-override-matlabs-default-static-javaclasspath#comment-24557243">Amro&#8217;s tip</a> (based on a <a target="_blank" rel="nofollow" href="https://community.oracle.com/message/5205737#5203737">Java forum post</a> from back in 2002), <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/19625073/how-to-run-clojure-from-matlab/22524112#22524112">Andrew created</a> a Matlab function that loads a Matlab class into the static classpath <b>at run-time</b> (i.e., without needing to modify/create either <i>classpath.txt</i> or <i>javaclasspath.txt</i>), slightly modified by me to include an optional classname input arg. Here&#8217;s the resulting <i><b>javaaddpathstatic</b></i> function:</p>
<pre lang='matlab'>
function javaaddpathstatic(file, classname)
%JAVAADDPATHSTATIC Add an entry to the static classpath at run time
%
% javaaddpathstatic(file, classname)
%
% Adds the given file to the static classpath. This is in contrast to the
% regular javaaddpath, which adds a file to the dynamic classpath.
%
% Files added to the path will not show up in the output of
% javaclasspath(), but they will still actually be on there, and classes
% from it will be picked up.
%
% Caveats:
%  * This is a HACK and bound to be unsupported.
%  * You need to call this before attempting to reference any class in it,
%    or Matlab may "remember" that the symbols could not be resolved. Use
%    the optional classname input arg to let Matlab know this class exists.
%  * There is no way to remove the new path entry once it is added.
% Andrew Janke 20/3/2014 http://stackoverflow.com/questions/19625073/how-to-run-clojure-from-matlab/22524112#22524112
parms = javaArray('java.lang.Class', 1);
parms(1) = java.lang.Class.forName('java.net.URL');
loaderClass = java.lang.Class.forName('java.net.URLClassLoader');
addUrlMeth = loaderClass.getDeclaredMethod('addURL', parms);
addUrlMeth.setAccessible(1);
sysClassLoader = java.lang.ClassLoader.getSystemClassLoader();
argArray = javaArray('java.lang.Object', 1);
jFile = java.io.File(file);
argArray(1) = jFile.toURI().toURL();
addUrlMeth.invoke(sysClassLoader, argArray);
if nargin > 1
    % load the class into Matlab's memory (a no-args public constructor is expected for classname)
    eval(classname);
end
</pre>
<p>The usage is super simple: instead of using <i><b>javaaddpath</b></i> to load a class-files folder (or ZIP/JAR file) into Matlab&#8217;s <i>dynamic</i> Java classpath, we&#8217;d use <i><b>javaaddpathstatic</b></i> to load the same input into the <i>static</i> classpath &#8211; in <b>runtime</b>.<br />
As Andrew notes, there are important caveats to using the new <i><b>javaaddpathstatic</b></i> function. One of the important caveats is that the class needs to be loaded before Matlab gets around to &#8220;discover&#8221; that it does not exist, because from then on even if we load the class into the static classpath, Matlab will report the class as missing. Therefore, we need to call <i><b>javaaddpathstatic</b></i> at the very top of the program (possibly even in our <i>startup.m</i> file). Moreover, if we directly call the class anywhere in the same m-file as our call to <i><b>javaaddpathstatic</b></i>, it will fail. The reason is that Matlab&#8217;s built-in interpreter processes the direct Java call when it pre-parses the file, before the <i><b>javaaddpathstatic</b></i> had a chance to run:</p>
<pre lang='matlab'>
function this_Will_Fail()
   % mylib.jar contains the com.app.MyClass class
   javaaddpathstatic([pwd '/mylib.jar']);
   obj = com.app.MyClass;  % this will fail!
</pre>
<p>Instead, we need to prevent the interpreter from processing the class before run-time, by loading the class at run-time:</p>
<pre lang='matlab'>
function this_Should_Work()
   % mylib.jar contains the com.app.MyClass class
   javaaddpathstatic([pwd '/mylib.jar']);
   obj = javaObject('com.app.MyClass');  % this should work ok
</pre>
<p>At least in one case, for a recent client project that required deploying a compiled Matlab application that used JDBC to connect to a database (and therefore relied on the static classpath), this saved the day for me.<br />
I&#8217;m sad I wasn&#8217;t aware of this years ago, but now that I have posted it, we have less of an excuse to complain about static classpath files in Matlab. Hopefully MathWorks will incorporate this idea into Matlab so that we can more easily load classes into the static classpath in runtime, and remove the need for ugly deployment hacks (and yes, this includes <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/answers/101206-how-can-i-use-the-database-toolbox-to-connect-to-a-database-using-a-jdbc-driver">MathWorks&#8217; own toolboxes</a>), hopefully removing the caveats listed above along the way.</p>
<h3 id="analyze">Analyzing loaded Java classes in run-time</h3>
<p>A related Matlab function, <i><b>whereisjavaclassloadingfrom</b></i>, <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/4376565/java-jpa-class-for-matlab#4380622">was posted</a> by Andrew Janke to report information about loaded classes, including whether they were loaded by the static (=standard Java) classloader, or the dynamic (=MathWorks&#8217; custom) classloader, and from which location. For example:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;"><span style="color: #228B22;">% This is loaded into the static classpath as part of Matlab's standard classpath.txt file:</span>
&gt;&gt; whereisjavaclassloadingfrom<span style="color: #080;">(</span><span style="color:#A020F0;">'java.util.HashMap'</span><span style="color: #080;">)</span>
Version: 8.6.0.232648 <span style="color: #080;">(</span>R2015b<span style="color: #080;">)</span>
Class:       java.<span style="">util</span>.<span style="">HashMap</span>
ClassLoader: sun.misc.Launcher$AppClassLoader@69365360
URL:         jar:file:/C:/Program%20Files/Matlab/R2015b/sys/java/jre/win64/jre/lib/rt.jar!/java/util/HashMap.class
&nbsp;
<span style="color: #228B22;">% This is loaded into the dynamic classpath using MathWorks' custom classloader</span>
&gt;&gt; javaaddpath<span style="color: #080;">(</span><span style="color:#A020F0;">'C:\Yair\Work\MultiClassTableModel'</span><span style="color: #080;">)</span>
&gt;&gt; whereisjavaclassloadingfrom<span style="color: #080;">(</span><span style="color:#A020F0;">'MultiClassTableModel'</span><span style="color: #080;">)</span>
Version: 8.6.0.232648 <span style="color: #080;">(</span>R2015b<span style="color: #080;">)</span>
Class:       MultiClassTableModel
ClassLoader: com.mathworks.jmi.CustomURLClassLoader@5270d6ad
URL:         file:/C:/Yair/Work/MultiClassTableModel/MultiClassTableModel.class
&nbsp;
<span style="color: #228B22;">% This is an example of a class that is not loaded</span>
&gt;&gt; whereisjavaclassloadingfrom<span style="color: #080;">(</span><span style="color:#A020F0;">'no.such.Class'</span><span style="color: #080;">)</span>
<span style="color: #FF0000;">Error using <u>javaArray</u>
No class no.such.Class can be located on the Java class path
Error in <u>whereisjavaclassloadingfrom</u> (<u>line 25</u>)</pre>
</div>
</div>
<h3 id="end">Parting words</h3>
<p>How risky is all this in terms of future compatibility? well, I&#8217;m not a prophet, but I&#8217;d say that using these hacks is pretty risky in this regard. Matlab&#8217;s custom classloader is way-deep in undocumented territory. This does not mean that the functionality will change tomorrow, but don&#8217;t be surprised if and when it does.<br />
Have you ever used any additional undocumented hack relating to using the Java classpaths in Matlab? If so then please post a comment below.<br />
Users who have endured my post this far, should probably also read my related article about <a target="_blank" href="/articles/java-class-access-pitfalls">Java class access pitfalls</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/static-java-classpath-hacks">Static Java classpath hacks</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-java-interface-using-static-control" rel="bookmark" title="Matlab-Java interface using a static control">Matlab-Java interface using a static control </a> <small>The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/java-class-access-pitfalls" rel="bookmark" title="Java class access pitfalls">Java class access pitfalls </a> <small>There are several potential pitfalls when accessing Matlab classes from Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-internal-java-class-members" rel="bookmark" title="Accessing internal Java class members">Accessing internal Java class members </a> <small>Java inner classes and enumerations can be used in Matlab with a bit of tweaking. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/listbox-selection-hacks" rel="bookmark" title="Listbox selection hacks">Listbox selection hacks </a> <small>Matlab listbox selection can be customized in a variety of undocumented ways. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/static-java-classpath-hacks/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
	</channel>
</rss>
