WebDriver / Selenium - How to set the browser viewport size in any browser

WebDriver / Selenium - How to set the browser viewport size in any browser

import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ViewPortSize {

      public static void main (String args[]) {

            WebDriver driver = new FirefoxDriver();
            driver.manage().window().setPosition(new Point(0,0));
            driver.manage().window().setSize(new Dimension(1280,214));
            driver.get("http://viewportsizes.com/mine/");

            Dimension browserSize = driver.manage().window().getSize();
            Dimension actualViewportSize = getViewportSize(driver);

            driver.manage().window().setSize(new Dimension(2 * browserSize.width - actualViewportSize
                        .getWidth(), 2 * browserSize.height - actualViewportSize.getHeight()));
            driver.get("http://viewportsizes.com/mine/");
            //driver.close();
      }

      protected static Dimension getViewportSize(WebDriver driver) {
            int width = extractViewportWidth(driver);
            int height = extractViewportHeight(driver);
            return new Dimension(width, height);
      }

      protected static int extractViewportWidth(WebDriver driver) {
            JavascriptExecutor js = (JavascriptExecutor) driver;
            int viewportWidth = Integer.parseInt(js.executeScript(JS_GET_VIEWPORT_WIDTH, new Object[0]).toString());
            return viewportWidth;
      }

      protected static int extractViewportHeight(WebDriver driver) {
            JavascriptExecutor js = (JavascriptExecutor) driver;
            int result = Integer.parseInt(js.executeScript(JS_GET_VIEWPORT_HEIGHT, new Object[0]).toString());
            return result;
      }

      private static final String JS_GET_VIEWPORT_WIDTH = "var width = undefined; if (window.innerWidth) {width = window.innerWidth;} else if (document.documentElement && document.documentElement.clientWidth) {width = document.documentElement.clientWidth;} else { var b = document.getElementsByTagName('body')[0]; if (b.clientWidth) {width = b.clientWidth;}};return width;";

      private static final String JS_GET_VIEWPORT_HEIGHT = "var height = undefined;  if (window.innerHeight) {height = window.innerHeight;}  else if (document.documentElement && document.documentElement.clientHeight) {height = document.documentElement.clientHeight;}  else { var b = document.getElementsByTagName('body')[0]; if (b.clientHeight) {height = b.clientHeight;}};return height;";

}