Blackout for SOPA and PIPA.
Click to learn more
Posterous theme by Cory Watilo

Filed under: tutorial

Xml Serialization with java - SimpleXml

Media_https3amazonaws_bbpdi
For those of you out there who have problem implementing some complex xmls i have a good example for you: Xml : [cc lang="xml" lines="auto"]
Teszt1
Teszt2
Teszt2
Teszt3
[/cc] And this is your Class Hierarchy representing it: [cc lang="java" lines="auto" escaped="true"] @Root public class UIElement { @ElementList(name="Elements") public List divContainers; } @Root public class DivContainer { @ElementList(name="DivContainer", inline=true) public List divs; @Attribute public String name; } @Root(name="Div") public class Div { @Element(name="test") public String test; @Attribute(name="name", required=false) public String name; } [/cc] And the serialize code: [cc lang="java" lines="auto" escaped="true"] public void testXml() { Serializer serializer = new Persister(); File source = new File("c:\\tmp\\test.xml"); UIElement ui = null; try { ui = serializer.read(UIElement.class, source); } catch (Exception e) { e.printStackTrace(); } for (DivContainer divc : ui.divContainers) { for (Div div : divc.divs) { System.out.println("Value of test: " + div.test); } } } [/cc] You have to look out for two things... First note the @Root under Div tag. That is necessary there. Writing in the attribute name there is necessary too. Also the 'inline' tag. Without them it wont work. Gergely.

Show Your GIT Branch Name In Your Prompt

Media_https3amazonaws_hvyjm

Show Your GIT Branch Name In Your Prompt

Typing git branch over and over to see what branch you are on sucks. Sure, you could argue that you should always KNOW what branch you’re currently working on. And if you did, you would obviously not be a git user. Bouncing around branches can be pretty common, and I know I’ve messed some things up pretty bad not knowing what branch I was on. So set up your shell to always put the name of the current branch into your prompt. [cc lang="bash" escaped="yes" lines="27"] function parse_git_branch { git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/' } function proml { local BLUE="\[\033[0;34m\]" local RED="\[\033[0;31m\]" local LIGHT_RED="\[\033[1;31m\]" local GREEN="\[\033[0;32m\]" local LIGHT_GREEN="\[\033[1;32m\]" local WHITE="\[\033[1;37m\]" local LIGHT_GRAY="\[\033[0;37m\]" case $TERM in xterm*) TITLEBAR=&'\[\033]0;\u@\h:\w\007\]&' ;; *) TITLEBAR="" ;; esac PS1="${TITLEBAR}\ $BLUE[$RED\$(date +%H:%M)$BLUE]\ $BLUE[$RED\u@\h:\w$GREEN\$(parse_git_branch)$BLUE]\ $GREEN\$ " PS2=&'> &' PS4=&'+ &' } proml [/cc] Pastie Link Put this at the top of your .bash_profile and you’ll be pimping your branch all over. Thanks to @defunkt for this. via Show Your GIT Branch Name In Your Prompt.
I thank @fqqkd for this, He pointed me to the post. Though I didn't like the colors, so I've made blue [cc lang="bash" inline="yes"]BLUE="\[\033[0;36m\]"[/cc] and the propt: [cc lang="bash" escpaed="yes"] PS1="${TITLEBAR}\ $BLUE[$RED\$(date +%H:%M)$BLUE]\ $BLUE[$BLUE\u@\h:\w$GREEN\$(parse_git_branch)$BLUE]\ $BLUE\$ " [/cc]

Swiss army knife for XP PHP projects (defining code quality)

Media_https3amazonaws_lbybu
The title is a bit wishful thinking, but you'll see why. The guides below could be used for any PHP project out there, but it will represent different things for different quality code.
This tutorial doesn't handle UI testing. You probably have a lot of code sitting on your hard drive and hopefully you already use some sort of source control system. The trouble is, that whenever you have to fix a bug, you can only be sure, that the specified bug is gone, but you're unaware of what might have broken. This tutorial assumes you know what OOP is and you use it more-or-less for your projects. In an ideal world you develop a web application, users use it and everybody is 'appy. But we (at least I) don't live in an ideal world, money doesn't come with spam. (wish it would). Did you ever get into a situation of working way more for the same amount of money, because bugfixing took twice as much time as creating the software? I did. The 2day coding resulted 2 weeks of bugfixing. Why? - you may ask. Every single bug I've fixed, introduced a new one somewhere else. That was the point that led me to the world of eXtreme programming.

Read the rest of this post »

Validators - 2 - Age validation

