How to use Actions class of org.openqa.selenium.interactions package

Best Selenium code snippet using org.openqa.selenium.interactions.Actions

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package Practice;
2
3import java.awt.AWTException;
4import java.awt.Robot;
5import java.awt.event.KeyEvent;
6import java.util.concurrent.TimeUnit;
7
8import org.openqa.selenium.By;
9import org.openqa.selenium.Keys;
10import org.openqa.selenium.WebDriver;
11import org.openqa.selenium.WebElement;
12import org.openqa.selenium.chrome.ChromeDriver;
13import org.openqa.selenium.interactions.Action;
14
15public class Actions {
16	static {
17		System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
18		// System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
19	}
20
21	public static void main(String[] args) throws InterruptedException, AWTException {
22		// Mouse Hover
23		/*
24		  WebDriver driver=new ChromeDriver(); driver.get("http://www.actitime.com");
25		  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); WebElement
26		  menu = driver.findElement(By.xpath("//a[.='Features']"));
27		  org.openqa.selenium.interactions.Actions action=new
28		  org.openqa.selenium.interactions.Actions(driver);
29		  action.moveToElement(menu).perform();
30		  driver.findElement(By.xpath("(//li/a[.='Simple Time Tracking'])[1]")).click() ;
31		 */
32		// ISTQB Mouse Hover
33		/*
34		  WebDriver driver=new ChromeDriver(); driver.get("https://www.istqb.org/");
35		  driver.manage().window().maximize();
36		  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); WebElement
37		  menu=driver.findElement(By.xpath("(//a)[@class=' dropdown-toggle'][4]"));
38		  org.openqa.selenium.interactions.Actions action=new
39		  org.openqa.selenium.interactions.Actions(driver);
40		  action.moveToElement(menu).perform();
41		  driver.findElement(By.linkText("Why ISTQB® Certification?")).click();
42		  driver.close();
43		 */
44
45		// Composite Action
46		/*
47		  WebDriver driver=new ChromeDriver(); driver.get("http://demo.actitime.com");
48		  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
49		  driver.manage().window().maximize(); WebElement menu=
50		  driver.findElement(By.linkText("actiTIME Inc."));
51		  org.openqa.selenium.interactions.Actions action=new
52		  org.openqa.selenium.interactions.Actions(driver);
53		  action.sendKeys(Keys.CONTROL).click(menu).perform(); Thread.sleep(1000);
54		 */
55
56// Context click
57		/*WebDriver driver = new ChromeDriver();
58		driver.get("http://demo.actitime.com");
59		driver.manage().window().maximize();
60		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
61		WebElement link = driver.findElement(By.linkText("actiTIME Inc."));
62		org.openqa.selenium.interactions.Actions action = new org.openqa.selenium.interactions.Actions(driver);
63		action.contextClick(link).perform();
64		Robot r = new Robot();
65		r.keyPress(KeyEvent.VK_T);
66		 */
67
68
69		//		Drag and Drop
70
71		/*WebDriver driver=new ChromeDriver();
72		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
73		driver.get("http://www.dhtmlgoodies.com/submitted-scripts/i-google-like-drag-drop/index.html");
74		WebElement src=	driver.findElement(By.xpath("//h1[.='Block 2']"));
75		WebElement dest=	driver.findElement(By.xpath("//h1[.='Block 1']"));
76		org.openqa.selenium.interactions.Actions action=new org.openqa.selenium.interactions.Actions(driver);
77		action.dragAndDrop(src, dest).perform();
78*/	
79//Handling Frames
80	/*	WebDriver driver=new ChromeDriver();
81		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
82		driver.get("https://jqueryui.com/droppable/");
83		driver.switchTo().frame(0); 
84		WebElement src=	driver.findElement(By.id("draggable"));
85		WebElement dest=driver.findElement(By.id("droppable"));
86		org.openqa.selenium.interactions.Actions action=new org.openqa.selenium.interactions.Actions(driver);
87		action.dragAndDrop(src, dest).perform();*/
88		
89//Handling frames	
90	/*	WebDriver driver=new ChromeDriver();
91		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
92		driver.get("file:///C:/Users/mege/Desktop/page1.html");
93		driver.switchTo().frame(0);
94		driver.findElement(By.id("t2")).sendKeys("abc");
95		driver.switchTo().parentFrame();
96		driver.findElement(By.id("t1")).sendKeys("xyz");
97*/
98
99//DoubleClick		
100	WebDriver driver=new ChromeDriver();
101	driver.get("https://drive.google.com/drive/my-drive");
102	driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
103	driver.findElement(By.id("identifierId")).sendKeys("[email protected]");
104	Robot r=new Robot();
105	r.keyPress(KeyEvent.VK_ENTER);
106	driver.findElement(By.name("password")).sendKeys("[email protected]");
107	r.keyPress(KeyEvent.VK_ENTER);
108	WebElement click = driver.findElement(By.className("l-u-Ab-zb-Pn-ve"));
109	org.openqa.selenium.interactions.Actions action=new org.openqa.selenium.interactions.Actions(driver);
110	action.doubleClick(click).perform();
111	}
112}
113
Full Screen
copy
1package baseline;
2
3import org.openqa.selenium.Keys;
4import org.openqa.selenium.WebDriver;
5import org.openqa.selenium.WebElement;
6import org.openqa.selenium.interactions.Action;
7import org.openqa.selenium.interactions.ButtonReleaseAction;
8import org.openqa.selenium.interactions.ClickAction;
9import org.openqa.selenium.interactions.ClickAndHoldAction;
10import org.openqa.selenium.interactions.ContextClickAction;
11import org.openqa.selenium.interactions.DoubleClickAction;
12import org.openqa.selenium.interactions.HasInputDevices;
13import org.openqa.selenium.interactions.KeyDownAction;
14import org.openqa.selenium.interactions.KeyUpAction;
15import org.openqa.selenium.interactions.Keyboard;
16import org.openqa.selenium.interactions.Mouse;
17import org.openqa.selenium.interactions.MoveMouseAction;
18import org.openqa.selenium.interactions.MoveToOffsetAction;
19import org.openqa.selenium.interactions.SendKeysAction;
20import org.openqa.selenium.internal.Locatable;
21
22public class MyActions {
23
24    protected Mouse mouse;
25    protected Keyboard keyboard;
26    protected MyCompositeAction action;
27	
28	public MyActions(WebDriver driver) {
29        this(((HasInputDevices)driver).getKeyboard(), ((HasInputDevices)driver).getMouse());
30    }
31	
32	public MyActions(Keyboard keyboard, Mouse mouse) {
33        this.mouse = mouse;
34        this.keyboard = keyboard;
35        resetCompositeAction();
36    }
37
38    public MyActions(Keyboard keyboard) {
39        this.keyboard = keyboard;
40        resetCompositeAction();
41    }
42
43    private void resetCompositeAction() {
44        action = new MyCompositeAction();
45    }
46
47    public MyActions keyDown(Keys theKey) {
48        return keyDown(null, theKey);
49    }
50
51    public MyActions keyDown(WebElement element, Keys theKey) {
52        action.addAction(new KeyDownAction(keyboard, mouse, (Locatable)element, theKey));
53        return this;
54    }
55
56    public MyActions keyUp(Keys theKey) {
57        return keyUp(null, theKey);
58    }
59
60    public MyActions keyUp(WebElement element, Keys theKey) {
61        action.addAction(new KeyUpAction(keyboard, mouse, (Locatable)element, theKey));
62        return this;
63    }
64
65    public MyActions sendKeys(CharSequence keysToSend[]) {
66        return sendKeys(null, keysToSend);
67    }
68
69    public MyActions sendKeys(WebElement element, CharSequence keysToSend[]) {
70        action.addAction(new SendKeysAction(keyboard, mouse, (Locatable)element, keysToSend));
71        return this;
72    }
73
74    public MyActions clickAndHold(WebElement onElement) {
75        action.addAction(new ClickAndHoldAction(mouse, (Locatable)onElement));
76        return this;
77    }
78
79    public MyActions clickAndHold() {
80        return clickAndHold(null);
81    }
82
83    public MyActions release(WebElement onElement) {
84        action.addAction(new ButtonReleaseAction(mouse, (Locatable)onElement));
85        return this;
86    }
87
88    public MyActions release() {
89        return release(null);
90    }
91
92    public MyActions click(WebElement onElement) {
93        action.addAction(new ClickAction(mouse, (Locatable)onElement));
94        return this;
95    }
96
97    public MyActions click() {
98        return click(null);
99    }
100
101    public MyActions doubleClick(WebElement onElement) {
102        action.addAction(new DoubleClickAction(mouse, (Locatable)onElement));
103        return this;
104    }
105
106    public MyActions doubleClick() {
107        return doubleClick(null);
108    }
109
110    public MyActions moveToElement(WebElement toElement) {
111        action.addAction(new MoveMouseAction(mouse, (Locatable)toElement));
112        return this;
113    }
114
115    public MyActions moveToElement(WebElement toElement, int xOffset, int yOffset) {
116        action.addAction(new MoveToOffsetAction(mouse, (Locatable)toElement, xOffset, yOffset));
117        return this;
118    }
119
120    public MyActions moveByOffset(int xOffset, int yOffset) {
121        action.addAction(new MoveToOffsetAction(mouse, null, xOffset, yOffset));
122        return this;
123    }
124
125    public MyActions contextClick(WebElement onElement) {
126        action.addAction(new ContextClickAction(mouse, (Locatable)onElement));
127        return this;
128    }
129
130    public MyActions contextClick() {
131        return contextClick(null);
132    }
133
134    public MyActions dragAndDrop(WebElement source, WebElement target) {
135        action.addAction(new ClickAndHoldAction(mouse, (Locatable)source));
136        action.addAction(new MoveMouseAction(mouse, (Locatable)target));
137        action.addAction(new ButtonReleaseAction(mouse, (Locatable)target));
138        return this;
139    }
140
141    public MyActions dragAndDropBy(WebElement source, int xOffset, int yOffset) {
142        action.addAction(new ClickAndHoldAction(mouse, (Locatable)source));
143        action.addAction(new MoveToOffsetAction(mouse, null, xOffset, yOffset));
144        action.addAction(new ButtonReleaseAction(mouse, null));
145        return this;
146    }
147
148    public Action build() {
149        MyCompositeAction toReturn = action;
150        resetCompositeAction();
151        return toReturn;
152    }
153
154    public void perform() {
155        build().perform();
156    }
157
158}
159
Full Screen
copy
1org.apache.commons.lang.Validate //using apache framework
2
Full Screen
copy
1if(someObject!=null){ // simply checking against null
2}
3
Full Screen
copy
1@isNull @Nullable  // using annotation based validation
2
Full Screen
copy
1// by writing static method and calling it across whereever we needed to check the validation
2
3static <T> T isNull(someObject e){  
4   if(e == null){
5      throw new NullPointerException();
6   }
7   return e;
8}
9
Full Screen
copy
1// Bad
2ArrayList<String> lemmings;
3String[] names;
4
5void checkLemmings() {
6    if (lemmings != null) for(lemming: lemmings) {
7        // do something
8    }
9}
10
11
12
13// Good
14ArrayList<String> lemmings = new ArrayList<String>();
15String[] names = {};
16
17void checkLemmings() {
18    for(lemming: lemmings) {
19        // do something
20    }
21}
22
Full Screen
copy
1if(object == null){
2   //you called my method badly!
3
Full Screen
copy
1if(str.length() == 0){
2   //you called my method badly again!
3}
4
Full Screen
copy
1getCustomerAccounts(@NotEmpty String customerId,@Size(min = 1) String accountType)
2
Full Screen
copy
1public class Car {
2
3   @NotNull
4   private String manufacturer;
5
6   @NotNull
7   @Size(min = 2, max = 14)
8   private String licensePlate;
9
10   @Min(2)
11   private int seatCount;
12
13   // ...
14}
15
Full Screen
copy
1Optional stringToUse = Optional.of("optional is there");
2stringToUse.ifPresent(System.out::println);
3
Full Screen
copy
1Optional<Integer> i = Optional.ofNullable(wsObject.getFoo())
2    .map(f -> f.getBar())
3    .map(b -> b.getBaz())
4    .map(b -> b.getInt());
5
Full Screen
copy
1Optional optionalCarNull = Optional.ofNullable(someNull);
2optionalCarNull.orElseThrow(IllegalStateException::new);
3
Full Screen
copy
1String lowerVal = Objects.requireNonNull(someVar, "input cannot be null or empty").toLowerCase();
2
Full Screen
copy
1public Optional<Service> getRefrigertorControl() {
2      Service s = new  RefrigeratorService();
3       //...
4      return Optional.ofNullable(s);
5   }
6
Full Screen
copy
1Optional ref = homeServices.getRefrigertorControl();
2ref.ifPresent(HomeServices::switchItOn);
3
Full Screen
copy
1@FunctionalInterface
2public interface Consumer<T>
3
Full Screen
copy
1public static Optional<HomeServices> get() {
2    service = Optional.of(service.orElse(new HomeServices()));
3    return service;
4}
5
Full Screen
copy
1import java.util.Optional;
2public class HomeServices {
3    private static final int NOW = 0;
4    private static Optional<HomeServices> service;
5
6public static Optional<HomeServices> get() {
7    service = Optional.of(service.orElse(new HomeServices()));
8    return service;
9}
10
11public Optional<Service> getRefrigertorControl() {
12    Service s = new  RefrigeratorService();
13    //...
14    return Optional.ofNullable(s);
15}
16
17public static void main(String[] args) {
18    /* Get Home Services handle */
19    Optional<HomeServices> homeServices = HomeServices.get();
20    if(homeServices != null) {
21        Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();
22        refrigertorControl.ifPresent(HomeServices::switchItOn);
23    }
24}
25
26public static void switchItOn(Service s){
27         //...
28    }
29}
30
Full Screen
copy
1Optional<Integer> possible = Optional.of(5);
2possible.isPresent(); // returns true
3possible.get(); // returns 5
4
Full Screen
copy
1class C {
2    private final MyType mustBeSet;
3    public C(MyType mything) {
4       mustBeSet=Contract.notNull(mything);
5    }
6   private String name = "<unknown>";
7   public void setName(String s) {
8      name = Contract.notNull(s);
9   }
10}
11
12
13class Contract {
14    public static <T> T notNull(T t) { if (t == null) { throw new ContractException("argument must be non-null"); return t; }
15}
16
Full Screen
copy
1if (someobject == null) {
2    // Handle null here then move on.
3}
4
Full Screen
copy
1if (someobject != null) {
2    .....
3    .....
4
5
6
7    .....
8}
9
Full Screen
copy
1ValidationUtils.getNullValidator().addParam(plans, "plans").addParam(persons, "persons").validate();
2
Full Screen
copy
1void validate() throws ValidationException;
2
Full Screen
copy
1Objects.requireNonNull(someObject);
2someObject.doCalc();
3
Full Screen
copy
1Parent(Child child) {
2   if (child == null) {
3      throw new NullPointerException("child");
4   }
5   this.child = child;
6}
7
Full Screen
copy
1Parent(Child child) {
2   this.child = Objects.requireNonNull(child, "child");
3}
4
Full Screen
copy
1static <T> T checkNotNull(T e) {
2   if (e == null) {
3      throw new NullPointerException();
4   }
5   return e;
6}
7
Full Screen
copy
1...
2void foo(int a, Person p) {
3   if (checkNotNull(p).getAge() > a) {
4      ...
5   }
6   else {
7      ...
8   }
9}
10...
11
Full Screen
copy
1checkNotNull(someobject).doCalc();
2
Full Screen
copy
1a.f(b); <-> b.f(a);
2
Full Screen
copy
1String foo;
2...
3if( StringUtils.isBlank( foo ) ) {
4   ///do something
5}
6
Full Screen
copy
1String foo;
2...
3if( StringUtils.isEmpty( foo ) ) {
4   ///do something
5}
6
Full Screen
copy
1public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
2    Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
3    return read(new StringReader(xml), true, validationEventHandler);
4}
5
Full Screen
copy
1Assert.notNull(validationEventHandler,"ValidationHandler not Injected");
2
Full Screen
copy
1public static Optional<Fruit> find(String name, List<Fruit> fruits) {
2   for (Fruit fruit : fruits) {
3      if (fruit.getName().equals(name)) {
4         return Optional.of(fruit);
5      }
6   }
7   return Optional.empty();
8}
9
Full Screen
copy
1Optional<Fruit> found = find("lemon", fruits);
2if (found.isPresent()) {
3   Fruit fruit = found.get();
4   String name = fruit.getName();
5}
6
Full Screen
copy
1String nameOrNull = find("lemon", fruits)
2    .map(f -> f.getName())
3    .orElse("empty-name");
4
Full Screen
copy
1if ( foo.equals("bar") ) {
2 // ...
3}
4
Full Screen
copy
1if ( "bar".equals(foo) ) {
2 // ...
3}
4
Full Screen
copy
1public String getPostcode(Person person) {  
2  return person?.getAddress()?.getPostcode();  
3}  
4
Full Screen
copy
1public void method(Object object) {
2  if (object == null) {
3    throw new IllegalArgumentException("...");
4  }
5
Full Screen
copy
1public String getFirst3Chars(String text) {
2  return text.subString(0, 3);
3}
4
Full Screen
copy
1if (object == null) {
2  // something
3} else {
4  // something else
5}
6
Full Screen
copy
1@NotNull public static String helloWorld() {
2    return "Hello World";
3}
4
Full Screen
copy
1@Nullable public static String helloWorld() {
2    return "Hello World";
3}
4
Full Screen
copy
1public static void main(String[] args)
2{
3    String result = helloWorld();
4    if(result != null) {
5        System.out.println(result);
6    }
7}
8
Full Screen
copy
1void someMethod(@NotNull someParameter) { }
2
Full Screen
copy
1someMethod(null);
2
copy
1@Nullable iWantToDestroyEverything() { return null; }
2
Full Screen
copy
1iWantToDestroyEverything().something();
2
Full Screen
copy
1assert <condition>
2
Full Screen
copy
1assert <condition> : <object>
2
Full Screen
copy
1public interface Action {
2  void doSomething();
3}
4
5public interface Parser {
6  Action findAction(String userInput);
7}
8
Full Screen
copy
1public class MyParser implements Parser {
2  private static Action DO_NOTHING = new Action() {
3    public void doSomething() { /* do nothing */ }
4  };
5
6  public Action findAction(String userInput) {
7    // ...
8    if ( /* we can't find any actions */ ) {
9      return DO_NOTHING;
10    }
11  }
12}
13
Full Screen
copy
1Parser parser = ParserFactory.getParser();
2if (parser == null) {
3  // now what?
4  // this would be an example of where null isn't (or shouldn't be) a valid response
5}
6Action action = parser.findAction(someInput);
7if (action == null) {
8  // do nothing
9} else {
10  action.doSomething();
11}
12
Full Screen
copy
1ParserFactory.getParser().findAction(someInput).doSomething();
2
Full Screen
copy
1try {
2    ParserFactory.getParser().findAction(someInput).doSomething();
3} catch(ActionNotFoundException anfe) {
4    userConsole.err(anfe.getMessage());
5}
6
Full Screen
copy
1public Action findAction(final String userInput) {
2    /* Code to return requested Action if found */
3    return new Action() {
4        public void doSomething() {
5            userConsole.err("Action not found: " + userInput);
6        }
7    }
8}
9
Full Screen
copy
1static void leakMe(final Object object) {
2    new Thread() {
3        public void run() {
4            Object o = object;
5            for (;;) {
6                try {
7                    sleep(Long.MAX_VALUE);
8                } catch (InterruptedException e) {}
9            }
10        }
11    }.start();
12}
13
Full Screen
copy
1    public static void main(String[] args) {
2        while (true) {
3            Element first = new Element();
4            first.next = new Element();
5            first.next.next = first;
6        }
7    }
8
Full Screen
copy
1public static Map<String, Integer> pseudoQueryDatabase();
2
Full Screen
copy
1class EntryHolder {
2    Map.Entry<String, Integer> entry;
3
4    EntryHolder(Map.Entry<String, Integer> entry) {
5        this.entry = entry;
6    }
7}
8
Full Screen
copy
1public class LeakTest {
2
3    private final List<EntryHolder> holdersCache = new ArrayList<>();
4    private static final int MAP_SIZE = 100_000;
5
6    public void run() {
7        // create 500 entries each holding a reference to an Entry of a TreeMap
8        IntStream.range(0, 500).forEach(value -> {
9            // create map
10            final Map<String, Integer> map = pseudoQueryDatabase();
11
12            final int index = new Random().nextInt(MAP_SIZE);
13
14            // get random entry from map
15            for (Map.Entry<String, Integer> entry : map.entrySet()) {
16                if (entry.getValue().equals(index)) {
17                    holdersCache.add(new EntryHolder(entry));
18                    break;
19                }
20            }
21            // to observe behavior in visualvm
22            try {
23                Thread.sleep(500);
24            } catch (InterruptedException e) {
25                e.printStackTrace();
26            }
27        });
28
29    }
30
31    public static Map<String, Integer> pseudoQueryDatabase() {
32        final Map<String, Integer> map = new TreeMap<>();
33        IntStream.range(0, MAP_SIZE).forEach(i -> map.put(String.valueOf(i), i));
34        return map;
35    }
36
37    public static void main(String[] args) throws Exception {
38        new LeakTest().run();
39    }
40}
41
Full Screen
copy
1import java.io.File;
2import java.io.FileOutputStream;
3import java.io.IOException;
4import java.util.zip.ZipEntry;
5import java.util.zip.ZipOutputStream;
6
7public class BigJarCreator {
8    public static void main(String[] args) throws IOException {
9        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File("big.jar")));
10        zos.putNextEntry(new ZipEntry("resource.txt"));
11        zos.write("not too much in here".getBytes());
12        zos.closeEntry();
13        zos.putNextEntry(new ZipEntry("largeFile.out"));
14        for (int i=0 ; i<10000000 ; i++) {
15            zos.write((int) (Math.round(Math.random()*100)+20));
16        }
17        zos.closeEntry();
18        zos.close();
19    }
20}
21
Full Screen
copy
1javac BigJarCreator.java
2java -cp . BigJarCreator
3
Full Screen
copy
1public class MemLeak {
2    public static void main(String[] args) throws InterruptedException {
3        int ITERATIONS=100000;
4        for (int i=0 ; i<ITERATIONS ; i++) {
5            MemLeak.class.getClassLoader().getResourceAsStream("resource.txt");
6        }
7        System.out.println("finished creation of streams, now waiting to be killed");
8
9        Thread.sleep(Long.MAX_VALUE);
10    }
11
12}
13
Full Screen
copy
1javac MemLeak.java
2java -Xmx2m -classpath .:big.jar MemLeak
3
Full Screen
copy
1MemLeak.class.getClassLoader().getResourceAsStream("resource.txt").close();
2
Full Screen
copy
1class Leakee {
2    public void check() {
3        if (depth > 2) {
4            Leaker.done();
5        }
6    }
7    private int depth;
8    public Leakee(int d) {
9        depth = d;
10    }
11    protected void finalize() {
12        new Leakee(depth + 1).check();
13        new Leakee(depth + 1).check();
14    }
15}
16
17public class Leaker {
18    private static boolean makeMore = true;
19    public static void done() {
20        makeMore = false;
21    }
22    public static void main(String[] args) throws InterruptedException {
23        // make a bunch of them until the garbage collector gets active
24        while (makeMore) {
25            new Leakee(0).check();
26        }
27        // sit back and watch the finalizers chew through memory
28        while (true) {
29            Thread.sleep(1000);
30            System.out.println("memory=" +
31                    Runtime.getRuntime().freeMemory() + " / " +
32                    Runtime.getRuntime().totalMemory());
33        }
34    }
35}
36
Full Screen
copy
1public class Leaker {
2    private static final Map<String, Object> CACHE = new HashMap<String, Object>();
3
4    // Keep adding until failure.
5    public static void addToCache(String key, Object value) { Leaker.CACHE.put(key, value); }
6}
7
Full Screen
copy
1pubclic class RequestProcessor {
2    private static final Logger logger = Logger.getLogger(RequestProcessor.class);
3    public void doSomething()  {
4        ....
5        final List<String> hugeList = new ArrayList<String>(10000);
6        new Thread() {
7           public void run() {
8               logger.info("Child thread spawned")
9               for(String s:hugeList) {
10                   ....
11               }
12           }
13        }.start();
14    }
15}    
16
Full Screen
copy
1public class Example1 {
2  public Example2 getNewExample2() {
3    return this.new Example2();
4  }
5  public class Example2 {
6    public Example2() {}
7  }
8}
9
Full Screen
copy
1public class Referencer {
2  public static Example2 GetAnExample2() {
3    Example1 ex = new Example1();
4    return ex.getNewExample2();
5  }
6
7  public static void main(String[] args) {
8    Example2 ex = Referencer.GetAnExample2();
9    // As long as ex is reachable; Example1 will always remain in memory.
10  }
11}
12
Full Screen
copy
1class A {
2    B bRef;
3}
4
5class B {
6    A aRef;
7}
8
9public class Main {
10    public static void main(String args[]) {
11        A myA = new A();
12        B myB = new B();
13        myA.bRef = myB;
14        myB.aRef = myA;
15        myA=null;
16        myB=null;
17        /* at this point, there is no access to the myA and myB objects, */
18        /* even though both objects still have active references. */
19    } /* main */
20}
21
Full Screen
copy
1public class Main {
2    public static void main(String args[]) {
3        Socket s = new Socket(InetAddress.getByName("google.com"),80);
4        s=null;
5        /* at this point, because you didn't close the socket properly, */
6        /* you have a leak of a native descriptor, which uses memory. */
7    }
8}
9
Full Screen
copy
1private static final Map<String, Info> myCache = new HashMap<>();
2
3public void getInfo(String key)
4{
5    // uses cache
6    Info info = myCache.get(key);
7    if (info != null) return info;
8
9    // if it's not in cache, then fetch it from the database
10    info = Database.fetch(key);
11    if (info == null) return null;
12
13    // and store it in the cache
14    myCache.put(key, info);
15    return info;
16}
17
Full Screen
copy
1<data>
2   <1>bla</1>
3   <2>foo</>
4   ...
5</data>
6
Full Screen
copy
1public class StringLeaker
2{
3    private final String muchSmallerString;
4
5    public StringLeaker()
6    {
7        // Imagine the whole Declaration of Independence here
8        String veryLongString = "We hold these truths to be self-evident...";
9
10        // The substring here maintains a reference to the internal char[]
11        // representation of the original string.
12        this.muchSmallerString = veryLongString.substring(0, 1);
13    }
14}
15
Full Screen
copy
1...
2this.muchSmallerString = new String(veryLongString.substring(0, 1));
3...
4
Full Screen
copy
1...
2this.muchSmallerString = veryLongString.substring(0, 1).intern();
3...
4
Full Screen
copy
1import java.lang.reflect.Constructor;
2import java.lang.reflect.Field;
3import sun.misc.Unsafe;
4
5
6public class TestUnsafe {
7
8    public static void main(String[] args) throws Exception{
9        Class unsafeClass = Class.forName("sun.misc.Unsafe");
10        Field f = unsafeClass.getDeclaredField("theUnsafe");
11        f.setAccessible(true);
12        Unsafe unsafe = (Unsafe) f.get(null);
13        System.out.print("4..3..2..1...");
14        try
15        {
16            for(;;)
17                unsafe.allocateMemory(1024*1024);
18        } catch(Error e) {
19            System.out.println("Boom :)");
20            e.printStackTrace();
21        }
22    }
23}
24
Full Screen
copy
1public E remove(int index) {
2    RangeCheck(index);
3
4    modCount++;
5    E oldValue = (E) elementData[index];
6
7    int numMoved = size - index - 1;
8    if (numMoved > 0)
9        System.arraycopy(elementData, index + 1, elementData, index,
10                numMoved);
11    elementData[--size] = null; // (!) Let gc do its work
12
13    return oldValue;
14}
15
Full Screen
copy
1void doWork() {
2    try {
3        Connection conn = ConnectionFactory.getConnection();
4        PreparedStatement stmt = conn.preparedStatement("some query");
5        // executes a valid query
6        ResultSet rs = stmt.executeQuery();
7        while(rs.hasNext()) {
8            // ... process the result set
9        }
10    } catch(SQLException sqlEx) {
11        log(sqlEx);
12    }
13}
14
Full Screen
copy
1class BadKey {
2   // no hashCode or equals();
3   public final String key;
4   public BadKey(String key) { this.key = key; }
5}
6
7Map map = System.getProperties();
8map.put(new BadKey("key"), "value"); // Memory leak even if your threads die.
9
Full Screen
copy
1class MemorableClass {
2    static final ArrayList list = new ArrayList(100);
3}
4
Full Screen
copy
1String str = readString(); // read lengthy string any source db,textbox/jsp etc..
2// This will place the string in memory pool from which you can't remove
3str.intern();
4
Full Screen
copy
1try {
2    BufferedReader br = new BufferedReader(new FileReader(inputFile));
3    ...
4    ...
5} catch (Exception e) {
6    e.printStacktrace();
7}
8
Full Screen
copy
1try {
2    Connection conn = ConnectionFactory.getConnection();
3    ...
4    ...
5} catch (Exception e) {
6    e.printStacktrace();
7}
8
Full Screen
copy
1getServletContext().setAttribute("SOME_MAP", map);
2
Full Screen
copy
1DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
2dtfb.append(DateTimeFormatter.ISO_LOCAL_DATE);
3dtfb.appendLiteral(' ');
4dtfb.append(DateTimeFormatter.ISO_LOCAL_TIME);
5DateTimeFormatter dtf = dtfb.toFormatter();
6ZoneId shanghai = ZoneId.of("Asia/Shanghai");
7
8String str3 = "1927-12-31 23:54:07";  
9String str4 = "1927-12-31 23:54:08";  
10
11ZonedDateTime zdt3 = LocalDateTime.parse(str3, dtf).atZone(shanghai);
12ZonedDateTime zdt4 = LocalDateTime.parse(str4, dtf).atZone(shanghai);
13
14Duration durationAtEarlierOffset = Duration.between(zdt3.withEarlierOffsetAtOverlap(), zdt4.withEarlierOffsetAtOverlap());
15
16Duration durationAtLaterOffset = Duration.between(zdt3.withLaterOffsetAtOverlap(), zdt4.withLaterOffsetAtOverlap());
17
Full Screen
copy
1// Both have offsets +08:05:52
2ZoneOffset zo3Earlier = zdt3.withEarlierOffsetAtOverlap().getOffset();
3ZoneOffset zo3Later = zdt3.withLaterOffsetAtOverlap().getOffset();
4
Full Screen
copy
1// +08:05:52
2ZoneOffset zo4Earlier = zdt4.withEarlierOffsetAtOverlap().getOffset();
3
4// +08:00
5ZoneOffset zo4Later = zdt4.withLaterOffsetAtOverlap().getOffset();
6
Full Screen
copy
1// Null
2ZoneOffsetTransition zot3 = shanghai.getRules().getTransition(ld3.toLocalDateTime);
3
4// An overlap transition
5ZoneOffsetTransition zot4 = shanghai.getRules().getTransition(ld3.toLocalDateTime);
6
Full Screen
copy
1long difference = (sDt4.getTime() - sDt3.getTime()) / 1000;
2System.out.println(difference);
3
Full Screen
copy
1import java.util.TimeZone;
2
3public class Test {
4    public static void main(String[] args) throws Exception {
5        long startOf1900Utc = -2208988800000L;
6        for (String id : TimeZone.getAvailableIDs()) {
7            TimeZone zone = TimeZone.getTimeZone(id);
8            if (zone.getRawOffset() != zone.getOffset(startOf1900Utc - 1)) {
9                System.out.println(id);
10            }
11        }
12    }
13}
14
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)