onsdag den 4. juli 2012

Movement speed OVER Magic Find

If you're at the point where you are considering packing on lots of Magic find and going for farms at lower difficulty, consider Movement speed first.

Movement speed(MVS) will boost everything, if you have good enough gear, elite mobs in f.ex. Act I are just a bump.

If you are farming elites only, there will be a lot of running involved. When I do runs, I'm running like 3/4 of the time.

Consider the math.

Movement speed is capped to 25%, you can get there with 12% on boots (obviously) and then mixing in some legendary armour to boost MVS. Equipment tips in the bottom of this article.

Lets say the run takes 30 mins. With 25% MVS, you can decrease it to:
(3/4 X 30 min) X 0,8* + (1/4 X 30 min) = 25.5 min per run
*0,8 is the MVS factor, increasing your MVS by 25%, makes you finish a lap at 80% of the time. That comes to 30 / 25.5 = 1.176, increasing your runs på 17.6%

How does that relate to Magic Find?
Magic find, you can get to 125% very easily, for a total of 200% with Nephalem buffs.

Running 17.6 % faster means you get the equivalent of 200 * 1.176 = 235.2 MF

And it scales very well

With 300% MF at max, you get 300 * 1.176 = 352.8 MF

Conclusion

The higher MF you have the more MVS is worthwhile. MVS at percent by percent starts to outweigh MF at as low levels as 125% MF, also take into consideration the guaranteed rare drops from elite and bosses where you rolled low on MF, you'll get more of those with higher MVS. Also consider that MVS does the exact same thing for Gold Find at the same time. Also consider that Blizzard might nerf MF anytime soon, see Magic Find Gear Swapping

Equipment tips

Don't go for movement speed on weapons, those weapons usually have too poor dps and we need to keep killing fast.

On my build I have 'Inna's glory' pants, with 7% move, 11% MF, a little resist and 140+ vit. Very crappy pants for main build, but excellent for MF build.

For bracers I have 'Lacuni prowlers' woth 6% move, 12% MF, 5% IAS, increased gold pickup. Increased gold pickup is very nice for speeding up runs.

fredag den 27. april 2012

Migrate from SQL Server to MySQL

On 64-bit windows
Download MySQL GUI tools
Make sure to have a 32-bit java
Run tool from CMD line
MySQLMigrationTool.exe -verbose -debug
-jvm "C:\Program Files (x86)\Java\jre7\bin\client\jvm.dll"
Alert box may appear with problem finding msvcr100.dll
In that case, rename msvcr100_clr0400.dll to msvcr100.dll in C:\Windows\SysWOW64
When tool is up and running, choose MS SQL server as source and MySQL as dest
If you are using UTF8, choose multilingualism and shit
Export inserts to a file
Check that encoding is correct with a tool, maybe Notepad++
If not correctly encoded, run tool again till an advanced tab shows you the JDBC connection string
find the string for MS SQL and copy it (UPDATE: its 'characterEncoding=UTF-8')
Go back to 'source selection', click 'advanced', input JDCB string, remove any encoding options
This way, the output is not encoded before being written to output
If encoding still fails, try setting environment option JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8, before running tool again

onsdag den 18. januar 2012

uncheck checkboxes with jQuery

$('input[type=checkbox]').removeAttr('checked');

tirsdag den 1. juni 2010

JavaScript self-replicating program (or Quine)

This program will output the code for itself:
using function.toString()

(function() {var f;function r() {
return "(function() {var f;" + f + ";f=rep.toString();return r();})();";
};f = r.toString();return r();})();

using unescape()

var a = "(function() { return 'var a = ' + unescape('%22') + a + unescape('%22') + ';' + a; })();";(function() { return 'var a = ' + unescape('%22') + a + unescape('%22') + ';' + a; })();

torsdag den 29. oktober 2009

Python UTF-8 for non english characters

Configure module
First make sure your python module is saved as UTF-8

Next, in the top of your python module add the setting:

# -*- coding: utf-8 -*-


this will tell the compiler to use UTF-8 instead of OS specific

Prefix a 'u' for all strings
print u"rødgrød med fløde"

- will work

print "red porridge with cream"

- wil work because no non-english characters are present
(or whatever difference between your OS and UTF-8)

print "rødgrød med fløde"


- will not work because the encoding is misinterpreted

Entire python script

# -*- coding: utf-8 -*-
print u"rødgrød med fløde"

mandag den 31. august 2009

KHAN's ladder to programming excellence!

In Maxwell Gladwells book 'Outliers' he mentions that in order to excel in anything you have to put atleast 10000 hours in to it, which is the equivalent of 6 hours each day in 5 years. 356 * 5 * 6 = 10680, well almost.

Here I present the ladder of programming excellenceu as perceived by me :)
Legend: HoP = Hours of Programming

KHAN's ladder to programming excellence!

I reckoned I hit the programming experience mark of 5000 hours 5 years ago.

Programming in Basic and DOS before my education = 1000 HoP

beginning programmer - 1000 HoP

Programming in high school Assembler, electronics, VB, Java, ASP, HTML: 1000 HoP

greenhorne programmer - 2000 HoP

Higher education as datamatician(mostly Java) 2 1/4 years, with an average of 140 hours a month: 4000 HoP