Continuing the post Validators - the beginning
Media_https3amazonaws_thjgo
This post is about age validation. The implementation below let's you easily define a date that will be used as a reference date. Values same or older tan this date will produce the validation to pass, other will not. [cc lines="-1" lang="php" escaped="true"] This implementation assumes that the default validation only * validates for dates 13 years or older. * * @param string $reference The date to refer to. */ public function __construct($reference="-13 years") { $this->_referenceAge = strtotime($reference); } /** * Validates that the given date is earlier or equal than the * reference age * * @param string $date An strtotime capable string * * @return bool true if valid, false otherwise */ public function validate($date) { $val = strtotime($date); return $val_referenceAge; } } ?> [/cc]

unit test

[cc lines="-1" lang="php" escaped="true" theme="blackboard" width="510"] object = new AgeValidator(); } else { $this->object = new AgeValidator($refDate); } $actual = $this->object->validate($value); $this->assertEquals($expected, $actual); } } ?> [/cc]

Validators - the beginning

I'm implementing validation to the site right now, and writing some useful little codes. I'll share them one by one with unittests.
Media_https3amazonaws_ofvba
[cc lines="-1" lang="php" escaped="true"] [/cc]

Valid String

Let's say you want to validate a field containing only alphanumeric characters ( a-z, A-Z, 0-9, - and _) Then you'll have a validator like: [cc lines="-1" lang="php" escaped="true"] 0; } } ?> [/cc]

unit test

[cc lines="-1" lang="php" escaped="true" theme="blackboard" width="510"] object = new StringValidator(); } public function stringProvider() { return array( array('a' , true), array('Z' , true), array('0' , true), array('9' , true), array('-' , true), array('_' , true), array('aZ09-_', true), array('á' , false), array('aZ09*_', false), array('userÉ' , false), ); } /** * The test needs to prove that the the validate method * gives the $expected value to the $string. * * @dataProvider stringProvider() */ public function testValidate($string, $expected) { $actual = $this->object->validate($string); $this->assertEquals($expected, $actual); } } ?> [/cc]

Unique username

If you'd like to check that the given username is unique, then you'll have: [cc lines="-1" lang="php" escaped="true"] _db=$db; } /** * Validates that the username is unique in the database * * @param string $value Username * * @return bool true if valid, false otherwise */ public function validate($value) { $sql = 'SELECT count(*) FROM users WHERE username = '.$this->_db->escape($value); $result = $this->_db->query($sql); //if the affected rows was 0, than return true. return ($result->affected_rows == 0) ? true : false; } } ?> [/cc]

unit test

[cc lines="-1" lang="php" escaped="true" theme="blackboard" width="510"] dbMock = $this->getMock('DatabaseConnection',array( 'query', 'escape' ),array(),'',false); $this->object = new UniqueNameValidator($this->dbMock); } public function setUpDbExpection($userName, $returnValue=true) { $sql = 'SELECT count(*) FROM users WHERE username = '.$userName; $this->dbMock->expects($this->at(0)) ->method('escape') ->with($this->equalTo($userName)) ->will($this->returnValue($userName)); $this->dbMock->expects($this->at(1)) ->method('query') ->with($this->equalTo($sql)) ->will( $this->returnValue( (object) array('affected_rows'=>$returnValue) ) ); } public function provider() { return array( array('notexistintgUser', (int)0), array('existingUser' , (int)1) ); } /** * Wee need the test to prove that the validate method * gives false if the username is present in the db, and * true otherwise. The Database mock will return 1 if the user exists * and 0 if not. * * @dataProvider provider() */ public function testValidateForInvalid($username, $returnValue) { $this->setUpDbExpection($username, $returnValue); $actual = $this->object->validate($username); $expected = !(bool)$returnValue; $this->assertEquals($expected, $actual); } } ?> [/cc]
More are coming. If you have an idea of some commonly used validation process, please leave a comment and we'll do it :) hope this example helps out some struggling with massive, legacy validation logic. Later on the tutorial series will show you how to chain these validators. Until then, happy coding :)

Refactoring #1

