How to use toJson method of org.openqa.selenium.firefox.FirefoxBinary class

Best Selenium code snippet using org.openqa.selenium.firefox.FirefoxBinary.toJson

Run Selenium automation tests on LambdaTest cloud grid

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

copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.firefox;
19
20import static java.nio.file.StandardOpenOption.DELETE_ON_CLOSE;
21import static org.hamcrest.Matchers.is;
22import static org.hamcrest.Matchers.nullValue;
23import static org.junit.Assert.assertEquals;
24import static org.junit.Assert.assertFalse;
25import static org.junit.Assert.assertSame;
26import static org.junit.Assert.assertThat;
27import static org.junit.Assert.assertTrue;
28import static org.junit.Assert.fail;
29import static org.junit.Assume.assumeNotNull;
30import static org.junit.Assume.assumeThat;
31import static org.openqa.selenium.firefox.FirefoxDriver.MARIONETTE;
32import static org.openqa.selenium.firefox.FirefoxDriver.PROFILE;
33import static org.openqa.selenium.firefox.FirefoxDriver.SystemProperty.BROWSER_BINARY;
34import static org.openqa.selenium.firefox.FirefoxDriver.SystemProperty.BROWSER_PROFILE;
35import static org.openqa.selenium.firefox.FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE;
36import static org.openqa.selenium.firefox.FirefoxOptions.FIREFOX_OPTIONS;
37import static org.openqa.selenium.remote.CapabilityType.ACCEPT_INSECURE_CERTS;
38import static org.openqa.selenium.remote.CapabilityType.PAGE_LOAD_STRATEGY;
39
40import com.google.common.base.Throwables;
41import com.google.common.collect.ImmutableMap;
42import com.google.common.collect.ImmutableSet;
43
44import org.junit.Test;
45import org.openqa.selenium.Capabilities;
46import org.openqa.selenium.ImmutableCapabilities;
47import org.openqa.selenium.PageLoadStrategy;
48import org.openqa.selenium.Platform;
49import org.openqa.selenium.WebDriverException;
50import org.openqa.selenium.firefox.internal.ProfilesIni;
51import org.openqa.selenium.remote.DesiredCapabilities;
52import org.openqa.selenium.testing.JreSystemProperty;
53import org.openqa.selenium.testing.TestUtilities;
54
55import java.io.File;
56import java.io.IOException;
57import java.io.OutputStream;
58import java.nio.file.Files;
59import java.nio.file.Path;
60import java.nio.file.Paths;
61import java.nio.file.attribute.PosixFilePermission;
62import java.util.Map;
63import java.util.Optional;
64
65public class FirefoxOptionsTest {
66
67  @Test
68  public void canInitFirefoxOptionsWithCapabilities() {
69    FirefoxOptions options = new FirefoxOptions(new ImmutableCapabilities(ImmutableMap.of(
70        MARIONETTE, false,
71        PAGE_LOAD_STRATEGY, PageLoadStrategy.EAGER,
72        ACCEPT_INSECURE_CERTS, true)));
73
74    assertTrue(options.isLegacy());
75    assertEquals(options.toCapabilities().getCapability(PAGE_LOAD_STRATEGY), PageLoadStrategy.EAGER);
76    assertEquals(options.toCapabilities().getCapability(ACCEPT_INSECURE_CERTS), true);
77  }
78
79  @Test
80  public void canInitFirefoxOptionsWithCapabilitiesThatContainFirefoxOptions() {
81    FirefoxOptions options = new FirefoxOptions().setLegacy(true).addCapabilities(
82        new ImmutableCapabilities(ImmutableMap.of(PAGE_LOAD_STRATEGY, PageLoadStrategy.EAGER)));
83    Capabilities caps = new ImmutableCapabilities(ImmutableMap.of(FIREFOX_OPTIONS, options));
84
85    FirefoxOptions options2 = new FirefoxOptions(caps);
86
87    assertTrue(options2.isLegacy());
88    assertEquals(options2.toCapabilities().getCapability(PAGE_LOAD_STRATEGY), PageLoadStrategy.EAGER);
89  }
90
91  @Test
92  public void canInitFirefoxOptionsWithCapabilitiesThatContainFirefoxOptionsAsMap() {
93    FirefoxProfile profile = new FirefoxProfile();
94    Capabilities caps = new ImmutableCapabilities(ImmutableMap.of(
95        FIREFOX_OPTIONS, ImmutableMap.of("profile", profile)));
96
97    FirefoxOptions options = new FirefoxOptions(caps);
98
99    assertSame(options.getProfile(), profile);
100  }
101
102  @Test
103  public void binaryPathNeedNotExist() {
104    try {
105      new FirefoxOptions().setBinary("does/not/exist");
106    } catch (Exception e) {
107      fail("Did not expect to see any exceptions thrown: " + e);
108    }
109  }
110
111  @Test
112  public void shouldKeepRelativePathToBinaryAsIs() {
113    FirefoxOptions options = new FirefoxOptions().setBinary("some/path");
114    Capabilities caps = options.addTo(new DesiredCapabilities());
115
116    assertEquals("some/path", caps.getCapability(FirefoxDriver.BINARY));
117  }
118
119  @Test
120  public void shouldConvertPathToBinaryToUseForwardSlashes() {
121    FirefoxOptions options = new FirefoxOptions().setBinary("some\\path");
122    Capabilities caps = options.addTo(new DesiredCapabilities());
123
124    assertEquals("some/path", caps.getCapability(FirefoxDriver.BINARY));
125  }
126
127  @Test
128  public void shouldKeepWindowsDriveLetterInPathToBinary() {
129    FirefoxOptions options = new FirefoxOptions().setBinary("F:\\some\\path");
130    Capabilities caps = options.addTo(new DesiredCapabilities());
131
132    assertEquals("F:/some/path", caps.getCapability(FirefoxDriver.BINARY));
133  }
134
135  @Test
136  public void canUseForwardSlashesInWindowsPaths() {
137    FirefoxOptions options = new FirefoxOptions().setBinary("F:\\some\\path");
138    Capabilities caps = options.addTo(new DesiredCapabilities());
139
140    assertEquals("F:/some/path", caps.getCapability(FirefoxDriver.BINARY));
141  }
142
143  @Test
144  public void shouldKeepWindowsNetworkFileSystemRootInPathToBinary() {
145    FirefoxOptions options = new FirefoxOptions().setBinary("\\\\server\\share\\some\\path");
146    Capabilities caps = options.addTo(new DesiredCapabilities());
147
148    assertEquals("//server/share/some/path", caps.getCapability(FirefoxDriver.BINARY));
149  }
150
151  @Test
152  public void shouldKeepAFirefoxBinaryAsABinaryIfSetAsOne() throws IOException {
153    File fakeExecutable = Files.createTempFile("firefox", ".exe").toFile();
154    fakeExecutable.deleteOnExit();
155    FirefoxBinary binary = new FirefoxBinary(fakeExecutable);
156    FirefoxOptions options = new FirefoxOptions().setBinary(binary);
157
158    Capabilities caps = options.addTo(new DesiredCapabilities());
159
160    assertEquals(binary, caps.getCapability(FirefoxDriver.BINARY));
161  }
162
163  @Test
164  public void stringBasedBinaryRemainsAbsoluteIfSetAsAbsolute() throws IOException {
165    Map<String, Object> json = new FirefoxOptions().setBinary("/i/like/cheese").toJson();
166
167    assertEquals("/i/like/cheese", json.get("binary"));
168  }
169
170  @Test
171  public void pathBasedBinaryRemainsAbsoluteIfSetAsAbsolute() throws IOException {
172    Map<String, Object> json = new FirefoxOptions().setBinary(Paths.get("/i/like/cheese")).toJson();
173
174    assertEquals("/i/like/cheese", json.get("binary"));
175  }
176
177  @Test
178  public void shouldPickUpBinaryFromSystemPropertyIfSet() throws IOException {
179    JreSystemProperty property = new JreSystemProperty(BROWSER_BINARY);
180    String resetValue = property.get();
181
182    Path binary = Files.createTempFile("firefox", ".exe");
183    try (OutputStream ignored = Files.newOutputStream(binary, DELETE_ON_CLOSE)) {
184      Files.write(binary, "".getBytes());
185      if (! TestUtilities.getEffectivePlatform().is(Platform.WINDOWS)) {
186        Files.setPosixFilePermissions(binary, ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE));
187      }
188      property.set(binary.toString());
189      FirefoxOptions options = new FirefoxOptions();
190
191      FirefoxBinary firefoxBinary =
192          options.getBinaryOrNull().orElseThrow(() -> new AssertionError("No binary"));
193
194      assertEquals(binary.toString(), firefoxBinary.getPath());
195    } finally {
196      property.set(resetValue);
197    }
198  }
199
200  @Test
201  public void shouldPickUpLegacyValueFromSystemProperty() throws IOException {
202    JreSystemProperty property = new JreSystemProperty(DRIVER_USE_MARIONETTE);
203    String resetValue = property.get();
204
205    try {
206      // No value should default to using Marionette
207      property.set(null);
208      FirefoxOptions options = new FirefoxOptions();
209      assertFalse(options.isLegacy());
210
211      property.set("false");
212      options = new FirefoxOptions();
213      assertTrue(options.isLegacy());
214
215      property.set("true");
216      options = new FirefoxOptions();
217      assertFalse(options.isLegacy());
218    } finally {
219      property.set(resetValue);
220    }
221  }
222
223  @Test
224  public void settingMarionetteToFalseAsASystemPropertyDoesNotPrecedence() {
225    JreSystemProperty property = new JreSystemProperty(DRIVER_USE_MARIONETTE);
226    String resetValue = property.get();
227
228    try {
229      DesiredCapabilities caps = new DesiredCapabilities();
230      caps.setCapability(MARIONETTE, true);
231
232      property.set("false");
233      FirefoxOptions options = new FirefoxOptions().addCapabilities(caps);
234      assertFalse(options.isLegacy());
235    } finally {
236      property.set(resetValue);
237    }
238  }
239
240  @Test
241  public void shouldPickUpProfileFromSystemProperty() throws IOException {
242    FirefoxProfile defaultProfile = new ProfilesIni().getProfile("default");
243    assumeNotNull(defaultProfile);
244
245    JreSystemProperty property = new JreSystemProperty(BROWSER_PROFILE);
246    String resetValue = property.get();
247    try {
248      property.set("default");
249      FirefoxOptions options = new FirefoxOptions();
250      Optional<FirefoxProfile> profile = options.getProfileOrNull();
251
252      assertTrue(profile.isPresent());
253    } finally {
254      property.set(resetValue);
255    }
256  }
257
258  @Test(expected = WebDriverException.class)
259  public void shouldThrowAnExceptionIfSystemPropertyProfileDoesNotExist() {
260    String unlikelyProfileName = "this-profile-does-not-exist-also-cheese";
261    FirefoxProfile foundProfile = new ProfilesIni().getProfile(unlikelyProfileName);
262    assumeThat(foundProfile, is(nullValue()));
263
264    JreSystemProperty property = new JreSystemProperty(BROWSER_PROFILE);
265    String resetValue = property.get();
266    try {
267      property.set(unlikelyProfileName);
268      new FirefoxOptions();
269    } finally {
270      property.set(resetValue);
271    }
272  }
273
274  @Test
275  public void callingToStringWhenTheBinaryDoesNotExistShouldNotCauseAnException() {
276    FirefoxOptions options =
277        new FirefoxOptions().setBinary("there's nothing better in life than cake or peas.");
278    try {
279      options.toString();
280      // The binary does not exist on this machine, but could do elsewhere. Be chill.
281    } catch (Exception e) {
282      fail(Throwables.getStackTraceAsString(e));
283    }
284  }
285}
286
Full Screen
copy
1package com.iansloat.scalperbot;
2
3import java.awt.AWTException;
4import java.awt.BorderLayout;
5import java.awt.Color;
6import java.awt.EventQueue;
7import java.awt.Image;
8import java.awt.SystemTray;
9import java.awt.Toolkit;
10import java.awt.TrayIcon;
11import java.awt.TrayIcon.MessageType;
12import java.awt.event.ActionEvent;
13import java.awt.event.ActionListener;
14import java.awt.event.KeyAdapter;
15import java.awt.event.KeyEvent;
16import java.awt.event.WindowAdapter;
17import java.awt.event.WindowEvent;
18import java.io.File;
19import java.io.IOException;
20import java.net.MalformedURLException;
21import java.net.URL;
22import java.util.ArrayList;
23import java.util.List;
24import java.util.Queue;
25import java.util.concurrent.BlockingQueue;
26import java.util.concurrent.LinkedBlockingQueue;
27import java.util.logging.Level;
28
29import javax.sound.sampled.AudioInputStream;
30import javax.sound.sampled.AudioSystem;
31import javax.sound.sampled.Clip;
32import javax.sound.sampled.FloatControl;
33import javax.sound.sampled.LineUnavailableException;
34import javax.sound.sampled.UnsupportedAudioFileException;
35import javax.swing.JButton;
36import javax.swing.JFrame;
37import javax.swing.JPanel;
38import javax.swing.JScrollPane;
39import javax.swing.JTextArea;
40import javax.swing.JTextField;
41import javax.swing.UIManager;
42import javax.swing.UnsupportedLookAndFeelException;
43
44import org.apache.commons.io.FileUtils;
45import org.apache.commons.io.LineIterator;
46import org.apache.http.HttpEntity;
47import org.apache.http.HttpResponse;
48import org.apache.http.client.HttpClient;
49import org.apache.http.client.methods.HttpPost;
50import org.apache.http.entity.StringEntity;
51import org.apache.http.impl.client.HttpClients;
52import org.json.JSONObject;
53import org.openqa.selenium.firefox.FirefoxBinary;
54import org.openqa.selenium.firefox.FirefoxDriver;
55import org.openqa.selenium.firefox.FirefoxOptions;
56import org.openqa.selenium.firefox.FirefoxProfile;
57import org.openqa.selenium.firefox.ProfilesIni;
58import org.openqa.selenium.logging.LogType;
59import org.openqa.selenium.logging.LoggingPreferences;
60import org.openqa.selenium.remote.CapabilityType;
61import org.slf4j.Logger;
62import org.slf4j.LoggerFactory;
63
64import com.iansloat.scalperbot.entities.jobs.BestbuyJob;
65import com.iansloat.scalperbot.entities.jobs.Job;
66import com.iansloat.scalperbot.entities.products.Product;
67
68import net.miginfocom.swing.MigLayout;
69
70public class ScalperBot {
71
72	private static final Logger logger = LoggerFactory.getLogger(ScalperBot.class);
73
74	public static List<FirefoxDriver> driverCache = new ArrayList<>();
75
76	private static JFrame frmScalperBot;
77	private static JTextField textField;
78
79	private static Job bestbuy;
80	private static Clip clip;
81	private static AudioInputStream audioInputStream;
82	private static String webHookUrl = "";
83	private static String webHookMsg = "";
84	private static BlockingQueue<String> inputQueue = new LinkedBlockingQueue<>();
85
86	public static FirefoxDriver getNewBrowserInstance() {
87		FirefoxProfile profile = new ProfilesIni().getProfile("selenium");
88		if (profile == null) {
89			try {
90				logger.info("Creating firefox selenium profile...");
91				Runtime.getRuntime().exec(new FirefoxBinary().toJson() + " -CreateProfile selenium");
92				Thread.sleep(2000);
93				profile = new ProfilesIni().getProfile("selenium");
94				if (profile == null) {
95					logger.error("Failed to create selenium profile");
96					Thread.sleep(3000);
97					System.exit(-1);
98				}
99			} catch (IOException | InterruptedException e) {
100				return null;
101			}
102		}
103		FirefoxBinary firefoxBinary = new FirefoxBinary();
104		firefoxBinary.addCommandLineOptions("--headless");
105		System.setProperty("webdriver.gecko.driver", ".\\geckodriver.exe");
106		System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE, "null");
107		FirefoxOptions firefoxOptions = new FirefoxOptions();
108		firefoxOptions.setBinary(firefoxBinary);
109		if (profile != null)
110			firefoxOptions.setProfile(profile);
111		LoggingPreferences pref = new LoggingPreferences();
112		pref.enable(LogType.BROWSER, Level.OFF);
113		pref.enable(LogType.CLIENT, Level.OFF);
114		pref.enable(LogType.DRIVER, Level.OFF);
115		pref.enable(LogType.PERFORMANCE, Level.OFF);
116		pref.enable(LogType.PROFILER, Level.OFF);
117		pref.enable(LogType.SERVER, Level.OFF);
118		firefoxOptions.setCapability(CapabilityType.LOGGING_PREFS, pref);
119		FirefoxDriver driver = new FirefoxDriver(firefoxOptions);
120		driverCache.add(driver);
121		return driver;
122	}
123
124	private static void displayTray() throws AWTException {
125		// Obtain only one instance of the SystemTray object
126		SystemTray tray = SystemTray.getSystemTray();
127
128		// If the icon is a file
129		Image image = Toolkit.getDefaultToolkit().createImage("icon.png");
130		// Alternative (if the icon is on the classpath):
131		// Image image =
132		// Toolkit.getDefaultToolkit().createImage(getClass().getResource("icon.png"));
133
134		TrayIcon trayIcon = new TrayIcon(image, "Stock checker");
135		// Let the system resize the image if needed
136		trayIcon.setImageAutoSize(true);
137		// Set tooltip text for the tray icon
138		trayIcon.setToolTip("Stock alert");
139		tray.add(trayIcon);
140		trayIcon.addActionListener(new ActionListener() {
141
142			@Override
143			public void actionPerformed(ActionEvent e) {
144				EventQueue.invokeLater(new Runnable() {
145
146					@Override
147					public void run() {
148						frmScalperBot.toFront();
149					}
150
151				});
152			}
153
154		});
155		trayIcon.displayMessage("STOCK FOUND!!!!!", "WEE WOO WEE WOO", MessageType.INFO);
156	}
157
158	public static void main(String[] args) {
159
160		Runtime.getRuntime().addShutdownHook(new Thread() {
161			public void run() {
162				driverCache.forEach(d -> d.quit());
163			}
164		});
165
166		try {
167			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
168		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
169				| UnsupportedLookAndFeelException e) {
170			e.printStackTrace();
171		}
172		frmScalperBot = new JFrame();
173		frmScalperBot.setTitle("Scalper bot");
174		frmScalperBot.setBounds(100, 100, 894, 599);
175		frmScalperBot.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
176		frmScalperBot.getContentPane().setLayout(new BorderLayout(0, 0));
177
178		JPanel panel = new JPanel();
179		panel.setBorder(null);
180		frmScalperBot.getContentPane().add(panel, BorderLayout.SOUTH);
181		panel.setLayout(new MigLayout("", "[grow][]", "[]"));
182
183		textField = new JTextField();
184		textField.addKeyListener(new KeyAdapter() {
185			@Override
186			public void keyReleased(KeyEvent e) {
187				if (e.getKeyCode() == KeyEvent.VK_ENTER && !textField.getText().equals("")) {
188					inputQueue.add(textField.getText());
189					textField.setText("");
190				}
191			}
192		});
193		panel.add(textField, "cell 0 0,growx");
194		textField.setColumns(10);
195
196		JButton Enter = new JButton("Enter");
197		Enter.addActionListener(new ActionListener() {
198			public void actionPerformed(ActionEvent e) {
199				if (!textField.getText().equals("")) {
200					inputQueue.add(textField.getText());
201					textField.setText("");
202				}
203			}
204		});
205		panel.add(Enter, "cell 1 0");
206
207		JPanel panel_1 = new JPanel();
208		frmScalperBot.getContentPane().add(panel_1, BorderLayout.CENTER);
209		panel_1.setLayout(new MigLayout("", "[grow]", "[grow]"));
210
211		JScrollPane scrollPane = new JScrollPane();
212		panel_1.add(scrollPane, "cell 0 0,grow");
213
214		JTextArea textArea = new JTextArea();
215		scrollPane.setViewportView(textArea);
216
217		Enter.setEnabled(false);
218		textField.setEditable(false);
219
220		MessageConsole mc = new MessageConsole(textArea);
221
222		mc.redirectOut();
223		mc.redirectErr(Color.RED, null);
224		mc.setMessageLines(100);
225
226		frmScalperBot.setVisible(true);
227
228		System.out.println("Please wait. Bot is starting up...");
229		File webHook = new File("webhook.txt");
230		if (webHook.exists()) {
231			try {
232				LineIterator iterator = FileUtils.lineIterator(webHook, "UTF-8");
233				webHookUrl = iterator.nextLine();
234				try {
235					new URL(webHookUrl);
236					webHookMsg = iterator.nextLine();
237				} catch (MalformedURLException e) {
238					logger.error("Webhook url is invalid. Ignoring...");
239					webHookUrl = "";
240				}
241			} catch (IOException e) {
242				e.printStackTrace();
243			}
244		}
245		if (!webHookUrl.equals("")) {
246			logger.info("Webhook url set to " + webHookUrl);
247			logger.info("Webhook message set to " + webHookMsg);
248		}
249		bestbuy = new BestbuyJob();
250		boolean doLoop = true;
251		List<Product> products;
252		while (doLoop) {
253			System.out.print("What would you like to search for: ");
254			Enter.setEnabled(true);
255			textField.setEditable(true);
256			String search = "";
257			try {
258				search = inputQueue.take();
259			} catch (InterruptedException e2) {
260				e2.printStackTrace();
261				System.exit(-1);
262			}
263			System.out.println(search);
264			Enter.setEnabled(false);
265			textField.setEditable(false);
266			products = bestbuy.getStore().searchForProducts(search);
267			if (products != null) {
268				if (products.size() > 0) {
269					boolean stop = false;
270					while (!stop) {
271						System.out.println("Please type the number of your selection:");
272						for (int i = 0; i < products.size(); i++) {
273							System.out.println((i + 1) + ". " + products.get(i).getProductName());
274						}
275						System.out.println((products.size() + 1) + ". Print current queued products");
276						System.out.println((products.size() + 2) + ". Reprint search results");
277						System.out.println((products.size() + 3) + ". Start job");
278						System.out.println((products.size() + 4) + ". Queue all and start job");
279						boolean subLoop = true;
280						while (subLoop) {
281							System.out.print('>');
282							Enter.setEnabled(true);
283							textField.setEditable(true);
284							String choiceStr = "";
285							try {
286								choiceStr = inputQueue.take();
287							} catch (InterruptedException e1) {
288								e1.printStackTrace();
289								System.exit(-1);
290							}
291							System.out.println(choiceStr);
292							Enter.setEnabled(false);
293							textField.setEditable(false);
294							try {
295								int choice = Integer.parseInt(choiceStr);
296								if (choice > 0 && choice <= products.size() + 4) {
297									if (choice == products.size() + 1) {
298										for (int i = 0; i < bestbuy.getPendingProducts().size(); i++) {
299											System.out.println(bestbuy.getPendingProducts().get(i).getProductName());
300										}
301									} else if (choice == products.size() + 2) {
302										for (int i = 0; i < products.size(); i++) {
303											System.out.println((i + 1) + ". " + products.get(i).getProductName());
304										}
305									} else if (choice == products.size() + 3) {
306										if (bestbuy.getPendingProducts().size() > 0) {
307											subLoop = false;
308											stop = true;
309											doLoop = false;
310										} else {
311											System.out
312													.println("You do not have enough products queued to start the job");
313											subLoop = false;
314										}
315									} else if (choice == products.size() + 4) {
316										for (int i = 0; i < products.size(); i++) {
317											bestbuy.addProduct(products.get(i));
318										}
319										subLoop = false;
320										stop = true;
321										doLoop = false;
322									} else {
323										bestbuy.addProduct(products.get(choice - 1));
324										products.remove(choice - 1);
325										subLoop = false;
326									}
327								}
328							} catch (Exception e) {
329								System.out.println("Please input a NUMBER");
330							}
331						}
332					}
333				} else
334					System.out.println("No products found");
335			} else
336				System.out.println("No products found");
337		}
338		bestbuy.startJob();
339		bestbuy.waitForComplete();
340		Queue<Product> results = bestbuy.getCheckoutQueue();
341		String launchArgs = "";
342		while (!results.isEmpty()) {
343			launchArgs += results.poll().getSourceURL() + ' ';
344		}
345		try {
346			Runtime.getRuntime().exec(new FirefoxBinary().toJson() + ' ' + launchArgs);
347		} catch (IOException e) {
348			e.printStackTrace();
349		}
350		File alarm = new File("alarm.wav");
351		if (alarm.exists()) {
352			try {
353				audioInputStream = AudioSystem.getAudioInputStream(alarm);
354				clip = AudioSystem.getClip();
355				clip.open(audioInputStream);
356				FloatControl volume = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
357				volume.setValue(1.0f);
358				new Thread(() -> {
359					clip.start();
360					clip.loop(Clip.LOOP_CONTINUOUSLY);
361				}).start();
362			} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
363				e.printStackTrace();
364			}
365		} else {
366			logger.info("alarm.wav not found so no sound was played");
367		}
368		if (!webHookUrl.equals("")) {
369			new Thread(() -> {
370				HttpClient client = HttpClients.createDefault();
371				HttpPost postRequest = new HttpPost(webHookUrl);
372				postRequest.addHeader("Content-Type", "application/json");
373				JSONObject msgBody = new JSONObject();
374				msgBody.put("content", webHookMsg);
375				try {
376					postRequest.setEntity(new StringEntity(msgBody.toString()));
377					HttpResponse response = client.execute(postRequest);
378					HttpEntity entity = response.getEntity();
379					if (entity != null) {
380						System.out.println(entity.getContent().readAllBytes());
381					}
382				} catch (IOException e) {
383					e.printStackTrace();
384				}
385			}).start();
386		} else {
387			logger.info("No webhook set so post request was skipped");
388		}
389		frmScalperBot.addWindowListener(new WindowAdapter() {
390			@Override
391			public void windowClosing(WindowEvent e) {
392				if (audioInputStream != null)
393					try {
394						audioInputStream.close();
395					} catch (IOException e1) {
396						e1.printStackTrace();
397					}
398				if (clip != null)
399					clip.stop();
400			}
401		});
402		try {
403			displayTray();
404		} catch (AWTException e1) {
405			e1.printStackTrace();
406		}
407		bestbuy.shutdownJob();
408		System.out.println("STOCK HAS BEEN FOUND!!!!!");
409		System.out.println("You can close this window to end your suffering...");
410	}
411
412}
413
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

Trigger toJson code on LambdaTest Cloud Grid

Execute automation tests with toJson on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

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