- at this point I broke the 5000 HoP

jorneyman programmer - 4000 HoP

After the bulk of work with non-contractor jobs 3 years, with an average of 180 hours a month: 6500 HoP
This involved mostly Java with J2EE, but I began on more complex tasks like configuring WebSphere servers, designing parts of enterprise wide technical solutions. Here I picked up many new complex skills, Eclipse RCP, Version control, functional programming, unit testing, server administration etc.
- here i accelarated because I had to break into many new concepts and frameworks, working after hours and reading a lot while experimenting.

veteran programmer - 8000 HoP

At this point I started my own company and began working as a freelancer. I had no products, no particular approach or plan, only my skill as a programmer. Though I discovered I also needed economical and business skills.
In this work I now have 2 years of experience, my pace has slowed down and I would now estimate to having 170 hours per month of IT experience: 4000 HoP, making a total of 16500 HoP.

expert programmer - 16000 HoP

master for me is 5 years away

master programmer - 32000 HoP

I might achieve programming guru before retirement

programming guru - 64000 HoP

//TODO insert lots of effort

deity programmer -
128000 HoP

I think of this scale as a logarithmic one. Each step requires the double amount of effort and I find this to be quite true. At a time while being greenhorne I experienced discovering new things more often, towards becoming a guru I can only guess to what I learn.

mandag den 13. april 2009

Automatically testing advanced web applications (revisited)

More than one and a half years ago I first posted a blog article 'high automatic test coverage of web applications'. While working with this and later projects I realized that in order to have complete coverage and a more dynamic testing environment I had to take it a step further and therefore started inventing my own test framework, described in the article 'full testing with javascript'.

Soon thereafter I discovered the Selenium Core framework which was still rather immature. Since it functions similar to the framework I was working on, I gave it a go and never looked back.

Testing priorities in a web application
When testing you have to first plan what areas need the most testing. Test driven development requires a lot of focus on unit testing and functional testing. I will not discuss unit testing here, since it depends heavily on the platform of the web application.
Aside from unit testing, functional testing is the most important testing for web applications, because it can be used to directly measure progress and prohibits regression.
On a second place comes integration testing, because alot of problems tend to occur in communication with other systems.
In third comes performance testing. This tends to be the focus of automatic tests, but that is an ancient view imo. Performance testing is important, but it's rather easy once functional testing has been done, because you can leverage the functional tests and scale them to performance tests.
On a fourth place comes installation testing. Redeploying a web application is important, both for testing environments, but also for reestablishing an environment.

Functional testing
this is exactly what Selenium is for. It's fast and works for Python, Java and several other popular platforms. I would go for Python because the interactive compiler is killer for writing test cases. Java is not a bad alternative with Seleniums excellent integration with JUnit.
You should not need any other tool for this task.

Performance testing
For performance testing you could use HTTPUnit, which also integrates well with JUnit. It's a rather simple, but powerful framework for controlling all parameters of requests and monitoring the responses.
Functional test cases written for functional testing using Selenium could be rewritten easily and scaled to do performance testing.

Integration testing
This depends on what technology is used for communication, I'll only present the most common one here. Integration in web applications are typically over Web Services, therefore testing could be done with a framework for easily creating web clients, like Axis 2 and using JUnit to execute it, but HTTPUnit is also viable.

Installation testing
Installation testing involves two parts. Scripts to deploy the application and verification of the function.
Scripts would typically depend on the platform of the web application. For WebLogic or WebSphere, you would use ant targets available from the vendor. How you manage to deploy the application automatically is rather irrelevant, since you needn't verify anything during the process.
The second part of verifying function after installation is rather easy, since it's just a matter of running the functional tests.

Conclusion
Using a few open source tools is an easy, fast and effective way to test advanced Web Applications with lots of javascript and complexity.
Standardizing the executing can be achieved using a common executing framework like JUnit.

torsdag den 26. februar 2009

KHANDI the temporal database manager

Introduction
On contract for a customer I had to develop a temporal database manager.

The problem is very simple. You have an entity that exists from a data to another date and is dependent on another entity to exist in the same period.

Consider the example below, this is a valid dependency, because, the dependency exists in atleast the same period as the entity.

Entity
I-------------I

Dependency Entity
I-------------------I

Legend:
lines represent the existance of the entities

Considering you have to edit an entity, you have two basic changes you can make.
Edit attributes of an entity, creating a new record from that point, or
Edit the period in which the entity exists

Editing attributes
Entity
I-------I (attribute changed on this date)
I----I

Dependency Entity
I-------------------I

- dependency is still valid

Editing period
Entity
I-------I (end date of entity is sooner)

Dependency Entity
I-------------------I

- dependency is still valid

Now consider the situation where a user makes an invalid edit.

Invalid edit
Entity
I-------------------I (end date of entity is later)

Dependency Entity
I-------------------I

- dependency is NOT valid

The main point of this last example is that there's a lot of checks that need to be made before editing something.

The database I've made with the customer consists of multiple tables 20+, that are all interdependent.

The component I've written is an ORM with temporal management built-in and transparently handles these relation restrictions as defined in the business logic.

Although very clean, it poses some challenges in a UI. If you need to edit several types of entities in the same submit, you could end up having dependencies, that may put the user in a deadlock. Therefore, one should consider if temporal management of an entitty is really necessary to store temporally.