I was introduced to a code the other day, that had a bug. It was pretty easy to reproduce, and I could easily create a Selenium test case for the problem. I was told, that the code is a mess and I'm free to do whatever I want. When you're doing refactoring, you should always know what exactly you are doing. In this case the goal was to eliminate the bug causing the security issues. The ~500LOC method had an enormous cyclometric complexity, and more static calls than I've ever written. At least it was in some sort of a class, but not a single comment were there to guide me through the tough logic that merges security settings from various extensions (modules) and calculates the dependencies and verifies values and draws forms and ... hard-to-test code heaven... So what to do when you see a [cc lines="-1" lang="php" escaped="true"] class DemoClass { public function someMethod() { $val1 = SomeClass1::staticMethod1(); $val2 = SomeClass2::staticMethod2(); } public function process() { if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fieldValue'])) { return $this->_doSomethingWith($_POST['fieldValue']); } return null; } private function _doSomethingWith($field) { return strrev( (string) $field); } }[/cc] With a client code: [cc lines="-1" lang="php" escaped="true" theme="blackboard"] $demo = new DemoClass(); $demo->someMethod(); print $demo->process(); [/cc] If refactoring the statics is not yet an option, use wrappers! [cc lines="-1" lang="php" escaped="true"] class SomeClass1Wrapper { public function staticMethod1() { return SomeClass1::staticMethod1(); } } class SomeClass2Wrapper { public function staticMethod2() { return SomeClass2::staticMethod2(); } } [/cc] Then you can easily add the dependencies for your method [cc lines="-1" lang="php" escaped="true"] class DemoClass { public function someMethod( SomeClass1Wrapper $someClass1, SomeClass2Wrapper $someClass2 ) { $val1 = $someClass1->staticMethod1(); $val2 = $someClass2->staticMethod2(); } public function process() { if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fieldValue'])) { return $this->_doSomethingWith($_POST['fieldValue']); } return null; } private function _doSomethingWith($field) { return strrev( (string) $field); } } [/cc] And there you go. You have the statics in control. The client code needs to be modified: [cc lines="-1" lang="php" escaped="true" theme="blackboard"] $demo = new DemoClass(); $someClass1 = new SomeClass1Wrapper(); $someClass2 = new SomeClass2Wrapper(); $demo->someMethod($someClass1, $someClass2); print $demo->process(); [/cc] The other thing I've bumped into is using [cci_php]$_POST[/cci_php] and [cci_php]$_SERVER[/cci_php] in the methods. Doing this you won't have such a hard time testing, but you'll hopefully won't want to set variables in these arrays by hand to reproduce some scenarios.

What's wrong with globals?

Accessing global state statically doesn’t clarify those shared dependencies to readers of the constructors and methods that use the Global State. Global State and Singletons make APIs lie about their true dependencies. To really understand the dependencies, developers must read every line of code. It causes Spooky Action at a Distance: when running test suites, global state mutated in one test can cause a subsequent or parallel test to fail unexpectedly. Misko Hevery: Flaw: Brittle Global State & Singletons
So what can you do? Give them to your method. Or if they're used widely in your code, pass them in the constructor. (you do have one do you?) When I realized I need all dependencies throughout the whole class, I've moved them up one level. [cc lines="-1" lang="php" escaped="true"] class DemoClass { /** * @var SomeClass1Wrapper */ private $_someClass1; /** * @var SomeClass2Wrapper */ private $_someClass2; /** * @var array */ private $_serverVars=array(); /** * @var array */ private $_postVars=array(); public function __construct( SomeClass1Wrapper $someClass1, SomeClass2Wrapper $someClass2, array $serverVars=array(), array $postVars=array() ) { $this->_someClass1 = $someClass1; $this->_someClass2 = $someClass2; $this->_serverVars = $serverVars; $this->_postVars = $postVars; } public function someMethod() { $val1 = $this->_someClass1->staticMethod1(); $val2 = $this->_someClass2->staticMethod2(); } public function process() { if ($this->_serverVars['REQUEST_METHOD'] === 'POST' && isset($this->_postVars['fieldValue'])) { return $this->_doSomethingWith($this->_postVars['fieldValue']); } return null; } private function _doSomethingWith($field) { return strrev( (string) $field); } } [/cc] Then the client code wil be: [cc lines="-1" lang="php" escaped="true" theme="blackboard"] $someClass1 = new SomeClass1Wrapper(); $someClass2 = new SomeClass2Wrapper(); $demo = new DemoClass($someClass1, $someClass2,$_SERVER,$_POST); $demo->someMethod(); print $demo->process(); [/cc] The other thing you should look for in a code is the usage of the variables. For example, when I've searched for "where do I use the $this->_serverVars", I've found the following: [cc lines="-1" lang="php" escaped="true"] public function process() { if ($this->_serverVars['REQUEST_METHOD'] === 'POST' && isset($this->_postVars['fieldValue'])) { return $this->doSomethingWith($this->_postVars['fieldValue']); } ... //some lines of other stuff if ($this->_serverVars['REQUEST_METHOD'] === 'POST') { $this->doSomethingElse(); } ... //some lines of other stuff if ($this->_serverVars['REQUEST_METHOD'] === 'POST') { $this->doSomethingNaughty(true); } return null; } [/cc] You should note, that the code is only using the 'REQUEST_METHOD' element, nothing else.

Tell, Don't Ask

The "Tell, Don't Ask" principle suggests that you should tell objects what to do rather than ask for their state (i.e., their data), make a decision, and then tell them what to do. The guiding idea behind this is that an object should avoid exposing it's internal state to another object. Consider a quote from The Art of Enbugging which discusses the story of "The Paperboy and the Wallet".
Suppose the paperboy comes to your door, demanding payment for the week. You turn around, and the paperboy pulls your wallet out of your back pocket, takes the two bucks, and puts the wallet back. Instead of asking for the wallet, the paperboy should tell the customer to pay the $2.00.
from & more @ http://learn.objectorientedcoldfusion.org/wiki/Tell_Dont_Ask
So I've modified my code: [cc lines="-1" lang="php" escaped="true"] class DemoClass { /** * @var SomeClass1Wrapper */ private $_someClass1; /** * @var SomeClass2Wrapper */ private $_someClass2; /** * @var string */ private $_requestMethod='GET'; /** * @var array */ private $_postVars=array(); public function __construct( SomeClass1Wrapper $someClass1, SomeClass2Wrapper $someClass2, $requestMethod='GET', //assuming array $postVars=array() ) { $this->_someClass1 = $someClass1; $this->_someClass2 = $someClass2; $this->_requestMethod = $requestMethod; $this->_postVars = $postVars; } public function someMethod() { $val1 = $this->_someClass1->staticMethod1(); $val2 = $this->_someClass2->staticMethod2(); } public function process() { if ($this->_requestMethod === 'POST' && isset($this->_postVars['fieldValue'])) { return $this->_doSomethingWith($this->_postVars['fieldValue']); } return null; } private function _doSomethingWith($field) { return strrev( (string) $field); } } [/cc] Then the client code wil be: [cc lines="-1" lang="php" escaped="true" theme="blackboard"] $someClass1 = new SomeClass1Wrapper(); $someClass2 = new SomeClass2Wrapper(); $demo = new DemoClass($someClass1, $someClass2,$_SERVER['REQUEST_METHOD'],$_POST); $demo->someMethod(); print $demo->process(); [/cc] And there you have a nice, testable, mockable code. Here's the test file: [cc lines="-1" lang="php" escaped="true"] require_once 'PHPUnit/Framework.php'; require_once dirname(__FILE__).'/DemoClass.php'; class DemoClassTest extends PHPUnit_Framework_TestCase { /** * @var DemoClass */ protected $object; /** * @var someClass1Wrapper */ protected $someClass1Mock; /** * @var someClass2Wrapper */ protected $someClass2Mock; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->someClass1Mock = $this->getMock( 'someClass1Wrapper', array('staticMethod1'), array(), '', false); $this->someClass2Mock = $this->getMock( 'someClass2Wrapper', array('staticMethod2'), array(), '', false); } /** * Test that the static methods are called */ public function testSomeMethod() { $this->object = new DemoClass($this->someClass1Mock, $this->someClass2Mock); $this->someClass1Mock->expects($this->at(0)) ->method('staticMethod1'); $this->someClass2Mock->expects($this->at(0)) ->method('staticMethod2'); $this->object->someMethod(); } /** * Test that we get the expected null if the method is GET */ public function testProcessWithGet() { $this->object = new DemoClass($this->someClass1Mock, $this->someClass2Mock); $expected = null; $actual = $this->object->process(); } /** * Test that we get the expected null if there's no 'fieldValue' */ public function testProcessWithPostAndNoInput() { $this->object = new DemoClass($this->someClass1Mock, $this->someClass2Mock,'POST'); $expected = null; $actual = $this->object->process(); } /** * Test that the process returns the reversed 'fieldValue' */ public function testProcessWithPostAndInput() { $input = 'Refactoring is fun'; $postVars = array('fieldValue'=>$input); $this->object = new DemoClass( $this->someClass1Mock, $this->someClass2Mock, 'POST', $postVars); $expected = 'nuf si gnirotcafeR'; $actual = $this->object->process(); $this->assertEquals($expected, $actual); } } [/cc] Of course testing is only easy when your base objects' responsibilities are clear and simple. In my case, I still haven't found the cause of the bug, since the whole code is more complex and still has a lot of work to do. In the next chapter of hunting down the strange error I'll fill you in with my experiences of finding out what and how the original code does, before you can carry on with refactoring.