tag:blogger.com,1999:blog-6652703120966123952024-03-14T06:26:14.494+01:00XMedekO's blogBlog of Ondrej Medek, alias Ondra, aka XMedekO, or MeDon.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.comBlogger46125tag:blogger.com,1999:blog-665270312096612395.post-70696404524957608762019-04-27T21:09:00.001+02:002019-10-11T10:17:50.124+02:00Running Docker on Windows 10 HomeIf you try to install <a href="https://docs.docker.com/docker-for-windows/">Docker for Windows</a> on Windows 10 Home edition, it would fail with a message that it requires Windows Professional. The reason is, that the current Docker requires <a href="https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/enable-hyper-v">Hyper-V enabled</a>. But do not worry. If you have a CPU with Hyper-V (<a href="https://www.thewindowsclub.com/check-intel-amd-processor-supports-hyper-v">you can check it with msinfo32</a>), there's a way, how install Docker on your machine. All credits goes to the Docker users <a href="https://forums.docker.com/t/installing-docker-on-windows-10-home/11722/25">in this forum post</a>, especially to Marcel Hesselbarth and his blog <a href="https://www.deskmodder.de/blog/2018/08/23/windows-10-home-hyper-v-aktivieren/">Windows 10 Home Hyper-V aktivieren</a> (in German).
<br />
<br />
<b>1.</b> Make a file <code>hyperv.bat</code> file and run is at Administrator:<br />
<pre class="prettyprint">@rem Install Hyper-V on Windows Home
pushd "%~dp0"
dir /b %SystemRoot%\servicing\Packages\*Hyper-V*.mum >hyper-v.txt
for /f %%i in ('findstr /i . hyper-v.txt 2^>nul') do dism /online /norestart /add-package:"%SystemRoot%\servicing\Packages\%%i"
del hyper-v.txt
Dism /online /enable-feature /featurename:Microsoft-Hyper-V -All /LimitAccess /ALL
pause
</pre>
You need to reboot a computer after that.
<br />
<br />
<b>2.</b> Change your registry: <code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion</code> and change <code>EditionID</code> from <code>Core</code> to <code>Professional</code>
<br />
<br />
<b>3.</b> Install <a href="https://docs.docker.com/docker-for-windows/">Docker for Windows</a>.
<br />
<br />
<b>4.</b> Change your registry back.
<br />
<br />
And voilà, we have a Docker running on Windows 10.
Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-10165927638878935312017-10-05T08:10:00.000+02:002019-04-27T21:08:34.630+02:00Python logger by classCommon Python logging practice is to have one logger per module (e.s. <a href="https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/">see the Fang's blog</a>):<br />
<pre class="prettyprint lang-py">import logging
logger = logging.getLogger(__name__)
</pre>
However, the general habit in other OOP programming languages (Java, C#, ...) is to have one (private static) logger per class:
<br />
<pre class="prettyprint lang-java">public class MyObject {
private final static Logger LOG = Logger.getLogger(MyObject.class.getName());
}
</pre>
In Python, a logger per class may be created, too:
<br />
<pre class="prettyprint lang-py">import logging
class Foo(object):
__log = logging.getLogger(__name__ + '.Foo')
def foo(self):
self.__log.info('foo called')
class Bar(Foo):
__log = logging.getLogger(__name__ + '.Bar')
def bar(self):
self.__log.info('bar called')
bar = Bar()
bar.foo()
bar.bar()
>>> INFO:__main__.Foo:foo called
>>> INFO:__main__.Bar:bar called
</pre>
<br />
Note the double leading underscore <code>__log</code> to exploit the <a href="https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles">Python name mangling</a> to simulate a private attribute.
However, it is not very convenient to write the name of the class as a string. One way to avoid that is to init the logger after the class has been created:
<br />
<pre class="prettyprint lang-py">class Bar(Foo):
def bar(self):
self.__log.info('bar called')
Bar._Bar__log = logging.getLogger(__name__ + Bar.__name__) # manual name mangling
</pre>
Still not very nice. We had to type the name of the class manually again. So let's exploit a decorator black magic to do it automatically:
<pre class="prettyprint lang-py">def addlogger(cls: type):
aname = '_{}__log'.format(cls.__name__)
setattr(cls, aname, logging.getLogger(cls.__module__ + '.' + cls.__name__))
return cls
@addlogger
class Foo(object):
def foo(self):
self.__log.info('foo called')
@addlogger
class Bar(Foo):
def bar(self):
self.__log.info('bar called')
bar = Bar()
bar.foo()
bar.bar()
>>> INFO:__main__.Foo:foo called
>>> INFO:__main__.Bar:bar called
</pre>
And voilà, we have a private static logger for each class with just one simple line or code.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-58136913578088684982016-10-19T09:50:00.001+02:002016-10-19T09:52:38.319+02:00.NET and Windows proxy problemsWindows has two HTTP APIs, which are unfortunatelly not 100% compatible in case of proxy settings:<br />
<ul>
<li><i>WinINet</i>, used by Internet Explorer and most of the Windows C/C++ applications. Window proxy settings dialog sets the proxy for the WinINet</li>
<li><i>WinHTTP</i> used by .NET.</li>
</ul>
So, when you develop a .NET application, is may happen that on a certain computer the Internet Explorer and other apps are connecting well, while your .NET app cannot connect to the Internet.<br />
Since some proxy settings are hidden to the user by the "Automatically detect settings"checkbox, I have made a simple program <a href="https://github.com/xmedeko/WinProxyViewer">WinProxyViewer</a>, which may be run with a inexperienced user and the result sent to the application authors.<br />
<br />
<h3>
Default Credentials</h3>
<br />
.NET does not pick up the proxy credentials entered in the Windows proxy settings, e.g. see this <a href="http://stackoverflow.com/questions/299940/">StackOverflow thread</a>. One solution is to add to the application config:<br />
<br />
<pre class="prettyprint lang-xml"><system .net="">
<defaultproxy usedefaultcredentials="true" />
</system>
</pre>
But I preffer the solution in the code (at least for the desktop apps):
<br />
<pre class="prettyprint lang-cs">try
{
System.Net.IWebProxy proxy = System.Net.WebRequest.DefaultWebProxy;
PropertyInfo propInfo = proxy.GetType().GetProperty("WebProxy", BindingFlags.NonPublic | BindingFlags.Instance);
((System.Net.WebProxy)propInfo.GetValue(proxy)).UseDefaultCredentials = true;
}
catch (Exception ex)
{
// log the exception
}
</pre>
<br />
<h3>
More proxies</h3>
<br />
The automatic proxy script for the <i>WinINet</i> may contain more proxy servers. The <i>WinINet</i> chooses next cycle the list until it finds the first proxy working. While the .NET (<i>WinHTTP</i>) use the <b>first proxy from the list always</b>, event when it does not work. So the .NET app may be disconnected, while the Internet Explorer is working. There is not known remedy for that. Fortunately, such situations are very rare.<br />
<br />
<h3>
NTLM proxy</h3>
<br />
.NET (<i>WinHTTP</i>) cannot automatically detect NTLM proxy and use Window credentials for it like the <i>WinINet</i>. There is not known remedy for that. NTLM proxies are sometimes used in the enterpise environments.<br />
<br />
<h3>
Summary</h3>
<br />
.NET app cannot be 100% compatible with all the Windows proxy settings. A possible solution for that is to have own proxy settings in the app. But the app may be used by people who cannot (security or have no knowledge) to set the proxy settings in the .NET app. So they may be situations, when .NET stays disconnected.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com2tag:blogger.com,1999:blog-665270312096612395.post-29152699390396446662016-05-19T21:56:00.001+02:002016-05-27T10:59:51.568+02:00Atlassian Bamboo and xUnit testingI needed to run <a href="https://xunit.github.io/">xUnit</a> test on the Atlassian Bamboo Cloud (OnDemand) build server. It has no runner for xUnit, but can be run from the command line by <a href="https://xunit.github.io/docs/getting-started-desktop#run-tests">xunit.runner.console</a>.<br />
<br />
<h3>
Configure your build server</h3>
<br />
On the build server, just NuGet the runner:<br />
<pre class="prettyprint">nuget.exe xunit.runner.console</pre>
The Bamboo cannot parse xUnit output. It can handle the nUnit output nd the xUnit has an option to print results in the nUnit format. So, create a simple <code>xunit.cmd</code> script:
<br />
<pre class="prettyprint">@echo off
@rem xunit runner for Bamboo
if "%2"=="" (
echo Usage: test.dll report.xml
exit /b 1
)
if not exist %~dp2 mkdir %~dp2
"c:\path\to\xunit.runner.console.2.1.0\tools\xunit.console.exe" %1 -nunit %2
</pre>
<br />
<h3>
Configure Bamboo</h3>
<br />
Then go to your <i>Bamboo Administration - Agents Summary</i> and choose your agent. Add a new capability:
<br />
<table>
<tbody>
<tr><td>Capability type</td><td><b>Executable</b></td>
</tr>
<tr><td>Executable label</td><td><b>xUnit</b></td>
</tr>
<tr><td>Path</td><td><code>c:\path\to\xunit.cmd</code></td>
</tr>
</tbody></table>
<br />
To add the xUnit to you plan's job, just add the Command task after the project build (e.g. MSBuild, or NAnt). I expect you have a module MyProjectTests in your solution. Then configure the xUnit task:
<br />
<table>
<tbody>
<tr><td>Executable</td><td><b>xUnit</b></td>
</tr>
<tr><td>Argument</td><td><code>bin\Release\MyProjectTests.dll test-reports\MyProjectTests.xml</code></td>
</tr>
<tr><td>Working sub directory</td><td><code>MyProjectTests</code></td>
</tr>
</tbody></table>
<br />
The final trick is to add the NUnit Parser task, just take care to put is as the <b>final task</b>:
<br />
<table>
<tbody>
<tr><td>NUnit Test Results File/Directory</td><td><code>MyProjectTests/test-reports/*.xml</code></td>
</tr>
</tbody></table>
<br />
The bamboo logic is, that:
<br />
<ol>
<li>Any task fails, and no test result is found, it assumes the compilation error has occurred.
</li>
<li>Any task fails, and a test result is found, it assumes a test has failed.
</li>
<li>All tasks pass, the build is OK. If the test results are found, they are picked up.
</li>
</ol>
Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-90144071492374754012016-03-18T17:39:00.000+01:002016-03-18T17:40:50.792+01:00C# Caliburn.Micro Check Unmatched Elements<a href="http://caliburnmicro.com/">Caliburn.Micro</a> is a great C# MVVM framework. It saves the developer's fingers with the binding by the <code>x:Name</code> convention:
<pre class="prettyprint lang-xml"><textbox x:name="Username" /></pre>
However, when one mistypes the <code>x:Name</code> or rename the property in the ViewModel then the Caliburn silently does not apply the binding. Such mistakes are hard to track. Fortunately Caliburn comes with the help of <code>ViewModelBinder.HandleUnmatchedElements</code>. We have a simple rule in the project: if the <code>x:Name</code> starts with the capital letter, then it has to be binded by the Caliburn. Then I have been able to plug in a simple method to check for unmathched elements starting with the capital:
<pre class="prettyprint lang-csharp">ViewModelBinder.HandleUnmatchedElements = (elems, type) =>
{
if (!elems.Any())
return;
// elems with Name with the first letter upper case
elems = elems.Where(e => !string.IsNullOrEmpty(e.Name) && e.Name.StartsWith(e.Name.Substring(0, 1).ToUpperInvariant()));
if (!elems.Any())
return;
throw new InvalidOperationException(type + " contains Caliburn unmatched elements " + string.Join(",", elems.Select(e => e.Name)));
};
</pre>
Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-90658194310021787462015-06-08T17:49:00.001+02:002016-05-20T08:33:48.575+02:00C# Safe Event PatternC# language has a very good support for event programming. However, is does not address a two common issues with event handlers:
<ol>
<li>An event handler is registered more times, but we want to call it just once.</li>
<li>An event handler is registered from longer living object then the event source. Then the event handler must be unregistered. Otherwise it may cause memory leaks.</li>
</ol>
First issue is usually simple to solve. The memory leaks are best avoided when using weak references. There are several solutions to .NET weak event references. e.g. see <a href="http://www.codeproject.com/Articles/738109/The-NET-weak-event-pattern-in-Csharp">The .NET weak event pattern in C#</a>. I have decided to go with .NET 4.5 <code><a href="https://msdn.microsoft.com/en-us/library/system.windows.weakeventmanager%28v=vs.110%29.aspx">WeakEventManager</a></code>. The following pattern makes it easy for <code>MyEvent</code> consumer to write the code without worrying about event handler unregistering.
<pre class="prettyprint lang-cs">
private event MyEventArgs _myEvent;
public event EventHandler<MyEventArgs> MyEvent
{
add
{
// first unregister if registered
MyEvent-= value;
// register
WeakEventManager<ThisType, MyEventArgs>.AddHandler(_myEvent, "MyEvent", value);
}
remove
{
WeakEventManager<ThisType, MyEventArgs>.RemoveHandler(_myEvent, "MyEvent", value);
}
}
</pre>
Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-75151178651659097422015-05-19T08:03:00.001+02:002015-05-19T08:03:30.837+02:00Log4net Configuration for Desktop ApplicationI have configured <a href="https://logging.apache.org/log4net/">log4net</a> for out current project, a plain Windows Desktop application. I wanted log to rolling file into the <code>AppData\Local</code> folder. Not the Roaming folder, since log are specific to the machine and it is waste of resources to let them roam around. Also I wanted to see logs in console, but in DEBUG mode only, not in production.
First problem to find the <code>AppData\Local\MyAppName</code> has been solved by <code>log4net.Util.PatternString</code> class. It parses a special <code>%envFolderPath</code> and <code>%appdomain</code> patterns.
The second problem, to configure <code>ConsoleAppender</code> just in DEBUG mode has several solutions. It is possible to load different configs, or to configure <code>ConsoleAppender</code> programatically. I have decided to create own <code>DebugFilter</code>, which denies all log in production mode. This way I have just one log4net config file. The cons is that it is very slightly less efficient to have configured an Appender which denies all log, but it's OK for most of applications.
<pre class="prettyprint lang-xml">
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%envFolderPath{LocalApplicationData}\%appdomain\log.txt" />
<appendToFile value="true" />
<maxSizeRollBackups value="2" />
<maximumFileSize value="10MB" />
<rollingStyle value="Size" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
<filter type="cvtBackend.Logging.DebugFilter" />
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="INFO" />
<appender-ref ref="RollingLogFileAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
</pre>
And the <code>DebugFilter</code>:
<pre class="prettyprint lang-csharp">
/// <summary>
/// log4net filter which allows logging in DEBUG mode only.
/// </summary>
public class DebugFilter : FilterSkeleton
{
public override FilterDecision Decide(LoggingEvent loggingEvent)
{
#if DEBUG
return FilterDecision.Neutral;
#else
return FilterDecision.Deny;
#endif
}
}
</pre>Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-91009541165943250762015-02-13T11:53:00.000+01:002015-06-08T17:49:45.002+02:00Java: Fast Date Formatting in Web ContainersJava <a href="http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html"><code>SimpleDateFormat</code></a> is not thread safe. When it is used in multithreaded applications, like Java web containers, it's forbidden use it as a static constant
<br />
<pre class="prettyprint lang-java">public static final DateFormat DATE_FORMAT = new SimpleDateFormat('YYYY.MM.dd'); // DON'T!
</pre>
Most developers properly constructs new <code>SimpleDateFormat</code> everytime they need<br />
<pre class="prettyprint lang-java">DateFormat dateFormat = new SimpleDateFormat('YYYY.MM.dd');
String str = dateFormat.format(date);
</pre>
However, constructing new SimpleDateFormat is not so cheap operation. So, how to safe CPU and memory like in static final pattern in a multithreaded environment?<br />
<br />
<h3>Solution 1: clone</h3>
<br />
Fortunatelly, <code>SimpleDateFormat</code> implements <code>clone()</code> method, which is fasters than constructing a new one form a <code>String</code>:
<pre class="prettyprint lang-java">private static final DateFormat DATE_FORMAT_TEMPLATE = new SimpleDateFormat('YYYY.MM.dd'); // Do not use directly
/**
* @return every time a new SimpleDateFormat.
*/
public static DateFormat getDateFormat() {
return DATE_FORMAT_TEMPLATE.clone();
}
</pre>
<br />
<h3>Solution 2: ThreadLocal</h3>
<br />
A general solution for sharing non-thread safe objects is to have one copy for each thread. Java has a very nice <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html"><code>ThreadLocal</code></a>. Together with lazy initialization we got the proper thread safe and fast solution:
<pre class="prettyprint lang-java">private static final ThreadLocal DATE_FORMAT_TL = new ThreadLocal<DateFormat>() {
protected DateFormat initialValue() {
return new SimpleDateFormat('YYYY.MM.dd');
};
};
/**
* @return SimpleDateFormat, new one for every thread.
*/
public static DateFormat getDateFormat() {
return DATE_FORMAT_TL .get();
}
/**
* Simple, optimized Date formatting.
*/
public static String format(Date d) {
return format == null ? null : getDateFormat().format(d);
}
</pre>
This solution has advantage over <code>clone()</code> method, that calling <code>getDateFormat()</code> multiple times in one thread (e.g. inside a loop) does not create a new object. I like to add <code>format()</code> to simplify usage and handle null values.
Note: ThreadLocal may cause redeploy memory leaks when it's value from a WAR class. E.g. see <a href="http://xmedeko.blogspot.cz/2010/02/java-web-container-hunting-redeploy.html">Java Web Container: Hunting Redeploy Memory Leaks</a>Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-57795260457623461732014-12-12T12:31:00.001+01:002015-06-08T17:49:57.756+02:00Git error: Short SHA1 is AmbiguousGit allows using shortened SHA1 hashes. Default is to use 7 characters (see <code>core.abbrev</code> config option). But sooner or later, you may hit problem, that short hashes are ambiguous. E.g.
<br />
<pre class="prettyprint lang-bash">$ git log 0ed98e5
...
error: short SHA1 0ed98e5 is ambiguous
</pre>
<br />
To find, what Git objects are referenced by the same short has, use
<br />
<pre class="prettyprint lang-bash">$git rev-parse --disambiguate=0ed98e | git cat-file --batch-check
0ed98e56dd43b172d438dba0aa6ea9ebed0554c7 commit 307
0ed98e50771521f9ec27314d49286fd54e989c87 blob 1478
0ed98e50771521f9ec27314d49286fd54e989c87 blob 1478
</pre>
<br />
In this case, only the first hash (0ed98e56) refers to a commit. The second hash (0ed98e50) refers to a blob - file. So, Git does check SHA1 for all it's objects, not only for commits, although the <code>git log</code> command uses just commits SHA1 for it's arguments.
<br />
<br />
How to fix the error? Use longer prefix of the SHA1 hash. The bulletproof solution is to use all 40 characters. But if you still like abbreviates, then you can find the safe minimum length of SHA1 prefix for your project by <a href="http://blog.cuviper.com/2013/11/10/how-short-can-git-abbreviate/">Josh Stone's solution</a>:
<br />
<pre class="prettyprint lang-bash">$git rev-list --all --abbrev=0 --abbrev-commit | wc -L
</pre>Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-67652369169136001992014-05-15T09:37:00.002+02:002014-05-15T09:48:18.875+02:00Simple console.log wrapper hangs IE10 and ChromeMany programmers write a wrapper around <code>console.log</code> to use logging only when it's available. I have reassigned log to my own variable <code>this.log = console.log;</code> and it has worked fine in Firefox with Firebug plugin. However, it has caused Javascript to stop working in Internet Explorer 10 (IE10) and Chrome. Strange thing is, IE10 hangs only when it has <b>closed</b> the developer tools F12. When I have opened the developer tools to see what's going on, the IE10 has proceeded well.<br />
<br />
<pre class="prettyprint lang-javascript">var mylog = {
log : this._logNull,
init: function() {
if (typeof console == 'object' && typeof console.log == 'function') {
console.log(this);
this.log = console.log; // IE10 hangs bug
//this.log = this._log; // IE10 ok
}
},
_logNull : function() {},
_log : function() { console.log.apply(console, arguments); }
};
</pre>
Try <a href="http://jsfiddle.net/xmedeko/Z9t4p/">the code at JSFiddle</a>.
<br />
<br />
After writing a proper wrapper function _log, the code goes well even in IE10 with closed developer tools.<br />
<br />
Note, this is just proof of concept code for IE10. The real console.log wrapper may become more complicated when considering various browser like Chrome, Safari, etc.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-44370957620590493412013-10-21T16:01:00.003+02:002013-10-21T16:07:24.834+02:00Java Swing: Change Global Action KeyJava Swing Look and Feel defines it's own actions and register them globally on key strokes. It may happen, such a global keystroke is the same you need to use for own action. E.g. you define an action hooked on F8 key in the JPanel. But when the user has focused a JTable inside the JPanel and hit F8, then it still triggers the "focusHeader" action instead your action. One solution is to put your action on every component in the JPanel. Or you can change default keys globally:<br />
<br />
<pre class="prettyprint lang-java">private static void reregisterGlobalKeys() {
// F8 to Ctrl+F8
reregisterGlobalKey("Table.ancestorInputMap", KeyStroke.getKeyStroke(KeyEvent.VK_F8), KeyStroke.getKeyStroke(KeyEvent.VK_F8, KeyEvent.CTRL_DOWN_MASK));
reregisterGlobalKey("SplitPane.ancestorInputMap", KeyStroke.getKeyStroke(KeyEvent.VK_F8), KeyStroke.getKeyStroke(KeyEvent.VK_F8, KeyEvent.CTRL_DOWN_MASK));
}
private static void reregisterGlobalKey(String uiManagerKey, KeyStroke oldKeyStroke, KeyStroke newKeyStroke) {
Object inputMapObj = UIManager.get(uiManagerKey);
if (inputMapObj == null || !(inputMapObj instanceof InputMap)) {
System.err.println("reregisterGlobalKey inputMap not found: " + uiManagerKey);
return;
}
InputMap inputMap = (InputMap) inputMapObj;
String actionCommand = (String) inputMap.get(oldKeyStroke);
if (actionCommand == null) {
System.err.println("reregisterGlobalKey actionCommand not found for inputMap: " + uiManagerKey + " keyStroke: " + oldKeyStroke);
return;
}
inputMap.remove(oldKeyStroke);
if (newKeyStroke != null) {
inputMap.put(newKeyStroke, actionCommand);
}
}
</pre>
<br />
Keep in mind that these uiManagerKeys and key strokes are Look and Feel dependend.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-84739230133249678192013-04-25T16:05:00.004+02:002013-04-25T16:05:49.819+02:00Guava ClassPath SuiteSometimes, one needs to run just a subset of <a href="http://junit.org/">JUnit</a> test. The very good library <a href="http://johanneslink.net/projects/cpsuite.jsp">ClassPathSuite</a> (cpsuite) address this problem and is able to select test based on a class name, or another class properties (annotation, super class, etc.)<br />
<br />
In our project, we have needed a little bit more complicated filter conditions than it offers. Afters studying ClassPathSuite and <a href="https://code.google.com/p/guava-libraries/">Google Guava</a> internals, I just figure out, some kind of more flexible ClassPathSuite can be created using Guava <code>Predicate</code> and <code>ClassPath</code> classes. So I have coded just one core file, <code>GuavaClassPathSuite</code> which does what we need - scans the class path for JUnit tests and filter them by user defined Predicates. I have pushed the solution to GitHub as <a href="https://github.com/xmedeko/gcpsuite">gcpsuite</a>, <a href="https://github.com/xmedeko/gcpsuite">Guava ClassPath Suite</a>, project. (Not very distinct name, but points to the Guava <code>ClassPath</code>).
Either use it as a library, or simply copy&paste the <code>GuavaClassPathSuite.java</code>, write your predicates and enjoy!Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-45313589889267246262012-09-13T08:40:00.004+02:002013-07-15T13:22:39.563+02:00Java Swing: MigLayout, JScrollPane and JTextField Showing Horizontal Scrollbar<a href="http://www.miglayout.com/">MigLayout </a>is a great layout manager for Java Swing. However, it needs some time to discover it's nooks and crannies. One common problem is with components inside <code><a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html">JScrollPane</a></code>. <br />
<br />
We place all components inside the <code>JPanel</code>, which has a <code>JScrollPane</code> as parent. And we use MigLayout mostly with <code>fill</code> and <code>grow</code> parameters. Such layout ensures that a user can access all components by scrolling when she has a small screen.<br />
<br />
But I have a faces a problem with <code>JTextField</code> containing a very long text. I usually use MigLayuot<br />
<br />
<pre><b>growx, width 50::</b></pre>
<br />
constraints for text fields. However, when a text files contains a very long String, then it forces JScrollPane to to enlarge it's width and show the horizontal scrollbar. The user usually need the text field to be as long as possible, but not to overflow the screen width, if possible. After a while, I have found a proper and simple solution, just set the preferred size as minimum:<br />
<br />
<pre><b>growx, width 50:50:</b></pre>
<br />
Note: I have described the problem using component constraints, the solution is similar with row constraints<br />
<br />
<pre><b>fill, grow, 50:50:</b></pre>
Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-16104556290907559622012-01-20T09:27:00.000+01:002012-01-20T09:27:29.792+01:00Eclipse: Manual and Automatic Code FormattingI like automatic code formatting in the <a href="http://www.eclipse.org/">Eclipse IDE</a>. For Java see the settings in <code>Window -> Preferences -> Java -> Code Style -> Formatter</code>. I Just hit <code>CTRL+SHIFT+F</code> time from time and let the IDE do the boring job for me. <br />
<br />
Occasionally, I want the different result then the Eclipse Formatter produce. Especially when a method has many parameters. Sometimes I like to have all of them on one line, sometimes I like to break them into multiple times. Of course, the Eclipse automatic formatter cannot be configured to meet wishes.<br />
<br />
The Eclipse formatter has a nice option <code>On/Off Tags</code>:<br />
<ul><li><code>@formatter:off</code></li>
<li><code>@formatter:on</code></li>
</ul>But it's tedious and ugly to write these tags into the code. (Even Code templates does not simply usage of On/Off Tags very much). Much more simpler solution is to append the Java comment <code>//</code> ant the and of line, which you want to break. For example, I have configured the Eclipse formatter to have all method parameters on a single line. But when I write<br />
<pre class="prettyprint lang-java">this.someMethod(param1, //
param2, //
param3, //
param4, //
param5);
</pre>Then the <code>CTRL+SHIFT+F</code> reformatting let this piece of the code as is.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-45066530097509635192011-10-06T14:24:00.002+02:002011-10-06T14:37:01.154+02:00Simple Javascript SCORM 2004 APIJust a very very simple implementation of SCORM 2004 API for LMS (RTS) developers. It implements just basic SCORM 2004 features. Hope, someone else may find it useful, see <a href="http://sites.google.com/site/xmedeko/code/misc/simple-javascript-scorm-2004-api">http://sites.google.com/site/xmedeko/code/misc/simple-javascript-scorm-2004-api</a>.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-70565344063678481752011-05-31T09:51:00.001+02:002011-05-31T13:39:35.624+02:00Java zsyncThe very first implementation of <a href="http://zsync.moria.org.uk/">zsync</a> in Java: <a href="http://sourceforge.net/projects/jazsync/">http://sourceforge.net/projects/jazsync/</a>. It has no release yet, check out the source code from SVN.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-48771601633970044132011-05-11T10:56:00.000+02:002011-05-11T10:56:32.449+02:00ZK-DL Released!<a href="http://zk.datalite.cz/zk-dl">ZK-DL</a>, an extension to the <a href="http://www.zkoss.org/">ZKoss framework</a> (ZK 5), has been released under LGPL just a few weeks ago!. ZK_DL provides especially:<br />
<br />
<ol><li>Integration with Spring.</li>
<li>Flexible listbox, combobox and lovbox (a kind of combobox) components with automatic sorting and searching build upon the Hibernate Criteria API.</li>
<li>And much more, see <a href="http://zk.datalite.cz/zk-dl">http://zk.datalite.cz/zk-dl</a>.</li>
</ol><br />
The documentation is at <a href="http://zk.datalite.cz/zk-dl">http://zk.datalite.cz/zk-dl</a> and the source code can be found at <a href="http://code.google.com/p/zk-dl/">http://code.google.com/p/zk-dl/</a>.<br />
<br />
<b>I have used DL-ZK with EJB3 on JBoss 5.1 successfully.</b> So I had not taken the advantage of ZK-DL Spring integration (IMHO better than original ZK Spring integration). Anyway the ZK-DL listobox, combobox and lovbox components has greatly simplified our development and provided a rich yet simple interface to our users. <br />
<br />
Many thanks to Jiří Bubník and Karel Čemus for their valuable help and cooperation. I wish DL-ZK long life and have many users!Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-63427519961749893302011-03-10T16:38:00.010+01:002011-08-16T16:24:44.013+02:00JPA Queries - A Few Methods to Simplify the Life with JPA/JPQLThe JPA <a href="http://download.oracle.com/javaee/6/api/javax/persistence/Query.html#getSingleResult%28%29"><code>Query.getSingleResult()</code></a> method is usable only when the JPQL has exactly one result. Yeah, you can catch <code>NoResultException</code> or <code>NonUniqueResultException</code> exceptions, but the try ... catch block make the code less readable. So I have coded three static method to overcome this JPA deficiency:<br />
<pre class="prettyprint lang-java">public class Queries {
/**
* @param query
* @return {@code true}, the query has one or more results, otherwise returns {@code false}.
*/
public static boolean hasAnyResult(Query query) {
query.setMaxResults(1);
final List<?> list = query.getResultList();
return list.size() > 0;
}
/**
* @param query
* @return The only one result or {@code null}, when the query has no result.
* @throws NonUniqueResultException
* when the query has more than one result.
*/
public static Object singleResultOrNull(Query query) {
query.setMaxResults(2);
final List<?> list = query.getResultList();
final int size = list.size();
if (size <= 0) {
return null;
}
if (size > 1) {
throw new NonUniqueResultException("result returns more than one element");
}
// return first element from the list
return list.get(0);
}
/**
* @param query
* @return The first result or {@code null}, when the query has no result.
*/
public static Object firstResultOrNull(Query query) {
query.setMaxResults(1);
final List<?> list = query.getResultList();
final int size = list.size();
if (size <= 0) {
return null;
}
if (size > 1) { // should not happened, Hibernate bug?
Logger.getLogger(Queries.class).error("firstResultOrNull more rows returned. setMaxResults(1) does not work?");
}
return list.get(0);
}
/**
* Constructor. No instances.
*/
private Queries() {
}
}
</pre>The <b><code>hasAnyResult</code></b> is the <i>boolean</i> query method - you may test if something exists in database. The best is to use it with some JPQL query returning only id of an entity, e.g.:<br />
<pre class="prettyprint lang-java">Queries.hasAnyResult(em.createQuery("SELECT id FROM Person WHERE ..."));</pre>I think the usage of the <b><code>singleResultOrNull</code></b> is obvious. Use it, when you are sure the result returns one or no result. The exception <code>NonUniqueResultException</code> should warn you that something is wrong, wither the query or the data.<br />
<br />
The <b><code>firstResultOrNull</code></b> returns just the first result of the query. Typically, use it with queries with "ORDER BY" statement, like "get the Person with lowest/highest salary."Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-11667324070295388052011-02-15T15:17:00.003+01:002011-05-20T13:43:36.427+02:00Oracle Like Decode in JasperReportsOracle SQL has a nice function <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions040.htm">DECODE</a>. I am using Java Beans data source for <a href="http://jasperforge.org/projects/jasperreports">JasperReports</a> and sometimes I have missed such a function in JasperReports expressions. One can achieve the same functionality by a <a href="http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html">ternary operator <code>? :<code></code></code></a>. But it is not nice for more complicated conditions. So I have created my own Java decode:<br />
<pre class="prettyprint lang-java">public static Object decode(Object value, Object... arg) {
if (arg == null) {
return value;
}
int n = arg.length;
for (int i = 0; i < n; i+=2) {
int j = i + 1;
if (j >= n) {
// only the default remains
return arg[i];
}
if (equal(value, arg[i])) {
return arg[j];
}
}
// no match found, no default is specified
return value;
}
</pre>Then import it into JasperReports <code>*.jrxml</code> report by:<br />
<pre class="prettyprint lang-xml"><import value="static com.mypackage.MyClass.decode"/>
</pre>And use it in the report like:<br />
<pre class="prettyprint lang-java">"" + decode(count, 0, "no one", 1, "one", 2, "two", "too many: " + count);
</pre>Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-47283521073750141002011-01-25T20:28:00.000+01:002011-01-25T20:28:00.020+01:00ZK and Converting to a Negative NumberWhen I was working with <a href="http://www.zkoss.org/">ZK Web Framework</a>, I have needed to convert some number to the negatives for the databinding. I have created a new type converter <b><code>NumberNegativeConverter</code></b>. Hope, someone else may find it useful, see <a href="http://sites.google.com/site/xmedeko/code/zk-web-framework/numbernegativeconverter">http://sites.google.com/site/xmedeko/code/zk-web-framework/numbernegativeconverter</a>.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-43213697589072344592010-12-03T15:29:00.005+01:002012-07-30T11:09:35.946+02:00Java: A Simple Assert Class for Design By Contract ChecksVery often, the programmer are lazy to include design by contract checks into the code. That means argument checking in the beginning of the method, checking of a wrong state in the method body, etc. The Java <a href="http://download.oracle.com/javase/1.4.2/docs/guide/lang/assert.html">assert</a> construct cannot be used for this purpose, since it is switched off by default (one has tu run <code>java -ea</code> to switch on the Java asserts). To simplify the design by contract checks, I have made three simple static methods:<br />
<br />
<pre class="prettyprint lang-java">/**
* A static class for simple run-time checks. The methods from this class may (and should) be used to check arguments
* and code for design-by-contract.
* <p>
* These are the methods for lazy programmers. If you like to write more complicated messages (and God bless you for
* that), use the classic {@code if (...) throw ... } way.
* <p>
* It is not possible to switch off these checks, do not use them for any memory or CPU consuming operations.
*
* @author xmedeko
*
*/
public class Assert {
/**
* Check, that the condition is {@code true}.
* <p>
* Usage:
*
* <pre>
* Assert.state(i &lt;= maxIter, &quot;iteration number exceeded&quot;);
* </pre>
*
* @param check
* @param message
* An error message.
*/
public static void state(boolean check, String message) {
if (check)
return;
throw new IllegalStateException(message);
}
/**
* Check, that the object is not null.
* <p>
* Usage:
*
* <pre>
* Assert.notNull(entity, &quot;entity&quot;);
* </pre>
*
*
* @param o
* @param message
* An error message.
*/
public static void notNull(Object o, String message) {
if (o != null)
return;
throw new NullPointerException(message);
}
/**
* Check, that the argument fullfills the given condition.
* <p>
* Usage:
*
* <pre>
* Assert.argument(from &gt; 0, &quot;from has to be greater then zero&quot;);
* </pre>
*
* @param check
* @param message
* An error message.
*/
public static void argument(boolean check, String message) {
if (check)
return;
throw new IllegalArgumentException(message);
}
/** No instances. */
private Assert() {
throw new UnsupportedOperationException();
}
}
</pre>
<br />
Note, to check argument for not <code>null</code> value, do not use <br />
<pre class="prettyprint lang-java">Assert.argument(obj != null, "obj is null");
</pre>
but use instead:<br />
<pre class="prettyprint lang-java">Assert.argument(obj != null, "obj");
</pre>
<br />
Also, do not put any String concatenation or other operation into the <code>argument</code>. These are the methods for lazy programmers. If you like to write more complicated messages (and God bless you for that), use the classic <code>if (...) throw ...</code> way.<br />
<br />
<b>Update 29.3.2011:</b> I have just found out that Spring frameworks has <a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/util/Assert.html">org.springframework.util.Assert</a> class, too.
<br />
<b>Update 30.7.2012:</b> Google Guava has a very similar solution in the class <a href="http://code.google.com/p/guava-libraries/wiki/PreconditionsExplained">Preconditions</a>.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-918410263695326512010-12-02T15:05:00.003+01:002011-05-20T13:44:59.329+02:00ZK Calendar ColorsUnfortunately, colours for the <a href="http://code.google.com/p/zkcalendar/">ZK Calendar</a> has to be specified in the Java. They cannot be set in a CSS file. Because writing hexadecimal colour codes directly in the code is error prone, I have created a simple enum constant with a set of ZK Calendar colors:<br />
<br />
<pre class="prettyprint lang-java">public enum ZkCalendarsColor {
GREY("#B4BAB7", "#72706F"),
GREEN("#4CB052", "#0D7813"),
KHAKI("#BFBF4D", "#88880E"),
PURPLE("#B373B3", "#7A367A"),
RED("#D96666", "#A32929"),
BLUE("#668CD9", "#3467CE");
private String contentColor;
private String headerColor;
private ZkCalendarsColor(String contentColor, String headerColor) {
this.contentColor = contentColor;
this.headerColor = headerColor;
}
public String getContentColor() {
return contentColor;
}
public String getHeaderColor() {
return headerColor;
}
}
</pre>Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0tag:blogger.com,1999:blog-665270312096612395.post-50763093924332189432010-10-14T10:24:00.004+02:002011-05-20T13:49:13.698+02:00Fixing Line Terminators for Cygwin CVSI have to use a Windows operating system (unfortunately :-)) and CVS in my current job. Thanks to the <a href="http://www.cygwin.com/">Cygwin</a>, I can work with Windows almost as effectively as in Linux. The CVS (CVSNT) installation in Windows and other CVS tools installed in on my Windows box (TortoiseCVS, Eclipse) stores the CVS files with CRLF line terminators (EOLs). The Cygwin CVS client requires the classic UNIX LT terminator. Fortunatelly, the Windows CVS clients can read the UNIX-way text files, too. So, I have creates a simple bash script to forx this problem:<br />
<pre class="prettyprint lang-sh">#!/bin/sh
find . -type f -path '*/CVS/*' -print0 | xargs -0 dos2unix
</pre>Hope, someone may find it useful.Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com1tag:blogger.com,1999:blog-665270312096612395.post-36679133743681912512010-08-31T11:22:00.001+02:002010-09-03T10:50:17.505+02:00JasperReports PDF Font MappingAre your font <b>bold</b> and <i>italic</i> font properties lost when you export your JasperReports report into the PDF? Do you wander, why PDF preview in the iReport has all fonts right? Check this link out, mate: <a href="http://sites.google.com/site/xmedeko/code/misc/jasperreports-pdf-font-mapping">http://sites.google.com/site/xmedeko/code/misc/jasperreports-pdf-font-mapping</a>Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com2tag:blogger.com,1999:blog-665270312096612395.post-3020705152075523572010-08-05T08:13:00.004+02:002010-09-03T10:50:38.709+02:00JBoss and HSQLDB 2.0.0<a href="http://hsqldb.org/">HSQLBD 2.0 GA</a> has been released on 7 June 2010 with <a href="http://hsqldb.org/web/features200.html">a lot of new cool features</a>. I have needed some of them for my JBoss 5.1.0GA, so I have just replaced the library <code>common/lib/hsqldb.jar</code> and voilà, it runs almost without any problem (Hibernate/JPA usage) as before. I have made just one small change, see bellow. Even the HSQLDB Database Manager starts from JMX console. My personal feeling is that the version 2.0 is a little bit faster than 1.8.0, but I have not made any benchmarks.<br />
<br />
The HSQLDB 2.0 upgrade notes:<br />
<ol><li>In my <code>import.sql</code> I had to change all timestamp formats from <code>'2010-08-06 8:00:00'</code> to <code>'2010-08-06 08:00:00'</code>, i.e. I had to zero pad the hours into two decimal places.</li>
</ol>Ondrej Medekhttp://www.blogger.com/profile/02465917905307330831noreply@blogger.com0