KHANDI Component short:
temporal ORM manager
compliable with java 1.4
Connects with SAS and MySQL out of the box, easily integratable with other dbs

Write me at kennethhn@gmail.com, if interested in knowing more.

mandag den 12. januar 2009

TOMCAT UTF-8 gotcha

If you are having problem with your encoding running on a platform with other than UTF-8 as a default, try going through your code and make sure request.getParameter() is not called before setting request.setCharEncoding().

example:

request.setCharacterEncoding("UTF-8");
String adUser = request.getParameter(TAM_AD_USER);


If you have no hook for it, consider making a filter: http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html

mandag den 8. september 2008

Full JS applications

Recently I asked my network for novel ideas for small web applications or sites.

My accountant mentioned that he had a hard time calculating distance travelled for some of his customers. He needs to calculate the specific distance for any trip made in a private car for a refund from the danish IRS.

For each trip made by an employee in one of the companies he used to go to a GeoCoding site like http://www.maps.google.com. Plot in 1 trip with From and To addresses, take the distance and put it into a spreadsheet. And so his days went. He made sure to mention to me that it is a problem for many smaller companies.

Using Google's public GeoCoding services I managed to put together an application run entirely by javascript. It is available at http://www.kennethhn.dk/map.html, it is in danish, until I bother using JS I18N. To give it a go, I included a demo, click 'tryk her for hjælp og demo', in the appeared box click 'klikke her'. Then at the bottom of the page click 'beregn alle'. This will calculate all the inputs with the rate of DKK/KM.

Then to print the results click 'print'.

The tricky thing here is to transfer all the data. What I did was serialize all the data in JSON and put it as a parameter for the print page.

Aside from some escape issues, this transfer works perfectly. It might aswell have been a server request, but this way, you don't need all that performance reducing Serverside rendering..

torsdag den 6. marts 2008

cross site javascript

This is an ajax widget I wrote, while learning about cross site scripting (xss). Read more about the Webspace wormhole here.

The idea is that on any page on any browser I should be able to embed this script and it will share content. Much like Google maps and a ton of other useful stuff from Yahoo and Google.

On the page itself the script only needs a small amount of information, like the id of the div it will use for the graphics and what 'tag' it will subscribe to.

The transport it uses is not the typical Ajax.Request from the prototype lbirary, because this uses solely XMLHttpRequest, which for security reasons default in browsers is not cross site.

Instead I had to write a transport of my own. The basic work-around is to embed a script element in the dom created by a dynamic page. This way, when the script is loaded it can inject data into the javascript execution, just like a plain script file. I implemented a reusable class for it, thusly:

var Transport = Class.create({
initialize: function(url, jsonCallback) {
this.url = url;
this.jsonCallback = jsonCallback;
},
activate: function() {
this._cleanUpScript(this.url);
var script_object = new Element('script', {src: this.url, type: 'text/javascript'});
var head=document.getElementsByTagName('head')[0] ;
head.appendChild(script_object);
this._xssScriptLoad();
},
_xssScriptLoad: function() {
var _this = this;
if(typeof(wh_xss_result) != 'undefined') {
this.jsonCallback(wh_xss_result);
void(wh_xss_result);
} else {
setTimeout(function(){_this._xssScriptLoad();}, 100);
}
},
_cleanUpScript: function(url) {
$A(document.getElementsByTagName('script')).each(function(el){
if(el.src == url){
el.remove();
};
});
}
});

The only 'gotcha' here is that I have to know the name of the variable that the result is stored in. This could be set on the serverside if I pass it as a parmater if I want the serverside to be more reusable, but for the sake of my little wormhole, I hardcoded the variable on both sides.

Here is an example usage of the transport:

