Best io.appium code snippet using io.appium.java_client.MobileBy.ByImage.toString
BaseTest.java
Source:BaseTest.java  
...152                }153            }154        });155        thread.start();156//        String x = driver.getCapabilities().getCapability("deviceName").toString();157//        String y = (driver.getSessionDetails()).toString();158//        Log.info(deviceName);159//        }160    }161    @AfterClass162    public void after() {163    }164    @AfterTest165    public void afterTest() {166    }167    public void openSTB() {168        try {169            List<String> lsArgs = Arrays.asList("");170            List<String> lsArgs2 = Arrays.asList("");171            Map<String, Object> lsCmd = ImmutableMap.of("command", "dumpsys power | grep state=", "args", lsArgs);172            String lsOutput = (String) driver.executeScript("mobile: shell", lsCmd);173            if (lsOutput.contains("OFF")) {174                Log.info("The STB is closed ... Opening the STB... ");175                Map<String, Object> OFF = ImmutableMap.of("command", "input keyevent 26", "args", lsArgs2);176                String state = (String) driver.executeScript("mobile: shell", OFF);177            }178            if (lsOutput.contains("ON")) {179            }180//        } else {181//            Log.info("STB is off, Opening STB, please wait a moment ...");182//            Map<String, Object> openscreen = ImmutableMap.of("command", "input keyevent 26", "args", lsArgs);183//            String OpenScreen = (String) driver.executeScript("mobile: shell", openscreen);184//            Log.info(OpenScreen);185        } catch (Exception ignore) {186            Log.info(ignore.getMessage());187        }188    }189    public void read(String FILENAME) {190//        final String FILENAME = "C:\\Selenium\\Eyal\\eyal.txt";191        BufferedReader br = null;192        FileReader fr = null;193        try {194            //br = new BufferedReader(new FileReader(FILENAME));195            fr = new FileReader(FILENAME);196            br = new BufferedReader(fr);197            String sCurrentLine;198            int printCount = 0; // Counter to count from 0 to 9 for printing 10 lines.199            boolean foundFatal = false; // Boolean variable to know when we found the fatal.200            while ((sCurrentLine = br.readLine()) != null) {201                if (sCurrentLine.contains("Fatal signal") || (sCurrentLine.contains("FATAL EXCEPTION"))) {202                    foundFatal = true; // We found the fatal exception. No need to continue and search for another.203                }204                if (printCount == 9) { // If we reached a counter of 9 we just finished printing 10 lines.205                }206                if (foundFatal) {207                    // We found the fatal. Print a line and start counting up to 10 lines.208                    Log.info(sCurrentLine);209                    //SendEmail.sendmail(sCurrentLine, "eyal.avramchik@partner.co.il", "FATAL EXCEPTION !!!!!!");210                    printCount++;211                }212            }213        } catch (IOException e) {214            e.printStackTrace();215        } finally {216            try {217                if (br != null)218                    br.close();219                if (fr != null)220                    fr.close();221            } catch (IOException ex) {222                ex.printStackTrace();223            }224        }225    }226    @Parameters({"deviceName"})227    public String monitorErrors(String deviceName, String ip) {228//        capabilities.setCapability("deviceName", deviceName);229        List<String> adb = Arrays.asList("");230        List<String> adb1 = Arrays.asList("");231        List<String> adb2 = Arrays.asList("");232        List<String> adb3 = Arrays.asList("");233        List<String> adb4 = Arrays.asList("");234        List<String> adb5 = Arrays.asList("");235        List<String> adb6 = Arrays.asList("");236        List<String> adb7 = Arrays.asList("");237        List<String> adb8 = Arrays.asList("");238        List<String> adb9 = Arrays.asList("");239        List<String> adb10 = Arrays.asList("");240        try {241            Map<String, Object> ADB = ImmutableMap.of("command", "logcat -d |grep 'DRM'", "args", adb);242            String AA = (String) this.driver.executeScript("mobile: shell", ADB);243            driver.pressKey(new KeyEvent(AndroidKey.CHANNEL_UP));244            Log.info("--- Zapping up ---");245            Thread.sleep(4000);246//            if (AA.contains("teardown/3002")) {247//                takeScreenShot();248//                Map<String, Object> AD = ImmutableMap.of("command", "logcat -d |grep 'teardown/3002'", "args", adb1);249//                String teardown = (String) this.driver.executeScript("mobile: shell", AD);250//                Log.info("********** Decoding error from ********** " + deviceName + "'s STB:  " + teardown);251//                logCatLinux(ip);252//                SendEmail.sendmail(teardown, Eyal, "Decoding Error is catched right now");253//                Thread.sleep(60000);254//                Log.info("Wait 60 seconds before retry mannually");255//            } if (AA.contains("error_code:#PBA")) {256//                takeScreenShot();257//                Map<String, Object> PBA = ImmutableMap.of("command", "logcat -d |grep 'error_code:#PBA'", "args", adb3);258//                String pbaerror = (String) this.driver.executeScript("mobile: shell", PBA);259//                Log.info("********** PBA Error ********** " + pbaerror);260//                logCatLinux(ip);261////                SendEmail.sendmail(pbaerror, "eyal.avramchik@partner.co.il", "PBA Error");262//                Thread.sleep(60000);263//                Log.info("Wait 60 seconds before retry mannually");264//265//            } else if (AA.contains("IFS_RESULT_HOST")) {266//                //press ok button to see the mini epg info267//                takeScreenShot();268//                Map<String, Object> DECODING = ImmutableMap.of("command", "logcat -d|grep 'IFS_RESULT_HOST'", "args", adb4);269//                String blackscreen = (String) this.driver.executeScript("mobile: shell", DECODING);270//                Log.info("********** SC error ********** " + blackscreen);271//                logCatLinux(ip);272//                Thread.sleep(60000);273//                Log.info("Wait 60 seconds before retry mannually");274////                SendEmail.sendmail(blackscreen, "eyal.avramchik@partner.co.il", "SC Error");275//            } else if (AA.contains("fatal")) {276//                takeScreenShot();277//                Map<String, Object> COACH = ImmutableMap.of("command", "logcat -d|grep 'fatal'", "args", adb5);278//                String fatal = (String) this.driver.executeScript("mobile: shell", COACH);279//                Log.info("********** fatal catched ********** " + fatal);280//                logCatLinux(ip);281//                Thread.sleep(60000);282//                Log.info("Wait 60 seconds before retry mannually");283//                Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);284//                this.driver.executeScript("mobile: shell", clearLogcat2);285//            }286            if (AA != null) {287                Log.info(AA);288                takeScreenShot();289                Log.info("First screenshot");290                Log.info("DRM Error catched");291                logCatLinux(ip);292                Thread.sleep(60000);293                Log.info("Wait 60 seconds before retry mannually");294                takeScreenShot();295                Log.info("Second screenshot after 60 seconds");296                Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);297                this.driver.executeScript("mobile: shell", clearLogcat2);298            }299//            if (AA.contains("Player is paused")) {300////                Map<String, Object> gg = ImmutableMap.of("command", "logcat -d |grep 'Player is paused'", "args", adb8);301////                String pause = (String) this.driver.executeScript("mobile: shell", gg);302//                Log.info("********** Player is paused ********** " + deviceName + "'s STB:  ");303//            } else if (AA.contains("Player is resumed")) {304////                Map<String, Object> bb = ImmutableMap.of("command", "logcat -d |grep 'Player is resumed'", "args", adb9);305////                String pause1 = (String) this.driver.executeScript("mobile: shell", bb);306//                Log.info("********** Player is Resumed ********** " + deviceName + "'s STB:  ");307//            } else if (AA.contains("exoPlayer is buffering")) {308////                Map<String, Object> cc = ImmutableMap.of("command", "logcat -d |grep 'Player is buffering'", "args", adb10);309////                String pause2 = (String) this.driver.executeScript("mobile: shell", cc);310//                Log.info("********** Player is Live ********** " + deviceName + "'s STB:  ");311//            }312        } catch (Exception ignore) {313        }314        return deviceName;315    }316    public void pingSent(String ip) {317        List<String> ping = Arrays.asList("");318        List<String> gate = Arrays.asList("");319        Map<String, Object> DNS = ImmutableMap.of("command", "ping -c1 80.179.52.100 | grep packets", "args", ping);320        String result = (String) this.driver.executeScript("mobile: shell", DNS);321        Map<String, Object> GATE = ImmutableMap.of("command", "ping -c1 80.179.52.100 | grep packets", "args", gate);322        String def = (String) this.driver.executeScript("mobile: shell", GATE);323        if (result.contains("0 received")) {324            Log.info("Ping Fails !!!!!!!!!!!!!!!!!!!!!!!!!!!!!Ping Fails!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Ping Fails!!!!!!!!!!!!!!!!!!!!!!!!!!Ping Fails " + result + ip);325            takeScreenShot();326            SendEmail.sendmail(result, "eyal.avramchik@partner.co.il", "Ping fails in Eyal automation !!");327        } else if (def.contains("0 received")) {328            Log.info("Default Gateway Ping Fails !!!!!!!!!!!!!!!!!!!!!!!!!!!!! Default Gateway Ping Fails !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Default Gateway Ping Fails !!!!!!!!!!!!!!!!!!!!!!!!!! Default Gateway Ping Fails " + def);329            takeScreenShot();330            SendEmail.sendmail(result, "eyal.avramchik@partner.co.il", "Default Gateway Ping Fails in Eyal automation !!");331        }332    }333    public void PBA() {334        List<String> pba = Arrays.asList("");335        try {336            Map<String, Object> PBAerror = ImmutableMap.of("command", "logcat -d | grep  'IFS_RESULT_HOST'", "args", pba);337            String AA = (String) this.driver.executeScript("mobile: shell", PBAerror);338            if (AA.contains("IFS_RESULT_HOST")) {339                driver.pressKeyCode(23);340                takeScreenShot();341                Log.info(AA);342//                SendEmail.sendmail(AA, Eyal, "Black screen catched !!");343                List<String> adb1 = Arrays.asList("");344                Map<String, Object> ADB2 = ImmutableMap.of("command", "logcat -c", "args", adb1);//clear the logcat and get new lines345                String bb = (String) this.driver.executeScript("mobile: shell", ADB2);346            }347        } catch (Exception ignore) {348        }349    }350    public void takeScreenShot() {351        // Set folder name to store screenshots.352        String destDir = "screenshots";353        // Capture screenshot.354        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);355        Log.info("Screensot is captured");356        // Set date format to set It as screenshot file name.357        SimpleDateFormat date = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");358        // Create folder under project with name "screenshots" provided to destDir.359        new File(destDir).mkdirs();360        // Set file name using current date time.361        String destFile = date.format(new Date()) + ".png";362        try {363            // Copy paste file at destination folder location364            FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));365            Log.info("Screenshot added to the folder");366        } catch (IOException e) {367            e.printStackTrace();368        }369    }370//    public void p() {371//        try {372//            Process pr = Runtime.getRuntime().exec("adb" + " logcat -d");373//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pr.getInputStream()));374//            StringBuilder log = new StringBuilder();375//            String line = "";376//            while ((line = bufferedReader.readLine()) != null) {377//                log.append(line);378//               Log.info(log.toString());379//            }380//        } catch (IOException e){}381//    }382    public String getIfsPid() {383        List<String> pid = Arrays.asList("");384        Map<String, Object> PID = ImmutableMap.of("command", "pidof com.ifeelsmart.smartui", "args", pid);//clear the logcat and get new lines385        String ifspid = (String) this.driver.executeScript("mobile: shell", PID);386        return ifspid;387    }388    public void killIfsPid() {389        List<String> kill = Arrays.asList("");390        Map<String, Object> KILL = ImmutableMap.of("command", "kill " + getIfsPid(), "args", kill);//clear the logcat and get new lines391        String killifs = (String) this.driver.executeScript("mobile: shell", KILL);392    }393    public void readLogcat() throws IOException {394        BufferedReader reader = null;395        File file = new File("C:\\Users\\OSN20933\\shlomi_crash.txt");396        try {397            reader = new BufferedReader(new FileReader(file));398            for (String next, line = reader.readLine(); line != null; line = next) {399                next = reader.readLine();400//401//                Log.info("Current line: " + line);402                Boolean decoding = line.contains("teardown/3002");403                Boolean PBA = line.contains("error_code:#PBA");404                Boolean BlackScreen = line.contains("IFS_RESULT_HOST");405                if (decoding) {406//                    SendEmail.sendmail("Decoding error is cacthed","eyal.avramchik@partner.co.il","Decoding error is cacthed");407                    Log.info("Decoding error catched !!");408                } else if (PBA) {409                    SendEmail.sendmail("PBA error is cacthed", "eyal.avramchik@partner.co.il", "PBA error is cacthed");410                } else if (BlackScreen) {411                    takeScreenShot();412//                    SendEmail.sendmail("Black screen error is cacthed", "eyal.avramchik@partner.co.il", "Black screen error is cacthed");413                }414//                Log.info("Next line: " + next);415//                if (line.contains("IFS_RESULT_HOST")) {416//                    Log.info("-------- Black screen catched ---------");417//                } else if (line.contains("error_code:#PBA")) {418//                    Log.info("PBA error occures");419//                } else if (line.contains("×× ××¡× ×××¦× ×©×× × ×ת×× 30 שנ××ת")) {420//                    Log.info("Entering Sleep mode from LogCat");421//                } else if (line.contains("Waking up by power key from standby mode")) {422//                    Log.info("Waking up from LogCat");423//                } else if (line.contains("teardown/3002")) {424//                    Log.info("----------- Decoding error catched -----------");425//                } else if (line.contains("STB Information")) {426//                    Log.info("STB Information");427            }428        } finally {429            if (reader != null) try {430                reader.close();431            } catch (IOException logOrIgnore) {432            }433        }434//       File file = new File("C:\\Selenium\\Eyal\\stb.txt");435//436//       BufferedReader br = new BufferedReader(new FileReader(file));437//438//       String st;439//       while ((st = br.readLine()) != null)440//           if (st.contains("STB Information"))441//               Log.info(st);442//           else443//               break;444    }445    public void shellCommands() throws IOException {446        try {447            CommandLine cmd = new CommandLine("adb");448            cmd.addArgument("logcat", false).addArgument("-d", false);449            DefaultExecutor exec = new DefaultExecutor();450            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();451            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);452            exec.setStreamHandler(streamHandler);453            exec.execute(cmd);454            if (outputStream.toString().contains("IFS_RESULT_HOST")) {455                List<String> adb1 = Arrays.asList("");456                Map<String, Object> printtear = ImmutableMap.of("command", "logcat -d |grep 'IFS_RESULT_HOST'", "args", adb1);457                driver.pressKeyCode(23);458                takeScreenShot();459                String coach = (String) this.driver.executeScript("mobile: shell", printtear);460                Log.info(coach);461            } else if (outputStream.toString().contains("error_code:#PBA")) {462                List<String> ad = Arrays.asList("");463                Map<String, Object> ppp = ImmutableMap.of("command", "logcat -d |grep 'error_code:#PBA'", "args", ad);464                driver.pressKeyCode(23);465                takeScreenShot();466                String ccc = (String) this.driver.executeScript("mobile: shell", ppp);467                Log.info(ccc);468            }469            List<String> adb = Arrays.asList("");470            Map<String, Object> clearLogcat = ImmutableMap.of("command", "logcat -c", "args", adb);471            this.driver.executeScript("mobile: shell", clearLogcat);472//            else if (outputStream.toString().contains("error_code:#PBA")) {473//                List<String> pba = Arrays.asList("");474//                Map<String, Object> PBA = ImmutableMap.of("command", "logcat -d |grep 'error_code:#PBA'", "args", pba);475//                String pbaerror = (String) this.driver.executeScript("mobile: shell", PBA);476//                Log.info(pbaerror);477//            }478//        cmd.addArgument("shell", false).addArgument("-s", false).addArgument(ip, false).addArgument("kill", false).addArgument(outputStream.toString(), false);479//            CommandLine commandline = CommandLine.parse(command);480        } catch481        (Exception ignore) {482        }483    }484    public void deleteShlomiLogcat() {485        try {486            Files.deleteIfExists(Paths.get("C:\\Users\\OSN20933\\shlomi_crash.txt"));487        } catch (IOException e) {488        }489    }490    public void readLogcatRealTime() throws IOException {491        Process logcatread;492        final StringBuilder log = new StringBuilder();493        try {494            logcatread = Runtime.getRuntime().exec(new String[]{"logcat"});495            BufferedReader br = new BufferedReader(new InputStreamReader(logcatread.getInputStream()), 4 * 1024);496            String line;497            String separator = System.getProperty("line.separator");498            while ((line = br.readLine()) != null) {499//                log.append(line);500//                log.append(separator);501                if (line.contains("Send teardown with metrics end with status code: 204")) {502                    log.append(line.contains("Send teardown with metrics end with status code: 204"));503                    try {504                        Runtime.getRuntime().exec(new String[]{"logcat", "-c"});505                    } catch (Exception e1) {506                        e1.printStackTrace();507                    }508                }509            }510        } catch (511                Exception e) {512            e.printStackTrace();513        }514    }515    public void killifs(String ip) throws IOException {516        try {517            CommandLine cmd = new CommandLine("adb");518            CommandLine cmd1 = new CommandLine("adb");519            cmd.addArgument("-s").addArgument(ip, false).addArgument("shell", false).addArgument("\"kill $(pidof com.ifeelsmart.smartui)\"", false);520            DefaultExecutor exec = new DefaultExecutor();521            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();522            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);523            exec.setStreamHandler(streamHandler);524            exec.execute(cmd);525            Log.info("Closing ifs from the background, please wait...");526        } catch527        (Exception ignore) {528            System.out.println(ignore);529        }530    }531    public void checkDevices() throws IOException {532        try {533            CommandLine cmd = new CommandLine("adb");534            cmd.addArgument("devices", false);535            DefaultExecutor exec = new DefaultExecutor();536            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();537            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);538            exec.setStreamHandler(streamHandler);539            exec.execute(cmd);540            if (outputStream.toString().contains("192.168.1.")) {541                Log.info("At least 1 STB is connected, Starting The test ...");542            } else {543                Log.info("No STB devices connected, Aborting the tests !!! " + outputStream.toString());544                System.exit(1);545            }546        } catch547        (Exception ignore) {548            System.out.println(ignore);549        }550    }551    public void StopNodes() throws IOException {552        try {553            CommandLine stop = new CommandLine("taskkill");554            stop.addArgument("/F", false).addArgument("/IM", false).addArgument("node.exe", false);555            DefaultExecutor exec = new DefaultExecutor();556            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();557            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);558            exec.setStreamHandler(streamHandler);559            exec.execute(stop);560            Log.info(outputStream.toString());561        } catch (Exception e) {562            e.getMessage();563        }564    }565    public void killAppiumServer() {566        try {567            CommandLine killAppium = new CommandLine("netstat");568            killAppium.addArgument("-ano", false).addArgument("|", false).addArgument("find", false).addArgument("\"0.0.0.0:4723\"", false);569            DefaultExecutor exec = new DefaultExecutor();570            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();571            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);572            exec.setStreamHandler(streamHandler);573            exec.execute(killAppium);574            Log.info(outputStream.toString());575        } catch (Exception e) {576            e.getMessage();577        }578    }579    public void cmd(String port) throws IOException {580        try {581            ProcessBuilder builder = new ProcessBuilder(582                    "/bin/bash", "-c", "netstat -nlp | grep :" + port);583            builder.redirectErrorStream(true);584            Process p = builder.start();585            BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));586            String line;587            while (true) {588                line = r.readLine();589                if (line == null) {590                    break;591                }592                Log.info(line);593//                System.out.println(line.substring(71));594//                String AppiumServerPid = line.substring(61);595                String AppiumServerPid = line;596                Log.info("Killing Appium port, Wait a sec...");597                ProcessBuilder builder2 = new ProcessBuilder(598                        "/bin/bash", "-c", "taskkill /pid " + AppiumServerPid + " /f");599                builder2.redirectErrorStream(true);600                Process p2 = builder2.start();601                BufferedReader r2 = new BufferedReader(new InputStreamReader(p2.getInputStream()));602                String line2;603                while (true) {604                    line2 = r2.readLine();605                    if (line2 == null) {606                        break;607                    }608                    System.out.println(line2);609                }610            }611        } catch (Exception ignore) {612            Log.info(ignore.getMessage());613        }614    }615    public void logCatPC(String ip) {616        String dateTime = driver.getDeviceTime().replace(":", "-");617        try {618            Process process = Runtime.getRuntime().exec("adb -s " + ip + " logcat >" + dateTime.substring(0, dateTime.length() - 6).replace("T", " ") + "." + ip);619            int exitCode = process.waitFor();620            if (exitCode == 0) {621                System.out.println("Executed successfully");622            } else {623                System.out.println("Failed ...");624            }625//            String dateTime = driver.getDeviceTime().replace(":", "-");626//            ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", "adb", "-s", ip, "logcat", ">", dateTime.substring(0, dateTime.length() - 6).replace("T", " ") + "." + ip);627//            builder.start();628            Log.info("adb logcat is active, name of the Log:" + dateTime.substring(0, dateTime.length() - 6).replace("T", " ") + " For ip - " + ip);629//            long pid = p.pid();630        } catch (Exception e) {631            e.getMessage();632        }633    }634    public void getRefreashRate(String ip, String deviceName) throws IOException {635//        List<String> adb = Arrays.asList("");636//        Map<String, Object> ADB2 = ImmutableMap.of("command", "dumpsys display |grep DisplayModeRecord", "args", adb);637//        String AA = (String) driver.executeScript("mobile: shell", ADB2);638//        if (AA.length() >= 69) {639//            Log.info("The Refresh Rate is: " + AA.substring(66, AA.length() - 3));640        CommandLine cmd = new CommandLine("adb");641        cmd.addArgument("-s").addArgument(ip, false).addArgument("shell", false).addArgument("dumpsys", false).addArgument("display", false).addArgument("|", false).addArgument("grep", false).addArgument("DisplayModeRecord", false);642        DefaultExecutor exec = new DefaultExecutor();643        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();644        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);645        exec.setStreamHandler(streamHandler);646        exec.execute(cmd);647        if (outputStream.toString().length() >= 69) {648            Log.info("The Refresh Rate for " + deviceName + " is: " + outputStream.toString().substring(66, outputStream.toString().length() - 4));649        }650    }651    public void findImage() throws IOException {652//653//            File black = new File("C:\\Users\\OSN20933\\Pictures\\black_screen.png");654        File start = new File("C:\\Users\\OSN20933\\Pictures\\s.png");655        byte[] fileContent = FileUtils.readFileToByteArray(new File("C:\\Users\\OSN20933\\Pictures\\start.png"));656        String encodedString = Base64.encodeBase64String(fileContent);657//658//        byte[] screenshot = Base64.encodeBase64(driver.getScreenshotAs(OutputType.BYTES));659//        byte[] partialImage = null;660//        OccurrenceMatchingResult result = driver661//                .findImageOccurrence(screenshot, partialImage, new OccurrenceMatchingOptions()662//                        .withEnabledVisualization());663//        Assert.assertTrue(result.getVisualization().length >(0));664//        assertNotNull(result.getRect());665        boolean el = driver.findElementsByImage(encodedString).size() > 0;666        //   takeScreenShot();667//        WebDriverWait wait = new WebDriverWait(driver,20);668//        wait.until(ExpectedConditions.visibilityOfElementLocated(MobileBy.ByImage.image(encodedString)));669//        Log.info("works!!!");670//takeScreenShot();671        //*    if (el){672        //  Log.info("Exist");673        //  }674        //    else675        //  {676        //    Log.info("Not exist");677    }678    public void che() throws IOException, InterruptedException {679//       takeScreenShot();680        byte[] pngBytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);681        if (IsPngEquals(new File("C:\\Users\\OSN20933\\Pictures\\sleep_black_take.png"), pngBytes)) {682            Log.info("Black screen catched on the screen");683            keyCode keyCode = new keyCode(this.driver);684            keyCode.OK();685            takeScreenShot();686        } else {687        }688    }689    public static boolean IsPngEquals(File pngFile, byte[] pngBytes) throws IOException {690        BufferedImage imageA = ImageIO.read(pngFile);691        ByteArrayInputStream inStreamB = new ByteArrayInputStream(pngBytes);692        BufferedImage imageB = ImageIO.read(inStreamB);693        inStreamB.close();694        DataBufferByte dataBufferA = (DataBufferByte) imageA.getRaster().getDataBuffer();695        DataBufferByte dataBufferB = (DataBufferByte) imageB.getRaster().getDataBuffer();696        if (dataBufferA.getNumBanks() != dataBufferB.getNumBanks()) {697            return false;698        }699        for (int bank = 0; bank < dataBufferA.getNumBanks(); bank++) {700            if (!Arrays.equals(dataBufferA.getData(bank), dataBufferB.getData(bank))) {701                return false;702            }703        }704        return true;705    }706    public void KillAppium(String port) throws IOException {707//        String terminalCommand2 = "netstat -nlp | grep :4728" + port;708        String[] args = new String[]{"/bin/bash", "-c", "netstat -nlp | grep :4728", port};709        ProcessBuilder pb = new ProcessBuilder(args);710        String output = IOUtils.toString(pb.start().getInputStream()).substring(80).replace("/node", "");711//        String b = output.substring(80).replace("/node","netstat -nlp | grep :" + port);712        Log.info(output);713        String[] args2 = new String[]{"/bin/bash", "-c", "kill ", output};714        Process proc = new ProcessBuilder(args2).start();715    }716    public void logCatLinux(String ip) throws IOException, InterruptedException {717        List<LogEntry> logEntries = driver.manage().logs().get("logcat").getAll();718        for (LogEntry logEntry : logEntries) {719            if (logEntry.toString().contains("DRM")){720            System.out.println(logEntry);721                List<String> adb10 = Arrays.asList("");722                Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);723                this.driver.executeScript("mobile: shell", clearLogcat2);724                Thread.sleep(60000);725        }726            driver.pressKey(new KeyEvent(AndroidKey.CHANNEL_UP));727            Log.info("--- Zapping up ---");728            Thread.sleep(4000);729        }730    }731    public void pause(String ip) throws IOException {732       // String[] args = new String[]{"/bin/bash", "-c", "adb -s " + ip + " logcat | grep 'Player is buffering'"};733    }734    public void pa(String ip) throws IOException {735        String s = null;736        try {737            // run the Unix "ps -ef" command738            // using the Runtime exec method:739//            Process c = Runtime.getRuntime().exec("adb -s " + ip + " logcat -c");740            Process p = Runtime.getRuntime().exec("adb -s " + ip + "logcat");741            BufferedReader stdInput = new BufferedReader(new742                    InputStreamReader(p.getInputStream()));743            BufferedReader stdError = new BufferedReader(new744                    InputStreamReader(p.getErrorStream()));745            // read the output from the command746            while ((s = stdInput.readLine()) != null) {747                    if (s.contains("DRM")){748                        takeScreenShot();749                        Log.info("DRM ERROR" +s);750                        SendEmail.sendmail("DRM ERROR " + s,"eyal.avramchik@partner.co.il","DRM ERROR");751                        Thread.sleep(60000);752                        List<String> adb10 = Arrays.asList("");753                        Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);754                        this.driver.executeScript("mobile: shell", clearLogcat2);755                }756//                    else if (s.contains("error_code:#PBA")){757//                        takeScreenShot();758//                        Log.info("PBA ERROR");759//                        SendEmail.sendmail("PBA ERROR","eyal.avramchik@partner.co.il","PBA ERROR");760//                        Thread.sleep(60000);761//                    }762//                if (s.contains("Player is buffering")) {763//                    Log.info(" **********  YOU ARE IN A LIVE CHANNEL  **********");764//                } else if (s.contains("Player is paused")) {765//                    Log.info(" **********  YOU ARE IN A PAUSE MODE  **********");766//                } else if (s.contains("Player is resumed")) {767//                    Log.info(" **********  YOU ARE IN RESUME MODE/PLAY MODE  **********");768//                } else if (s.contains("keycode=89")) {769//                    Log.info(" **********  REWIND  **********");770//                } else if (s.contains("keycode=90")) {771//                    Log.info(" **********  FAST FORWARD  **********");772//                }773                driver.pressKey(new KeyEvent(AndroidKey.CHANNEL_UP));774                Log.info("--- Zapping up ---");775                Thread.sleep(3000);776            }777            // read any errors from the attempted command778//            System.out.println("Here is the standard error of the command (if any):\n");779//            while ((s = stdError.readLine()) != null) {780//                System.out.println(s);781//            }782//            System.exit(0);783        } catch (IOException | InterruptedException e) {784            System.out.println("exception happened - here's what I know: ");785            e.printStackTrace();786            System.exit(-1);787        }788    }789    public void memoryTest(String ip,String deviceName) throws IOException {790        String n = null;791        try {792            // run the Unix "ps -ef" command793            // using the Runtime exec method:794            Process c = Runtime.getRuntime().exec("adb -s " + ip + " logcat -c");795            Process p = Runtime.getRuntime().exec("adb -s " + ip + " shell top -n 1 | grep 'System'");796            BufferedReader stdInput = new BufferedReader(new797                    InputStreamReader(p.getInputStream()));798            BufferedReader stdError = new BufferedReader(new799                    InputStreamReader(p.getErrorStream()));800            // read the output from the command801            while ((n = stdInput.readLine()) != null) {802                String[] splited = n.split("\\s+");803                String sum = splited[1];804//                Integer.parseInt(sum.substring(0,2));805//               if (!splited[5].contains("0%")) {806                Log.info(sum);807//                    Log.info("Total Cpu Usage is:  " + splited[5] + "   and the STB IP is: "+ ip + " and the STB name is: " + deviceName);808                }809//            }810//                } else if (n.contains("Player is paused")) {811//                    Log.info(" **********  YOU ARE IN A PAUSE MODE  **********");812//813//                }814            // read any errors from the attempted command815//            System.out.println("Here is the standard error of the command (if any):\n");816//            while ((s = stdError.readLine()) != null) {817//                System.out.println(s);818//            }819//            System.exit(0);820        } catch (IOException e) {821            System.out.println("exception happened - here's what I know: ");822            e.printStackTrace();823            System.exit(-1);824        }825    }826    public void DRM(String ip) {827        ProcessBuilder processBuilder = new ProcessBuilder();//DRM828        processBuilder.command("bash", "-c", "adb -s " + ip + " logcat -d | grep DRM");829        try {830            driver.pressKey(new KeyEvent(AndroidKey.CHANNEL_UP));831            Log.info("--- Zapping up ---");832            Thread.sleep(4000);833            Process process = processBuilder.start();834            StringBuilder output = new StringBuilder();835            BufferedReader reader = new BufferedReader(836                    new InputStreamReader(process.getInputStream()));837            String line;838            while ((line = reader.readLine()) != null) {839             System.out.println(output.append(line));840                takeScreenShot();841                Log.info("First screenshot of the DRM error");842                SendEmail.sendmail(output.toString(),"eyal.avramchik@partner.co.il","DRM Error cacthed");843                List<String> adb10 = Arrays.asList("");844                Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);845                this.driver.executeScript("mobile: shell", clearLogcat2);846            }847            int exitVal = process.waitFor();848            if (exitVal == 0) {849                System.out.println("Success!");850//                System.out.println(output);851//                System.exit(0);852            } else {853                //abnormal...854            }855        } catch (IOException e) {856            e.printStackTrace();857        } catch (InterruptedException e) {858            e.printStackTrace();859        }860    }861    public void pbaError(String ip) {862        ProcessBuilder processBuilder = new ProcessBuilder();//PBA863        processBuilder.command("bash", "-c", "adb -s " + ip + " logcat -d | grep error_code:#PBA");864        try {865            Process process = processBuilder.start();866            StringBuilder output = new StringBuilder();867            BufferedReader reader = new BufferedReader(868                    new InputStreamReader(process.getInputStream()));869            String line;870            while ((line = reader.readLine()) != null) {871                System.out.println(output.append(line));872                takeScreenShot();873                Log.info("First screenshot of PBA error before the 60 seconds");874                SendEmail.sendmail(output.toString(),"eyal.avramchik@partner.co.il","PBA Error cacthed");875                List<String> adb10 = Arrays.asList("");876                Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);877                this.driver.executeScript("mobile: shell", clearLogcat2);878            }879            int exitVal = process.waitFor();880            if (exitVal == 0) {881                System.out.println("Success!");882//                System.out.println(output);883//                System.exit(0);884            } else {885                //abnormal...886            }887        } catch (IOException e) {888            e.printStackTrace();889        } catch (InterruptedException e) {890            e.printStackTrace();891        }892    }893    public void decodingError(String ip) {894        ProcessBuilder processBuilder = new ProcessBuilder();//PBA895        processBuilder.command("bash", "-c", "adb -s " + ip + " logcat -d | grep teardown/3002");896        try {897            Process process = processBuilder.start();898            StringBuilder output = new StringBuilder();899            BufferedReader reader = new BufferedReader(900                    new InputStreamReader(process.getInputStream()));901            String line;902            while ((line = reader.readLine()) != null) {903                System.out.println(output.append(line));904                takeScreenShot();905                Log.info("First screenshot of the Decoding error");906                SendEmail.sendmail(output.toString(),"eyal.avramchik@partner.co.il","Decoding Error cacthed");907                List<String> adb10 = Arrays.asList("");908                Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);909                this.driver.executeScript("mobile: shell", clearLogcat2);910            }911            int exitVal = process.waitFor();912            if (exitVal == 0) {913                System.out.println("Success!");914//                System.out.println(output);915//                System.exit(0);916            } else {917                //abnormal...918            }919        } catch (IOException e) {920            e.printStackTrace();...MobileBy.java
Source:MobileBy.java  
...43    }44    @SuppressWarnings("unchecked")45    @Override public List<WebElement> findElements(SearchContext context) {46        return (List<WebElement>) ((FindsByFluentSelector<?>) context)47                .findElements(selector.toString(), getLocatorString());48    }49    @Override public WebElement findElement(SearchContext context) {50        return ((FindsByFluentSelector<?>) context)51                .findElement(selector.toString(), getLocatorString());52    }53    /**54     * Refer to https://developer.android.com/training/testing/ui-automator55     * @param uiautomatorText is Android UIAutomator string56     * @return an instance of {@link io.appium.java_client.MobileBy.ByAndroidUIAutomator}57     */58    public static By AndroidUIAutomator(final String uiautomatorText) {59        return new ByAndroidUIAutomator(uiautomatorText);60    }61    /**62     * About Android accessibility63     * https://developer.android.com/intl/ru/training/accessibility/accessible-app.html64     * About iOS accessibility65     * https://developer.apple.com/library/ios/documentation/UIKit/Reference/66     * UIAccessibilityIdentification_Protocol/index.html67     * @param accessibilityId id is a convenient UI automation accessibility Id.68     * @return an instance of {@link io.appium.java_client.MobileBy.ByAndroidUIAutomator}69     */70    public static By AccessibilityId(final String accessibilityId) {71        return new ByAccessibilityId(accessibilityId);72    }73    /**74     * This locator strategy is available in XCUITest Driver mode.75     * @param iOSClassChainString is a valid class chain locator string.76     *                            See <a href="https://github.com/facebookarchive/WebDriverAgent/wiki/Class-Chain-Queries-Construction-Rules">77     *                            the documentation</a> for more details78     * @return an instance of {@link io.appium.java_client.MobileBy.ByIosClassChain}79     */80    public static By iOSClassChain(final String iOSClassChainString) {81        return new ByIosClassChain(iOSClassChainString);82    }83    /**84     * This locator strategy is only available in Espresso Driver mode.85     * @param dataMatcherString is a valid json string detailing hamcrest matcher for Espresso onData().86     *                            See <a href="http://appium.io/docs/en/writing-running-appium/android/espresso-datamatcher-selector/">87     *                            the documentation</a> for more details88     * @return an instance of {@link io.appium.java_client.MobileBy.ByAndroidDataMatcher}89     */90    public static By androidDataMatcher(final String dataMatcherString) {91        return new ByAndroidDataMatcher(dataMatcherString);92    }93    /**94     * This locator strategy is only available in Espresso Driver mode.95     * @param viewMatcherString is a valid json string detailing hamcrest matcher for Espresso onView().96     *                            See <a href="http://appium.io/docs/en/writing-running-appium/android/espresso-datamatcher-selector/">97     *                            the documentation</a> for more details98     * @return an instance of {@link io.appium.java_client.MobileBy.ByAndroidViewMatcher}99     */100    public static By androidViewMatcher(final String viewMatcherString) {101        return new ByAndroidViewMatcher(viewMatcherString);102    }103    /**104    * This locator strategy is available in XCUITest Driver mode.105    * @param iOSNsPredicateString is an an iOS NsPredicate String106    * @return an instance of {@link io.appium.java_client.MobileBy.ByIosNsPredicate}107    */108    public static By iOSNsPredicateString(final String iOSNsPredicateString) {109        return new ByIosNsPredicate(iOSNsPredicateString);110    }111    public static By windowsAutomation(final String windowsAutomation) {112        return new ByWindowsAutomation(windowsAutomation);113    }114    /**115     * This locator strategy is available in Espresso Driver mode.116     * @since Appium 1.8.2 beta117     * @param tag is an view tag string118     * @return an instance of {@link ByAndroidViewTag}119     */120    public static By AndroidViewTag(final String tag) {121        return new ByAndroidViewTag(tag);122    }123    /**124     * This locator strategy is available only if OpenCV libraries and125     * NodeJS bindings are installed on the server machine.126     *127     * @see <a href="https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/image-comparison.md">128     * The documentation on Image Comparison Features</a>129     * @see <a href="https://github.com/appium/appium-base-driver/blob/master/lib/basedriver/device-settings.js">130     * The settings available for lookup fine-tuning</a>131     * @since Appium 1.8.2132     * @param b64Template base64-encoded template image string. Supported image formats are the same133     *                    as for OpenCV library.134     * @return an instance of {@link ByImage}135     */136    public static By image(final String b64Template) {137        return new ByImage(b64Template);138    }139    /**140     * This type of locator requires the use of the 'customFindModules' capability and a141     * separately-installed element finding plugin.142     *143     * @param selector selector to pass to the custom element finding plugin144     * @return an instance of {@link ByCustom}145     * @since Appium 1.9.2146     */147    public static By custom(final String selector) {148        return new ByCustom(selector);149    }150    public static class ByAndroidUIAutomator extends MobileBy implements Serializable {151        public ByAndroidUIAutomator(String uiautomatorText) {152            super(MobileSelector.ANDROID_UI_AUTOMATOR, uiautomatorText);153        }154        /**155         * {@inheritDoc}156         *157         * @throws WebDriverException when current session doesn't support the given selector or when158         *      value of the selector is not consistent.159         * @throws IllegalArgumentException when it is impossible to find something on the given160         * {@link SearchContext} instance161         */162        @SuppressWarnings("unchecked")163        @Override164        public List<WebElement> findElements(SearchContext context) throws WebDriverException,165            IllegalArgumentException {166            Class<?> contextClass = context.getClass();167            if (FindsByAndroidUIAutomator.class.isAssignableFrom(contextClass)) {168                return FindsByAndroidUIAutomator.class.cast(context)169                    .findElementsByAndroidUIAutomator(getLocatorString());170            }171            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {172                return super.findElements(context);173            }174            throw formIllegalArgumentException(contextClass, FindsByAndroidUIAutomator.class,175                FindsByFluentSelector.class);176        }177        /**178         * {@inheritDoc}179         *180         * @throws WebDriverException when current session doesn't support the given selector or when181         *      value of the selector is not consistent.182         * @throws IllegalArgumentException when it is impossible to find something on the given183         * {@link SearchContext} instance184         */185        @Override public WebElement findElement(SearchContext context) throws WebDriverException,186            IllegalArgumentException {187            Class<?> contextClass = context.getClass();188            if (FindsByAndroidUIAutomator.class.isAssignableFrom(contextClass)) {189                return FindsByAndroidUIAutomator.class.cast(context)190                    .findElementByAndroidUIAutomator(getLocatorString());191            }192            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {193                return super.findElement(context);194            }195            throw formIllegalArgumentException(contextClass, FindsByAndroidUIAutomator.class,196                FindsByFluentSelector.class);197        }198        @Override public String toString() {199            return "By.AndroidUIAutomator: " + getLocatorString();200        }201    }202    public static class ByAccessibilityId extends MobileBy implements Serializable {203        public ByAccessibilityId(String accessibilityId) {204            super(MobileSelector.ACCESSIBILITY, accessibilityId);205        }206        /**207         * {@inheritDoc}208         *209         * @throws WebDriverException when current session doesn't support the given selector or when210         *      value of the selector is not consistent.211         * @throws IllegalArgumentException when it is impossible to find something on the given212         * {@link SearchContext} instance213         */214        @SuppressWarnings("unchecked")215        @Override216        public List<WebElement> findElements(SearchContext context) throws WebDriverException,217            IllegalArgumentException {218            Class<?> contextClass = context.getClass();219            if (FindsByAccessibilityId.class.isAssignableFrom(contextClass)) {220                return FindsByAccessibilityId.class.cast(context)221                    .findElementsByAccessibilityId(getLocatorString());222            }223            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {224                return super.findElements(context);225            }226            throw formIllegalArgumentException(contextClass, FindsByAccessibilityId.class,227                FindsByFluentSelector.class);228        }229        /**230         * {@inheritDoc}231         *232         * @throws WebDriverException when current session doesn't support the given selector or when233         *      value of the selector is not consistent.234         * @throws IllegalArgumentException when it is impossible to find something on the given235         * {@link SearchContext} instance236         */237        @Override public WebElement findElement(SearchContext context) throws WebDriverException,238            IllegalArgumentException {239            Class<?> contextClass = context.getClass();240            if (FindsByAccessibilityId.class.isAssignableFrom(contextClass)) {241                return FindsByAccessibilityId.class.cast(context)242                    .findElementByAccessibilityId(getLocatorString());243            }244            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {245                return super.findElement(context);246            }247            throw formIllegalArgumentException(contextClass, FindsByAccessibilityId.class,248                FindsByFluentSelector.class);249        }250        @Override public String toString() {251            return "By.AccessibilityId: " + getLocatorString();252        }253    }254    public static class ByIosClassChain extends MobileBy implements Serializable {255        protected ByIosClassChain(String locatorString) {256            super(MobileSelector.IOS_CLASS_CHAIN, locatorString);257        }258        /**259         * {@inheritDoc}260         *261         * @throws WebDriverException when current session doesn't support the given selector or when262         *      value of the selector is not consistent.263         * @throws IllegalArgumentException when it is impossible to find something on the given264         * {@link SearchContext} instance265         */266        @SuppressWarnings("unchecked")267        @Override public List<WebElement> findElements(SearchContext context) {268            Class<?> contextClass = context.getClass();269            if (FindsByIosClassChain.class.isAssignableFrom(contextClass)) {270                return FindsByIosClassChain.class.cast(context)271                        .findElementsByIosClassChain(getLocatorString());272            }273            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {274                return super.findElements(context);275            }276            throw formIllegalArgumentException(contextClass, FindsByIosClassChain.class,277                    FindsByFluentSelector.class);278        }279        /**280         * {@inheritDoc}281         *282         * @throws WebDriverException when current session doesn't support the given selector or when283         *      value of the selector is not consistent.284         * @throws IllegalArgumentException when it is impossible to find something on the given285         * {@link SearchContext} instance286         */287        @Override public WebElement findElement(SearchContext context) {288            Class<?> contextClass = context.getClass();289            if (FindsByIosClassChain.class.isAssignableFrom(contextClass)) {290                return FindsByIosClassChain.class.cast(context)291                        .findElementByIosClassChain(getLocatorString());292            }293            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {294                return super.findElement(context);295            }296            throw formIllegalArgumentException(contextClass, FindsByIosClassChain.class,297                    FindsByFluentSelector.class);298        }299        @Override public String toString() {300            return "By.IosClassChain: " + getLocatorString();301        }302    }303    public static class ByAndroidDataMatcher extends MobileBy implements Serializable {304        protected ByAndroidDataMatcher(String locatorString) {305            super(MobileSelector.ANDROID_DATA_MATCHER, locatorString);306        }307        /**308         * {@inheritDoc}309         *310         * @throws WebDriverException when current session doesn't support the given selector or when311         *      value of the selector is not consistent.312         * @throws IllegalArgumentException when it is impossible to find something on the given313         * {@link SearchContext} instance314         */315        @SuppressWarnings("unchecked")316        @Override public List<WebElement> findElements(SearchContext context) {317            Class<?> contextClass = context.getClass();318            if (FindsByAndroidDataMatcher.class.isAssignableFrom(contextClass)) {319                return FindsByAndroidDataMatcher.class.cast(context)320                        .findElementsByAndroidDataMatcher(getLocatorString());321            }322            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {323                return super.findElements(context);324            }325            throw formIllegalArgumentException(contextClass, FindsByAndroidDataMatcher.class,326                    FindsByFluentSelector.class);327        }328        /**329         * {@inheritDoc}330         *331         * @throws WebDriverException when current session doesn't support the given selector or when332         *      value of the selector is not consistent.333         * @throws IllegalArgumentException when it is impossible to find something on the given334         * {@link SearchContext} instance335         */336        @Override public WebElement findElement(SearchContext context) {337            Class<?> contextClass = context.getClass();338            if (FindsByAndroidDataMatcher.class.isAssignableFrom(contextClass)) {339                return FindsByAndroidDataMatcher.class.cast(context)340                        .findElementByAndroidDataMatcher(getLocatorString());341            }342            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {343                return super.findElement(context);344            }345            throw formIllegalArgumentException(contextClass, FindsByAndroidDataMatcher.class,346                    FindsByFluentSelector.class);347        }348        @Override public String toString() {349            return "By.FindsByAndroidDataMatcher: " + getLocatorString();350        }351    }352    public static class ByAndroidViewMatcher extends MobileBy implements Serializable {353        protected ByAndroidViewMatcher(String locatorString) {354            super(MobileSelector.ANDROID_VIEW_MATCHER, locatorString);355        }356        /**357         * {@inheritDoc}358         *359         * @throws WebDriverException when current session doesn't support the given selector or when360         *      value of the selector is not consistent.361         * @throws IllegalArgumentException when it is impossible to find something on the given362         * {@link SearchContext} instance363         */364        @SuppressWarnings("unchecked")365        @Override public List<WebElement> findElements(SearchContext context) {366            Class<?> contextClass = context.getClass();367            if (FindsByAndroidViewMatcher.class.isAssignableFrom(contextClass)) {368                return FindsByAndroidViewMatcher.class.cast(context)369                    .findElementsByAndroidViewMatcher(getLocatorString());370            }371            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {372                return super.findElements(context);373            }374            throw formIllegalArgumentException(contextClass, FindsByAndroidViewMatcher.class,375                FindsByFluentSelector.class);376        }377        /**378         * {@inheritDoc}379         *380         * @throws WebDriverException when current session doesn't support the given selector or when381         *      value of the selector is not consistent.382         * @throws IllegalArgumentException when it is impossible to find something on the given383         * {@link SearchContext} instance384         */385        @Override public WebElement findElement(SearchContext context) {386            Class<?> contextClass = context.getClass();387            if (FindsByAndroidViewMatcher.class.isAssignableFrom(contextClass)) {388                return FindsByAndroidViewMatcher.class.cast(context)389                    .findElementByAndroidViewMatcher(getLocatorString());390            }391            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {392                return super.findElement(context);393            }394            throw formIllegalArgumentException(contextClass, FindsByAndroidViewMatcher.class,395                FindsByFluentSelector.class);396        }397        @Override public String toString() {398            return "By.FindsByAndroidViewMatcher: " + getLocatorString();399        }400    }401    public static class ByIosNsPredicate extends MobileBy implements Serializable {402        protected ByIosNsPredicate(String locatorString) {403            super(MobileSelector.IOS_PREDICATE_STRING, locatorString);404        }405        /**406         * {@inheritDoc}407         *408         * @throws WebDriverException when current session doesn't support the given selector or when409         *      value of the selector is not consistent.410         * @throws IllegalArgumentException when it is impossible to find something on the given411         * {@link SearchContext} instance412         */413        @SuppressWarnings("unchecked")414        @Override public List<WebElement> findElements(SearchContext context) {415            Class<?> contextClass = context.getClass();416            if (FindsByIosNSPredicate.class.isAssignableFrom(contextClass)) {417                return FindsByIosNSPredicate.class.cast(context)418                        .findElementsByIosNsPredicate(getLocatorString());419            }420            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {421                return super.findElements(context);422            }423            throw formIllegalArgumentException(contextClass, FindsByIosNSPredicate.class,424                    FindsByFluentSelector.class);425        }426        /**427         * {@inheritDoc}428         *429         * @throws WebDriverException when current session doesn't support the given selector or when430         *      value of the selector is not consistent.431         * @throws IllegalArgumentException when it is impossible to find something on the given432         * {@link SearchContext} instance433         */434        @Override public WebElement findElement(SearchContext context) {435            Class<?> contextClass = context.getClass();436            if (FindsByIosNSPredicate.class.isAssignableFrom(contextClass)) {437                return FindsByIosNSPredicate.class.cast(context)438                        .findElementByIosNsPredicate(getLocatorString());439            }440            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {441                return super.findElement(context);442            }443            throw formIllegalArgumentException(contextClass, FindsByIosNSPredicate.class,444                    FindsByFluentSelector.class);445        }446        @Override public String toString() {447            return "By.IosNsPredicate: " + getLocatorString();448        }449    }450    public static class ByWindowsAutomation extends MobileBy implements Serializable {451        protected ByWindowsAutomation(String locatorString) {452            super(MobileSelector.WINDOWS_UI_AUTOMATION, locatorString);453        }454        /**455         * {@inheritDoc}456         *457         * @throws WebDriverException when current session doesn't support the given selector or when458         *      value of the selector is not consistent.459         * @throws IllegalArgumentException when it is impossible to find something on the given460         * {@link SearchContext} instance461         */462        @SuppressWarnings("unchecked")463        @Override public List<WebElement> findElements(SearchContext context) {464            Class<?> contextClass = context.getClass();465            if (FindsByWindowsAutomation.class.isAssignableFrom(contextClass)) {466                return FindsByWindowsAutomation.class.cast(context)467                    .findElementsByWindowsUIAutomation(getLocatorString());468            }469            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {470                return super.findElements(context);471            }472            throw formIllegalArgumentException(contextClass, FindsByWindowsAutomation.class,473                FindsByFluentSelector.class);474        }475        /**476         * {@inheritDoc}477         *478         * @throws WebDriverException when current session doesn't support the given selector or when479         *      value of the selector is not consistent.480         * @throws IllegalArgumentException when it is impossible to find something on the given481         * {@link SearchContext} instance482         */483        @Override public WebElement findElement(SearchContext context) {484            Class<?> contextClass = context.getClass();485            if (FindsByWindowsAutomation.class.isAssignableFrom(contextClass)) {486                return FindsByWindowsAutomation.class.cast(context)487                    .findElementByWindowsUIAutomation(getLocatorString());488            }489            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {490                return super.findElement(context);491            }492            throw formIllegalArgumentException(contextClass, FindsByIosNSPredicate.class,493                FindsByWindowsAutomation.class);494        }495    }496    public static class ByImage extends MobileBy implements Serializable {497        protected ByImage(String b64Template) {498            super(MobileSelector.IMAGE, b64Template);499        }500        /**501         * {@inheritDoc}502         *503         * @throws WebDriverException when current session doesn't support the given selector or when504         *      value of the selector is not consistent.505         * @throws IllegalArgumentException when it is impossible to find something on the given506         * {@link SearchContext} instance507         */508        @SuppressWarnings("unchecked")509        @Override public List<WebElement> findElements(SearchContext context) {510            Class<?> contextClass = context.getClass();511            if (FindsByImage.class.isAssignableFrom(contextClass)) {512                return FindsByImage.class.cast(context).findElementsByImage(getLocatorString());513            }514            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {515                return super.findElements(context);516            }517            throw formIllegalArgumentException(contextClass, FindsByImage.class, FindsByFluentSelector.class);518        }519        /**520         * {@inheritDoc}521         *522         * @throws WebDriverException when current session doesn't support the given selector or when523         *      value of the selector is not consistent.524         * @throws IllegalArgumentException when it is impossible to find something on the given525         * {@link SearchContext} instance526         */527        @Override public WebElement findElement(SearchContext context) {528            Class<?> contextClass = context.getClass();529            if (FindsByImage.class.isAssignableFrom(contextClass)) {530                return FindsByImage.class.cast(context).findElementByImage(getLocatorString());531            }532            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {533                return super.findElement(context);534            }535            throw formIllegalArgumentException(contextClass, FindsByImage.class, FindsByFluentSelector.class);536        }537        @Override public String toString() {538            return "By.Image: " + getLocatorString();539        }540    }541    public static class ByCustom extends MobileBy implements Serializable {542        protected ByCustom(String selector) {543            super(MobileSelector.CUSTOM, selector);544        }545        /**546         * {@inheritDoc}547         *548         * @throws WebDriverException when current session doesn't support the given selector or when549         *      value of the selector is not consistent.550         * @throws IllegalArgumentException when it is impossible to find something on the given551         * {@link SearchContext} instance552         */553        @SuppressWarnings("unchecked")554        @Override public List<WebElement> findElements(SearchContext context) {555            Class<?> contextClass = context.getClass();556            if (FindsByCustom.class.isAssignableFrom(contextClass)) {557                return FindsByCustom.class.cast(context).findElementsByCustom(getLocatorString());558            }559            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {560                return super.findElements(context);561            }562            throw formIllegalArgumentException(contextClass, FindsByCustom.class, FindsByFluentSelector.class);563        }564        /**565         * {@inheritDoc}566         *567         * @throws WebDriverException when current session doesn't support the given selector or when568         *      value of the selector is not consistent.569         * @throws IllegalArgumentException when it is impossible to find something on the given570         * {@link SearchContext} instance571         */572        @Override public WebElement findElement(SearchContext context) {573            Class<?> contextClass = context.getClass();574            if (FindsByCustom.class.isAssignableFrom(contextClass)) {575                return FindsByCustom.class.cast(context).findElementByCustom(getLocatorString());576            }577            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {578                return super.findElement(context);579            }580            throw formIllegalArgumentException(contextClass, FindsByCustom.class, FindsByFluentSelector.class);581        }582        @Override public String toString() {583            return "By.Custom: " + getLocatorString();584        }585    }586    public static class ByAndroidViewTag extends MobileBy implements Serializable {587        public ByAndroidViewTag(String tag) {588            super(MobileSelector.ANDROID_VIEWTAG, tag);589        }590        /**591         * {@inheritDoc}592         *593         * @throws WebDriverException when current session doesn't support the given selector or when594         *      value of the selector is not consistent.595         * @throws IllegalArgumentException when it is impossible to find something on the given596         * {@link SearchContext} instance597         */598        @SuppressWarnings("unchecked")599        @Override600        public List<WebElement> findElements(SearchContext context) throws WebDriverException,601                IllegalArgumentException {602            Class<?> contextClass = context.getClass();603            if (FindsByAndroidViewTag.class.isAssignableFrom(contextClass)) {604                return FindsByAndroidViewTag.class.cast(context)605                        .findElementsByAndroidViewTag(getLocatorString());606            }607            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {608                return super.findElements(context);609            }610            throw formIllegalArgumentException(contextClass, FindsByAndroidViewTag.class,611                    FindsByFluentSelector.class);612        }613        /**614         * {@inheritDoc}615         *616         * @throws WebDriverException when current session doesn't support the given selector or when617         *      value of the selector is not consistent.618         * @throws IllegalArgumentException when it is impossible to find something on the given619         * {@link SearchContext} instance620         */621        @Override public WebElement findElement(SearchContext context) throws WebDriverException,622                IllegalArgumentException {623            Class<?> contextClass = context.getClass();624            if (FindsByAndroidViewTag.class.isAssignableFrom(contextClass)) {625                return FindsByAndroidViewTag.class.cast(context)626                        .findElementByAndroidViewTag(getLocatorString());627            }628            if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {629                return super.findElement(context);630            }631            throw formIllegalArgumentException(contextClass, FindsByAndroidViewTag.class,632                    FindsByFluentSelector.class);633        }634        @Override public String toString() {635            return "By.AndroidViewTag: " + getLocatorString();636        }637    }638}...toString
Using AI Code Generation
1MobileBy.ByImage byImage = new MobileBy.ByImage("path/to/image");2System.out.println(byImage.toString());3MobileBy.ByIosUIAutomation byIosUIAutomation = new MobileBy.ByIosUIAutomation("predicate string");4System.out.println(byIosUIAutomation.toString());5MobileBy.ByIosNsPredicate byIosNsPredicate = new MobileBy.ByIosNsPredicate("predicate string");6System.out.println(byIosNsPredicate.toString());7MobileBy.ByIosClassChain byIosClassChain = new MobileBy.ByIosClassChain("predicate string");8System.out.println(byIosClassChain.toString());9MobileBy.ByAndroidUIAutomator byAndroidUIAutomator = new MobileBy.ByAndroidUIAutomator("predicate string");10System.out.println(byAndroidUIAutomator.toString());11MobileBy.ByAndroidViewTag byAndroidViewTag = new MobileBy.ByAndroidViewTag("predicate string");12System.out.println(byAndroidViewTag.toString());13MobileBy.ByAndroidDataMatcher byAndroidDataMatcher = new MobileBy.ByAndroidDataMatcher("predicate string");14System.out.println(byAndroidDataMatcher.toString());15MobileBy.ByAndroidViewMatcher byAndroidViewMatcher = new MobileBy.ByAndroidViewMatcher("predicate string");16System.out.println(byAndroidViewMatcher.toString());17MobileBy.ByAccessibilityId byAccessibilityId = new MobileBy.ByAccessibilityId("predicate string");18System.out.println(byAccessibilityId.toString());19MobileBy.ByAndroidUIAutomator byAndroidUIAutomator = new MobileBy.ByAndroidUIAutomator("predicate string");20System.out.println(byAndroidtoString
Using AI Code Generation
1MobileBy.ByImage byImage = new MobileBy.ByImage(new File("path/to/image.png"));2System.out.println(byImage.toString());3MobileBy.ByIosUIAutomation byIosUIAutomation = new MobileBy.ByIosUIAutomation("predicateString");4System.out.println(byIosUIAutomation.toString());5MobileBy.ByIosNsPredicate byIosNsPredicate = new MobileBy.ByIosNsPredicate("predicateString");6System.out.println(byIosNsPredicate.toString());7MobileBy.ByAccessibilityId byAccessibilityId = new MobileBy.ByAccessibilityId("accessibilityId");8System.out.println(byAccessibilityId.toString());9MobileBy.ByAndroidUIAutomator byAndroidUIAutomator = new MobileBy.ByAndroidUIAutomator("uiSelectorString");10System.out.println(byAndroidUIAutomator.toString());11MobileBy.ByAndroidDataMatcher byAndroidDataMatcher = new MobileBy.ByAndroidDataMatcher("dataMatcherString");12System.out.println(byAndroidDataMatcher.toString());13MobileBy.ByAndroidViewTag byAndroidViewTag = new MobileBy.ByAndroidViewTag("viewTag");14System.out.println(byAndroidViewTag.toString());15MobileBy.ByAndroidViewMatcher byAndroidViewMatcher = new MobileBy.ByAndroidViewMatcher("viewMatcherString");16System.out.println(byAndroidViewMatcher.toString());17MobileBy.ByAndroidClass byAndroidClass = new MobileBy.ByAndroidClass("className");18System.out.println(byAndroidClass.toString());19MobileBy.ByAndroidText byAndroidText = new MobileBy.ByAndroidText("text");20System.out.println(byAndroidText.toString());toString
Using AI Code Generation
1import io.appium.java_client.MobileBy.ByImage;2ByImage byImage = new ByImage("image.png");3System.out.println(byImage.toString());4import io.appium.java_client.MobileBy.ByIosUIAutomation;5ByIosUIAutomation byIosUIAutomation = new ByIosUIAutomation(".elements().withName(\"name\")");6System.out.println(byIosUIAutomation.toString());7import io.appium.java_client.MobileBy.ByIosNsPredicate;8ByIosNsPredicate byIosNsPredicate = new ByIosNsPredicate("name == \"name\"");9System.out.println(byIosNsPredicate.toString());10import io.appium.java_client.MobileBy.ByIosClassChain;toString
Using AI Code Generation
1By by = MobileBy.ByImage.toString();2System.out.println(by);3By by = MobileBy.ByImage.toString("image.png");4System.out.println(by);5By by = MobileBy.ByImage.toString("image.png", 0.9);6System.out.println(by);7By by = MobileBy.ByImage.toString("image.png", 0.9, "image.png");8System.out.println(by);9By by = MobileBy.ByImage.toString("image.png", 0.9, "image.png", 0.9);10System.out.println(by);11By by = MobileBy.ByImage.toString("image.png", 0.9, "image.png", 0.9, "image.png");12System.out.println(by);13By by = MobileBy.ByImage.toString("image.png", 0.9, "image.png", 0.9, "image.png", 0.9);14System.out.println(by);15By by = MobileBy.ByImage.toString("image.png", 0.9, "image.png", 0.9, "image.png", 0.9, "image.png");16System.out.println(by);17By by = MobileBy.ByImage.toString("image.png", 0.9, "image.png", 0.9, "image.png", 0.9, "image.png", 0.9);18System.out.println(by);toString
Using AI Code Generation
1MobileBy.ByImage byImage = new MobileBy.ByImage("path/to/image.png");2System.out.println(byImage.toString());3MobileBy.ByIosClassChain byIosClassChain = new MobileBy.ByIosClassChain("**/XCUIElementTypeWindow[`name == 'Alerts'`]");4System.out.println(byIosClassChain.toString());5MobileBy.ByIosNsPredicate byIosNsPredicate = new MobileBy.ByIosNsPredicate("name == 'Alerts'");6System.out.println(byIosNsPredicate.toString());toString
Using AI Code Generation
1String str = new MobileBy.ByImage("C:\\Users\\admin\\Desktop\\appium.png").toString();2System.out.println(str);3String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();4System.out.println(str);5String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();6System.out.println(str);7String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();8System.out.println(str);9String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();10System.out.println(str);11String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();12System.out.println(str);13String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();14System.out.println(str);15String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();16System.out.println(str);17String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();18System.out.println(str);toString
Using AI Code Generation
1ByImage byImage = new ByImage();2byImage.setImagePath("C:\\Users\\user\\Desktop\\testimage.png");3byImage.setMinScore(0.7);4System.out.println(byImage.toString());5ByImage byImage = new ByImage("C:\\Users\\user\\Desktop\\testimage.png");6byImage.setMinScore(0.7);7System.out.println(byImage.toString());8ByImage byImage = new ByImage("C:\\Users\\user\\Desktop\\testimage.png", 0.7);9System.out.println(byImage.toString());10ByImage byImage = new ByImage();11byImage.setImagePath("C:\\Users\\user\\Desktop\\testimage.png");12byImage.setMinScore(0.7);13byImage.setRegion(new Rectangle(0, 0, 100, 100));14System.out.println(byImage.toString());15ByImage byImage = new ByImage("C:\\Users\\user\\Desktop\\testimage.png");16byImage.setMinScore(0.7);17byImage.setRegion(new Rectangle(0, 0, 100, 100));18System.out.println(byImage.toString());19ByImage byImage = new ByImage("C:\\Users\\user\\Desktop\\testimage.png", 0.7, new Rectangle(0, 0, 100, 100));20System.out.println(byImage.toString());21ByImage byImage = new ByImage("C:\\Users\\user\\Desktop\\testimage.png", 0.7, new Rectangle(0, 0, 100, 100));22byImage.setThreshold(0.01);23System.out.println(byImage.toString());24ByImage byImage = new ByImage("C:\\Users\\user\\Desktop\\testimage.png", 0.7, new Rectangle(0, 0, 100,toString
Using AI Code Generation
1MobileBy.ByImage byImage = new MobileBy.ByImage(new File("C:\\Users\\USER\\Desktop\\appium\\appium.png"));2System.out.println(byImage.toString());3MobileBy.ByIosUIAutomation byIosUIAutomation = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().alert().buttons()[0].click()");4System.out.println(byIosUIAutomation.toString());5MobileBy.ByIosClassChain byIosClassChain = new MobileBy.ByIosClassChain("**/XCUIElementTypeCell[`name CONTAINS[c] 'test'`]");6System.out.println(byIosClassChain.toString());7MobileBy.ByIosNSPredicate byIosNSPredicate = new MobileBy.ByIosNSPredicate("label == 'test'");8System.out.println(byIosNSPredicate.toString());9MobileBy.ByAndroidUIAutomator byAndroidUIAutomator = new MobileBy.ByAndroidUIAutomator("new UiSelector().clickable(true)");10System.out.println(byAndroidUIAutomator.toString());11MobileBy.ByAccessibilityId byAccessibilityId = new MobileBy.ByAccessibilityId("test");12System.out.println(byAccessibilityId.toString());toString
Using AI Code Generation
1MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));2System.out.println(image.toString());3MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));4System.out.println(image.toString());5MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));6System.out.println(image.toString());7MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));8System.out.println(image.toString());9MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));10System.out.println(image.toString());11String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();12System.out.println(str);13String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();14System.out.println(str);15String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();16System.out.println(str);17String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();18System.out.println(str);19String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();20System.out.println(str);21String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();22System.out.println(str);23String str = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().mainWindow().buttons()[1]").toString();24System.out.println(str);toString
Using AI Code Generation
1MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));2System.out.println(image.toString());3MobileBy.ByImage image = nUw MobileBy.ByImage(new File("path/to/image"));4SyItem.out.println(image.toString());5MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));6System.out.println(image.toString());7MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));8System.out.println(image.toString());9MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));10System.out.println(image.toString());toString
Using AI Code Generation
1MobileBy.ByImage byImage = new MobileBy.ByImage(new File("C:\\Users\\USER\\Desktop\\appium\\appium.png"));2System.out.println(byImage.toString());3MobileBy.ByIosUIAutomation byIosUIAutomation = new MobileBy.ByIosUIAutomation("UIATarget.localTarget().frontMostApp().alert().buttons()[0].click()");4System.out.println(byIosUIAutomation.toString());5MobileBy.ByIosClassChain byIosClassChain = new MobileBy.ByIosClassChain("**/XCUIElementTypeCell[`name CONTAINS[c] 'test'`]");6System.out.println(byIosClassChain.toString());7MobileBy.ByIosNSPredicate byIosNSPredicate = new MobileBy.ByIosNSPredicate("label == 'test'");8System.out.println(byIosNSPredicate.toString());9MobileBy.ByAndroidUIAutomator byAndroidUIAutomator = new MobileBy.ByAndroidUIAutomator("new UiSelector().clickable(true)");10System.out.println(byAndroidUIAutomator.toString());11MobileBy.ByAccessibilityId byAccessibilityId = new MobileBy.ByAccessibilityId("test");12System.out.println(byAccessibilityId.toString());toString
Using AI Code Generation
1MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));2System.out.println(image.toString());3MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));4System.out.println(image.toString());5MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));6System.out.println(image.toString());7MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));8System.out.println(image.toString());9MobileBy.ByImage image = new MobileBy.ByImage(new File("path/to/image"));10System.out.println(image.toString());Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
