The Gemara in Tractate Shabbos speaks about David's deed with Batsheva. David originally wanted to be one of the Forefathers and asked to be recognized as one. Just as the Forefathers were tested, so too David would have to be tested to be counted in their number, and G-d even told him he would be tested in the area of illicit relationships. We know the purpose of Adam was to bring the tikun to the world. Instead of fixing the world, he brought impurity into the world. Now, the impurity must be removed so the world can be prepared for the World to Come. These two actions need to be taken by the two Mashichim, one through Yosef and the other through David. Mashiach Ben Yosef will eradicate the impurity from creation and Mashiach Ben David will sanctify this world for the World to Come.