var url = 'http://www.kennethhn.dk/webhole/get.php?tag=science';
var t = Transport(url, function(json){alert("json object = " + json});
t.activate();

In this case, the url is a reference to a php script on my site that returns a url for content submitted for the tag.

The second argument is a callback function, that will be called with the resulting json object.

The result might look like this:

var wh_xss_result = {
message: 'fetched url for tag science',
result: 'http://tbn0.google.com/images?q=tbn:-U28WILXKSXv5M:http://www.familycourtchronicles.com/philosophy/wormhole/wormhole-diagram.jpg'};

The transport class will then embed the result as a script and set a timeout event to repeat until the browser has loaded the script. Loading of the script is determined by the variable wh_xss_result, which will be 'undefined' until executed.

Xss can be very useful, but also very dangerous, just be vary of what scripts you choose to embed.

Update 13/04/2009: removed the WebSpace wormhole from this page.

tirsdag den 26. februar 2008

Full testing with JavaScript

In my efforts to achieve a full and robust test of web applications I have run into several difficulties.
1. simulating different browsers
2. keeping test scripts simple
3. fragile tests

Simulating different browser


Initially I achieved this using the Canoo Webtest. Though powerful, this integration fo different third party frameworks has shown not to be able to handle JavaScript very well. This means that if you have no control over the javascript in an application, the test becomes very fragile.

Instead I concluded that the best way to simulate the different browsers is not to actually simulate them. Instead it is very efficient to inject JavaScript along with your tests into the page that you wish to test and thereby testing on the executed page.

Several issues comes with this. Firstly, the security in the browser won't allow you to execute JS on another page, if they are not from the same domain, so you have to execute the test from the domain itself. For inhouse testing this is not a problem, but involves some more deployment.

keeping test script simple


This is really up to the implementation of the web application. If its based on poor standard, test script become increasingly difficult. If for example id's are duplicated or tags are broken, the traversal of the DOM becomes difficult. The best solution to this is to stick to strict xhtml and keep your styles in CSS while maintaining ids on all divs.

A second worry is that the script becomes complicated with lots of hacks and too much code, but this is really up to the framework being used. The better the framework and web application coexist, the easier and cleaner the scripts become.

fragile tests


With a low sense of 'standards' in a project, the test become very fragile. The team must agree upon how to use divs and lists etc. Once referring to an id of a div or anchor at a specific position, that has moved or is renamed, the script might have to be rewritten. The framework should help avoid too specific referenced. Whenever referencing an element in the DOM, reference it as lenient as possible.

here is an example of how the framework might be implemented

MyTestFramework.clickLink = function(text) {
$$('a').each(function(el){if(el.innerHTML==text){window.location=el.href}});
}

MyTestFramework.clickLink('login');


I'll be working on this and post when I have a functioning framework. I'll proably pull in some JSUNit library and use that for a backbone for TestCase and TestRunner.

torsdag den 7. februar 2008

Making the BEA Weblogic Portal bookmarkable

The issue


The two big Portal servers I know have problems with state. WebSphere and WebLogic.

It seems as though somewhere along the productline, someone concluded that maintaining state in the portal while having clean bookmarkable URLs and back/forth working, was too much of a hassle, so they decided to disregard bookmarkability and browser history.

In any major portal project I have worked, this issue has come up. The customer says it's a 'need to have', and I agree.. but the portals really should handle this internally.. alas they don't.

A Weblogic solution


Through an experienced BEA developer I heard of a URL-rewriter plugin for the WebLogic portal, which might offer a solution. The idea is pretty straightforward, anywhere a URL is compiled, the URL rewriter is called upon to do it's *magic*.
Decompiled from 'com.bea.portlet.GenericURL', it looks like this:

if(urlRewriterPlugin != null)
{
ServletContext servletContext = UIContext.getFromRequest(httpRequest).getServletContext();
String target = path;
if(path != null || contextualPath != null)
{
DefaultUrl defaultUrl = resolveTemplate(removeUnsetParams);
target = defaultUrl.url;
}
if(scopedRequest != null)
val = urlRewriterPlugin.createUrl(target, params, getUrlType(), isStandalone(), scopedRequest, httpResponse, servletContext);
else
val = urlRewriterPlugin.createUrl(target, params, getUrlType(), isStandalone(), httpRequest, httpResponse, servletContext);
if(debug.ON)
debug.out((new StringBuilder()).append("Output from the URL rewriter: ").append(val).toString());
if(urlCompression != null && !suppressUrlCompression && val != null && !val.startsWith("wsrp_rewrite?"))
val = compress(val);
}


As you can see its a typical adapter pattern. What we can also see is that the URL rewriter also has to address the complexity of ScopedRequest, which is probably used for referencing any resources inside the scope of a portlet.

Implementing the rewriter


Firstly it must implement the interface 'com.bea.portlet.GenericURL.UrlRewriterPlugin'.
this interface forces the method:

public String createUrl(String path, Map parameters, String urlType, boolean
isStandAlone, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext);

Now, there's a lot of different parametres here, but we are only/mostly interested in parameters and the request.
Back to the issue of the ScopedRequest; We actually just want to ignore it, any request string coming in, should be the same coming out with the parameters trailing. In order to disregard a ScopedRequest, you can do something like this:

if(request instanceof ScopedRequestImpl) {
ServletRequest sRequest = ((ScopedRequestImpl) request).getRequest();
request = ((ScopedRequestImpl) request).getOuterRequest();
}

Now you have the original request and you may add any parameters you like. Firstly though, be sure to add all parameters from the Map parameters in order to keep any state the framework put there in the first place.

Example use case


One use of this is to have the portlets react to a parameter on the request. Thereby allowing a bookmarkable URL to return to the same page, with the same information. One side effect of this is that back and forth will be working, since the browser history executes via URLs :).
The responsibility of maintaining the parameters is then up to the portlets themselves. I will leave it up to individual projects to implement a backbone for the portlets communication with the URL rewriter. But using session might be the easy way out..

Registering the URL rewriter


The URL rewriter is retrieved from the request by the framework, but we need a way of putting it there in the first place. The simple solution is to use a filter, so we'll do just that:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain
chain) throws IOException, ServletException {
request.setAttribute(UrlRewriterPlugin.URL_REWRITER_PLUGIN, new MyURLRewriter());
}

and then add the appropriate configuration in the web.xml:

<filter>
<filter-name>URLFilter</filter-name>
<filter-class>com.mycompany.URLFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>URLFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>

Prologue


These few tips should be enough for a developer to implement bookmarkability in a WebLogic portal server. But beware of this solution, since it is highly dependant on the BEA implementation. If any issues regarding bad URLs pop-up, I would refer you to the 'com.bea.portlet.GenericURL' class. See what it does if the URLRewriter is not used. I have implemented a great deal of security around the URLRewriter in order to ensure the state of the portlet and portal. The power of the URLRewriter is great though.. use with caution ;)

credit for an example of this goes to Deepak Natarajan

mandag den 21. januar 2008

Interactive javascript environment

Before I really got into Javascript I experienced it as a necessary evil when constructing web applications.

Though recently because of the added pressure of webapps being interactive, I finally took the bullet and gave object oriented javascript a go.

I was amazed, after going through several tutorials on scriptaculous(based on prototype) and JQuery.

But to really get my groove on I needed the ultimate tools, which I found here: Web Development Bookmarklets.

The JavaScript interactive compiler(drag to bookmarks bar), from web development page. You can click this bookmarklet to open a javascript shell for any page and it keeps its scope across new requests.. Excellent!


here's a bookmarklet for loading prototype on the fly, made this myself :), drag to bookmark bar:

load prototype

Then you may write something like this, in the shell, to print the names of all divs:

$$('div').each(function(element){print(element.name);});

Or this to make all divs blink

$$('div').each(function(element){blink(element);});


You can load any script you want, which is particularly easy in the shell with> load(scriptURL). ex.

load('http://wiki.script.aculo.us/javascripts/prototype.js');
//to add more fun load this:
load('http://wiki.script.aculo.us/javascripts/effects.js');
//shake all divs
$$('div').each(function(divElement){Effect.Shake(divElement);});

It boils down to being able to manipulate the dom at will and test Ajax very easily. Enjoy it, I do.

UPDATE:
more powerfull load
load scripts

adds the function shakeDivs(); - try it

søndag den 23. december 2007

High automatic test coverage of web applications

Tests in web applications


Features in a web application reside in one of two locations: On the client or on the server.

A unit test of the feature in the serverside codebase can cover numerous errors. If the application is written in PHP, Python or any other language compiled at runtime, the unit test can cover compiler errors. It can also cover logical errors and the error of not meeting the requirements.

A functional test on the client side can also cover the integration test with browsers if the test framework can execute the tests in multiple browsers, otherwise the lowest denominator might be adequate (think IE 6).

frameworks to use


Almost every decent language has a unit testing framework which provide a standard way of defining, executing and reporting tests. Some, like Django's, also handles the fixtures, like creating and deleting a database for each test run. This is very helpful.

For functional tests in the browser engine, there are numerous frameworks. Some record a macro and repeats it, these tools are to be avoided, since they make maintenance of the tests very cumbersome, which may lead to neglect in the project. Instead of dicussing pro's and con's of various frameworks, like loadrunner, selenium etc. I'm simply going for Canoo's webtest, which aggregates HtmlUnit and several other thirdparty frameworks into one very good framework.

It has the advantage that it is defined in XML, which ought to be readable by most with at least some technical interest. Think testers, new developers and maybe even project managers. It also has a very good reporting tool that is generated in static html files. I'll give an example of a webtest further down.

implementing and maintaining the tests


When developing testdriven, it is a given that at least unit tests are being made. In most IDE's for java developers JUnit tests are we easily made and runnable (though sometimes it can be tricky to setup a full test suite running all tests). In Django you simply write a tests.py module at the root of your application*1. The management tool in Django can then invoke all tests py simple running 'manage.py tests' at the root of the project. In java you have to marshal all the tests in an ANT script or reference all test classes from 1 testsuite, leading to tedious work that puts the tests in jeopardy of being neglected.

A canoo webtest is run by an ANT script. 1 script, which I always use is simply called 'allTests.xml'. Separating tests should not be the norm as with JUnit instead you should have to put some effort into excluding certain tests. The exclusions might be performance tests or some other test that is not a candidate for regression testing.

In webtest you may define several macros and reuse them when you like and it has all the functionality of ANT. In the next section I give an example of a test implementation.

testing upload and file conversion


This feature of my project involves multiple units on the serverside and only 1 clientside. Because most of the features serverside are using almost exclusively the Django framework there is no need to cover it, so I can rely on one simple unit test to test this for me, it takes a file and converts it, which is the only part I have implemented myself:

def test_convert_video(self):
entity = Entity(name="test video")
entity.save()
physical = Physical(content_object=entity)

convert_to_flv(self.avifilename, self.flvfilename, physical)
result = os.path.exists(self.flvfilename)
self.assertTrue(result)
self.assertEqual(self.flvfilename, physical.converted_filename)
os.remove(self.flvfilename)

There are several more features surrounding this one, like test_grab_thumbnail_from_flv, test_invalid_cleanup_convert_video, test_get_default_thumbnail_filename and many more. This part has to have high coverage because it is a core function of the web application, but I will not go into priority vs. coverage in this entry.

The unit under test in the example is the convert_to_flv. When the test executes a fake database is set up and some test doubles are made. The files used in the test are cleaned up afterwards to ensure that the state of the system is not changed as a result of the test.

On the client side I have this webtest:

<target name="test">
<webtest name="add different kinds of content">
<login username="user" password="pass"/>
<addContent name="picture 1" file="../../JOOLLU_webtest/tests/picture1.png"/>
<addContent name="picture 2" file="../../JOOLLU_webtest/tests/babe.jpg"/>
<addContent name="movie 1" file="../../JOOLLU_webtest/tests/plane_lands.avi"/>
<addContent name="movie 2" file="../../JOOLLU_webtest/tests/preview.mov"/>
<addContent name="" file="../../JOOLLU_webtest/tests/preview.mov"/>
<addContent name="plain flv" file="../../JOOLLU_webtest/tests/3.flv"/>
</webtest>

It covers the feature of uploading files. Other tests rely on this being executed which leads to test dependencies, which is totally fine. If it was a requirement not to have test dependencies I would have tests that were hard to maintain since all tests relying on this one would have to upload content themselves, putting the test at risk of being neglected.

Inspect the test. The tag 'addContent' is one macro I have defined as a part of my test project, and it looks like this:

<macrodef name="addContent" description="add some content to the current user profile">
<attribute name="name"/>
<attribute name="file"/>

<sequential>
<clickLink label="add content"/>
<setInputField name="name" value="@{name}"/>
<setFileField name="file" fileName="@{file}"/>
<clickButton htmlId="add_button"/>
</sequential>
</macrodef>

The power of this is that I can encapsulate code that is part of implementing the tests separately and thus make the actual test easier to read and maintain. A tester with no programming background would be able to read the test and change the name of the file and the file itself.
Among other tests that rely on this I have contentValidation.xml, invalidContentValidation.xml, verifyCorrectContent.xml and many others. The nice thing is that each subsequent test can be a direct verification of the feature or requirement. This way I can ensure that no test effort is lost because the implementation on the server has changed.

closing remarks


Testing this way allows for full coverage of a web application. The webtest framework can handle almost all browser functionality even Ajax, ehich is due to the HtmlUit project. It has a couple of bugs, it can for example only drag and drop 1 item for each test. But these are minor issues. If my application did not contain flash as part of the implementation I reckon I could achieve 100% coverage in automatic tests. As it is now I don't have much test of requirements for performance, but I think I'm at 80% coverage in total with unit tests and webtest.

To get the high automatic coverage you need to figure out on which side you have to test your feature, client or server. Then implement the unit tests for serverside and clientside tests in a framework like webtest.. and then you can implement the feature itself, knowing that when the bar in the reporting tool reaches green.. you are finished.

links

canoo webtest

Django testing

footnotes
*1 in Django there are multiple applications per project. An application in Django is the equivalent of a plugin in Eclipse RCP or a Web Application Resource in J2EE.

tirsdag den 4. december 2007

Development with Django and NADB

Python has always intrigued me. Occasionally I have kept revisiting the language to be marbled at the simplicity and ease of use. Until recently I did not have a reason to go further with it.

I started implementing the project Joollu(coming soon joollu).

I decided to use the Django framework. Because a) its done in python and b) I heard it was good for content-driven websites.

And boy it's intuitive, being a novice Python-programmer I felt it astonishing that I could implement my own video blog in less than approx. 10 hours. The documentation is equally astounding.

The Django framework has an object relational-mapper, that handles all your db-management for you, it's a very simple way of making a model layer. You only need to configure the things that are specfic for you, making it very rapid for simple features. I thought it might be a bigger task to implement the NADB, which is only based on interfaces, but then I discovered this notion of Generics implemented in Django.

Generics is used to associate a model object with any other object, without knowing anything about it's implementation. This is exactly what the NADB is all about. Instead of having a Video model class, I implemented a Physical(for storing files), viewable(for attributes like thumbnail, width/height etc.) and firstly an Entity class to represent the actual video, the only attribute here is name and id. None of these models know anything about the other on the DB-layer, instead I have a MediaManager, that can marshal a video from all its referred interfaces. Retrieving a video can be done like so:


>>> from joollu.core.models import *
>>> entity = Entity.objects.get(name="myvideo")
>>> physical = Physical.objects.get(content_object=e)
>>> viewable = Viewable.objects.get(content_object=e)



or more simply with a little wrapping



>>> from joollu.core.managers import MediaManager
>>> entity = Entity.objects.get(name="myvideo")
>>> video = MediaManager().filter_video(name="myvideo")


OR


>>> from joollu.core.managers import MediaManager
>>> entity = Entity.objects.get(name="myvideo")
>>> video = MediaManager().get_media(entity.id)


sadly it kinda impairs the possibilities of filtering and retrieving which is done very easily with Django. Here is an example for physical, if I want particular files:


>>> from joollu.core.models import *
>>> physical_list = Physical.objects.filter(file__endswith=".png")
>>> physical_list
[Physical: /Users/kennethnielsen/pythonspace/joollu/media/content/picture1.png]


Keeping the notions of things like video and images in the business layer increases flexibility. If I were to change attributes I can slap it on one of the exisitng interfaces or make a new one. Like if I want to save who and when something has been published, I can make a new model class Publishable and attach it to all content. This would be regardless of it being a video, image or other. It is up to the business layer to decide if published attributes are needed in specific cases. Comments is another example and so it goes..

There are a ton of other stuff worth mentioning about Django, it all just kinda fits together in this very intuitive framework. You should read up on it, or find the tech talk about it on google tech talks.

Outsourcing

With all the J2EE projects being outsourced to India, I guess this zeitgeist graph makes sense:

Google searches for 'What is j2ee'

Look at the regions...

onsdag den 31. oktober 2007

No Artifacts DataBase (NADB)

prologue


Fueled by the Tech Talk 'Everything is miscellanous' and the book about abstract datamodelling I read lately I think it's time I give it some action...

Databases today inherently have trouble adapting to changes in the business, nowadays business logic changes rapidly because of the increasing demand of adaptive business and use of IT in general.

Our databases are not up to speed though. Designing a database often takes too much time and is too great a risk to mess up, so you start of by designing this, and then basing your software on it.

With rapid development, it ought to be the other way around. The business dictates what needs to be in the database and often business changes. Databases should be as adaptable.

Avoid artifacts in the database



Data are not static! The database of a typical company contains a product, order and orderline.

Looking at the product table, what constitutes a Product? That you say it's a product? - no, it has a price and can be bought and therefore is a product.

If you are a paint store your product table could contain the columns: color, viscousity, manufacturer, price. If the paint store at some point wishes to extend it's catalogue to, perhaps, lamps, the table would be extended and we would have a table with the columns: color, viscousity, manufacturer, bulbtype and price.

This would leave some of the rows as null values, since a lamp doesn't have viscousity(Okay bad example.. you get the idea). Maybe you would fill out viscousity anyway or do something awful like using the column for something else.

In a big company I worked for I actually saw a table called 'Ship' which also contained 'Automobiles', because when automobiles became accepted as a business object some time in the past, the table happened to involve some of the same systems and had a property like 'Motor registration number'. Ofcourse, some columns in the table were along the way misused for something completely different then intended.
Actually it wasn't really clear anymore what entites were saved there, but I think also 'Caravans' were in there.

Taking the example of mixing 'Paint' and 'Lamps', lets look at their individual properties:

    • Paint

      viscousity

      color



    • Lamp

      bulbtype



    • Product

      price


  • Notice that I dont go all out here and create a 'Fluid' table for viscousity and a 'Coloured' table for the color. Also I have left out the property manufacturer, because it becomes a table 'Manufactured'. A product could be a service, which is not manufactured.

    So you're probably asking, what handles the relations between all these properties. Well, the product should not relate to either 'Paint' or 'Lamp' since it should not define what a product is. Instead the business handles this by instantiating entities in the database with an abstract table 'Instance'. The abstract modelling I have come up with is shown below. The relations are read as "Instance implements Type" and "Type describes Instance". It is like the modelling we know from Object-oriented languages, with the key difference that it only describes states, because we are dealing with a persistence mechanism, that should only handle state. Behaviour is described by the business(READ application on top of DB).


    You might be thinking, what about metadata like logging of change of state and other valuble business info. These are very relevant issues and such a log of something should be an instance in its own right. It would have properties like date and user. Where user is a property that is a reference to an instance. So the property user would have a domain allowing it to be an instance, and the value would be a reference to an actual instance of a user. This is the way to do metadata in the model. If you would to refer to a user by a UserId you lock the table in to being a User logged event, by allowing it to be a reference to an arbitrary instance you can define it to be a User logged event in your business by checking the type of the referred instance.

    Note that this is not a classical Inheritance hierarchy where types can 'be of' other types, the 'Type' here is equal to an interface(as implemented in Java atleast). The creators of Java have since regretted the class inheritance as we know it today, because of the classical problem of the fragile superclass. The superclass is fragile because it's children are inherently(pun intended) dependant on the implementation of the superclass. When several children exists, the purpose of the superclass becomes more obscured as the business continues to grow and different requirements are put on the children, as the case with a table expanding horizontally. Instead, the children should implement different interfaces, dividing up the different requirements into several descriptors. The implementation of the interfaces can then be delegated. The big difference here is that state is not inherited.

    In the case of paint being sold, it would be an instance of paint AND price, collectively becoming what the business would describe as paint we are selling.

    The 'Instance' does not contain any properties itself because the 'Instance' is the sum of its relations.

    Conclusion


    The relational databases today are too statically implemented, by abstracting the data, we can much more easliy build a clean database, without ripping out tables. To change the properties of an instance you only need to relate it to a different property and not do heavy, frightening, undoable 'Alter tables' etc.

    The model ofcourse requires some robust business logic on top, but from the recent working with Hibernate and Linq it's apparent that the traditional business logic never really worked. Contraints and validation of data has moved more towards UI and the business layer has become some dumb DAO, hopefully this approach will revitalize the layer and bring more flexibility into our backend.

    From here I have to prove my theory by actually implementing a system for it and describe how intuitive and flexible my backend became :)

    Stating that something is within a particular domain by putting the instance in a table with a certain name, does not make it so. It is as absurd as arguing whether Pluto is a moon or a planet, because it doesn't fit into either. Pluto is just an instance with a different set of properties.. "Everything is miscellanous".

    onsdag den 17. oktober 2007

    BEA Weblogic tips

    J2EE shared libraries are very useful, because they are merged with your web application you can reuse web resources like JSP's, special framework stuff like BEA controller's and so on.

    Here's how you might do it:

    creating a shared J2EE library


    a library can be any J2EE module. Mind you I've mostly used Portal Web projects as the base for my libraries as I found that I often have web resources in my libraries

    defining a shared J2EE library


    1. go to the META-INF folder
    2. open the MANIFEST.MF file
    3. add the following three lines, filling in (example given further down):
    4. Extension-Name:
    5. Specification-Version:
    6. Implementation-Version:

    Manifest-Version: 1.0
    Extension-Name: common-portlet-template-web
    Specification-Version: 0.1
    Implementation-Version: 0.1

    NOTE: the version MUST be given in order to import the library into BEA Workshop 10.0

    exporting a shared J2EE library from a Web project


    1. update the versions as commented in 'defining a shared J2EE library'
    2. right-click the project, choose 'export->WAR file'

    exporting a shared J2EE library from a J2EE Utility project


    1. update the versions as commented in 'defining a shared J2EE library'
    2. right-click the project, choose 'export->Export', select JAR file, click 'Next'
    3. choose your source folders and the META-INF folder for export, click finish

    importing a shared J2EE library into the BEA Workshop 10.0


    1. in window->preferences->weblogic->J2EE libraries click 'add'
    2. click 'browse', locate your exported WAR or JAR or EAR
    3. click 'open', click 'ok'
    4. adding it to your project is done by expanding the 'WebLogic Deployment Descriptor' in your project
    5. right-click -> add, 'browse', locate it and click 'ok'

    redeploying a shared J2EE library from the Workshop


    1. in window->preferences->weblogic->J2EE libraries select the library and click 'remove'
    2. open the server overview by double-clicking the server in the 'Servers' view
    3. in the published module list, select the ear project and click 'Undeploy'
    4. after the ear has finished undeploying, click the shared Library module, and click 'Undeploy'
    5. now your are ready to deploy the library again, do this by going to window->preferences->weblogic->J2EE libraries
    6. click 'add', then 'browse' and navigate to your shared library, select the library, click 'ok'
    7. redploy the library by running you project on the server.

    torsdag den 11. oktober 2007

    Slow development cycles? Try something old-school.

    Does this scenario sound familliar?

    "Quality Assurance just discovered a logical error in your presentation of the customers product.. instead of the 'Two-month no credit limit' - product, the 'Three-month no credit limit' - product emerges,
    Thinking you have the answer, you are remembering the pesky ProductNameProvider you wrote, and you guess it's a one-off error here. You seem to remember that the first two OR three records in its output are just static titels. You can't remember if it was the first two OR three, so you try incrementing your reference-index by 1. You then restart the server, deploy the application and wait patiently for a result...

    After replicating the error in 42 easy steps, you conclude this wasn't the right fix, now it's showing a completely wrong 'One-month no credit limit' - product.

    You suddenly realize that this could be an error in the actual product request or maybe the text formatting or maybe it's the caching?
    - so you try every possible path for the error and try out 3-4 different scenarios for 3-4 different paths only repeating the 42 easy steps... again... and again..."

    Such slow processes of bugfixing are caused by ONE thing.. lack of unit tests and proper structure. This cycle of fixing said bug, should have an obvious solution. A unit test somewhere should test that the output of a ProductNameProvider is fixed. Having an automatic testframework and supporting stubbing(maybe mocking), would allow you to test this functionality exclusively and not the entire application at once, which is too complex for any human to handle... well some applications are, especially if you like me only handle applications for shorter periods(READ 3-6 months).

    I have just begun working on an assignment at a large danish company. Their applications are mainly J2EE with some heavy junk in the trunk.
    My task there involves developing portlets in WebLogic 10. This is a nice platform for portals because of their intuitive CMS and flexibility in layout. BUT since its a J2EE platform, it's inherently slow, because of lots of configuration and stuff under the hood that does lots of... well.. stuff.

    To test an application developers tend to restart the server, because we are neurotically inclined to think that an incorrect state of the configuration involved is the main cause of our bugs, and it's understandable. Although 99% of the time, we just fucked up, we do however restart the server about 5 times before admitting it..

    NONE of my tasks will ever involve extending the CMS or directly interfacing with the CMS in ANY manner, so why would I need to EVER start this up when doing a simple two-page portlet.. or a complex seventy-page one for that matter.. case is.. I don't and I certainly won't. So, my advice is to avoid that the running of your code requires a running server. A common mistake is to run code, right there in your main methods.. for an example in a struts action, a beehive controller or whatever. Delegate, delegate, delegate all responsibility to classes with limited responsibility.. atleast 1 class, that doesn't require you to load a shitload of code or annotated compiles.

    Even a simple ProductNameProvider will eventually be executed atleast 10 times in its development stage and atleast 10 times (maybe hundreds) in its lifetime for debugging purposes.. so lets do the math.

    total runs = 20
    Writing the ProductNameProvider in a unit test friendly environment = 15 min
    Restarting a shitload of applications on a J2EE server + replicating bug = 2 min (atleast)
    running a single unit test = 1 sec (atmost)

    60 x 15 (unittest creation) + 20 x 1 (unittest running) = 920 seconds
    60 x 2 x 20 = 2400 seconds

    I am not counting in maintenance of unit tests, this is parrallel to development and should not acquire extra time.. unless you implement a completely new feature..

    I'm not even getting in on how unit testing reduces bugs, facilitates refactoring, reduces the footprint of your code etc etc.. there are tons of documented experienced of that out there.. read it.. read it all... now!

    Running/testing your code, should be as easy as ALT + SHIFT + x, t