How to use BaseStartScreenRecordingOptions class of io.appium.java_client.screenrecording package

Best io.appium code snippet using io.appium.java_client.screenrecording.BaseStartScreenRecordingOptions

Run io.appium automation tests on LambdaTest cloud grid

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

VideoRecording.java

Source: VideoRecording.java Github

copy
1package se.soprasteria.automatedtesting.webdriver.helpers.video;
2
3import io.appium.java_client.android.AndroidStartScreenRecordingOptions;
4import io.appium.java_client.android.AndroidStopScreenRecordingOptions;
5import io.appium.java_client.ios.IOSStartScreenRecordingOptions;
6import io.appium.java_client.ios.IOSStopScreenRecordingOptions;
7import io.appium.java_client.screenrecording.BaseStartScreenRecordingOptions;
8import io.appium.java_client.screenrecording.BaseStopScreenRecordingOptions;
9import io.appium.java_client.screenrecording.CanRecordScreen;
10import org.monte.media.Format;
11import org.monte.media.math.Rational;
12import org.monte.screenrecorder.ScreenRecorder;
13import se.soprasteria.automatedtesting.webdriver.api.base.BaseClass;
14import se.soprasteria.automatedtesting.webdriver.api.base.BaseTestConfig;
15import se.soprasteria.automatedtesting.webdriver.api.datastructures.ConfigurationOption;
16import se.soprasteria.automatedtesting.webdriver.helpers.driver.AutomationDriver;
17
18import java.awt.*;
19import java.io.File;
20import java.io.FileOutputStream;
21import java.nio.file.Files;
22import java.nio.file.Path;
23import java.nio.file.Paths;
24import java.text.SimpleDateFormat;
25import java.util.Base64;
26import java.util.Date;
27
28import static org.monte.media.FormatKeys.*;
29import static org.monte.media.VideoFormatKeys.*;
30
31/**
32 * VIDEO RECORDING FUNCTIONALITY IS A BETA FEATURE!
33 * IT IS UNSTABLE AND NEED MORE TESTING.
34 * <p>
35 * Class with methods handling the video recording functionality.
36 * If property "config.video.record" is set to value "true" in config.xml-file
37 * video recording will be saved whenever a test fails.
38 */
39
40public class VideoRecording extends BaseClass {
41
42    private ScreenRecorder screenRecorder;
43    public static final String USER_DIR = "user.dir";
44    private static String outBaseFolder = "target/surefire-reports/video/";
45    private String folder;
46    private String currentVideoFilePath;
47    private static final VideoRecording INSTANCE;
48    private static final boolean VIDEO_RECORDING_ENABLED;
49
50    static {
51        INSTANCE = new VideoRecording();
52        VIDEO_RECORDING_ENABLED = Boolean.valueOf(BaseTestConfig.getConfigurationOption(ConfigurationOption.VIDEO_RECORDING));
53    }
54
55    public static VideoRecording getInstance() {
56        return INSTANCE;
57    }
58
59    public void startRecording(AutomationDriver driver) {
60        if (VIDEO_RECORDING_ENABLED) {
61            initVideoRecording();
62            if (driver.isWeb() || driver.isWindowsDriver()) {
63                startRecordingWeb();
64            } else if (driver.isMobile()) {
65                startRecordingMobile(driver);
66            }
67        }
68    }
69
70    public void stopRecording(AutomationDriver driver, boolean deleteRecording, String testName) {
71        if (VIDEO_RECORDING_ENABLED) {
72            if (driver.isWeb() || driver.isWindowsDriver()) {
73                stopRecordingWeb(testName);
74            } else if (driver.isMobile()) {
75                stopRecordingMobile(driver, testName);
76            }
77            logger.info("Stopped video recording");
78        }
79        if (deleteRecording) deleteRecording();
80    }
81
82    private void startRecordingWeb() {
83        try {
84            logger.info("Video recording is ON, Video folder: " + folder);
85            this.screenRecorder = new ScreenRecorder(getGraphicsConfiguration(), null,
86                    new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
87                    new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
88                            CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
89                            DepthKey, 24, FrameRateKey, Rational.valueOf(15),
90                            QualityKey, 1.0f,
91                            KeyFrameIntervalKey, 15 * 60),
92                    null, null, new File(folder));
93            this.screenRecorder.start();
94            logger.info("Start Video recording");
95        } catch (Exception e) {
96            System.setProperty("videoRecord", null);
97            logger.error("Can't start video recording." + e.getMessage());
98        }
99    }
100
101    private void startRecordingMobile(AutomationDriver driver) {
102
103        BaseStartScreenRecordingOptions options;
104        if (driver.isAndroid()) {
105            options = new AndroidStartScreenRecordingOptions();
106        } else {
107            options = new IOSStartScreenRecordingOptions();
108        }
109        try {
110            ((CanRecordScreen) driver.getWebDriver()).startRecordingScreen(options);
111        } catch (Exception e) {
112            logger.warn("Could not start recording screen on mobile platform: " + e.getMessage());
113        }
114        logger.trace("Mobile recording started");
115    }
116
117    private void stopRecordingWeb(String testName) {
118        try {
119            this.screenRecorder.stop();
120            File currentVideoFile = this.screenRecorder.getCreatedMovieFiles().get(0);
121            currentVideoFilePath = videoFileName(testName) + ".avi";
122            File videoFile = new File(currentVideoFilePath);
123            currentVideoFile.renameTo(videoFile);
124            logger.info("Append video record to file : " + currentVideoFile);
125        } catch (Exception e) {
126            logger.error("Can't stop video recording." + e.getMessage());
127        }
128    }
129
130    private void stopRecordingMobile(AutomationDriver driver, String testName) {
131        BaseStopScreenRecordingOptions options;
132        if (driver.isAndroid()) {
133            options = new AndroidStopScreenRecordingOptions();
134        } else {
135            options = new IOSStopScreenRecordingOptions();
136        }
137        byte[] decodedBytes = null;
138        try {
139            decodedBytes = Base64.getDecoder().decode(((CanRecordScreen) driver.getWebDriver()).stopRecordingScreen(options));
140        } catch (Exception e) {
141            logger.warn("Could not stop recording screen on mobile platform: " + e.getMessage());
142        }
143        try {
144            currentVideoFilePath = videoFileName(testName) + ".mp4";
145            FileOutputStream out = new FileOutputStream(currentVideoFilePath);
146            out.write(decodedBytes);
147            out.close();
148        } catch (Exception e) {
149            logger.error("Could not decode mobile video: ", e.toString());
150        }
151        logger.trace("Mobile recording stopped");
152    }
153
154    private void initVideoRecording() {
155        folder = System.getProperty(USER_DIR) + File.separator + outBaseFolder;
156        File movieFolder = new File(folder);
157        if (!movieFolder.exists()) {
158            movieFolder.mkdir();
159        }
160    }
161
162    private void deleteRecording() {
163        try {
164            Path path = Paths.get(currentVideoFilePath);
165            Files.delete(path);
166            logger.info("Test passed, deleting file : " + currentVideoFilePath);
167        } catch (Exception ioe) {
168            logger.error("File : " + currentVideoFilePath + " could not be deleted: " + ioe.getMessage());
169        }
170    }
171
172    private GraphicsConfiguration getGraphicsConfiguration() {
173        return GraphicsEnvironment
174                .getLocalGraphicsEnvironment()
175                .getDefaultScreenDevice()
176                .getDefaultConfiguration();
177    }
178
179    private String videoFileName(String testName) {
180        Date date = new Date();
181        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yy_HH-mm-ss");
182        return folder + testName + "_" + simpleDateFormat.format(date.getTime());
183    }
184}
185
Full Screen

MobileScreen.java

Source: MobileScreen.java Github

copy
1package com.epam.jdi.light.mobile.elements.composite;
2
3import com.epam.jdi.light.common.JDIAction;
4import com.epam.jdi.light.mobile.MobileContextHolder;
5import io.appium.java_client.MultiTouchAction;
6import io.appium.java_client.PerformsTouchActions;
7import io.appium.java_client.TouchAction;
8import io.appium.java_client.android.AndroidDriver;
9import io.appium.java_client.ios.IOSDriver;
10import io.appium.java_client.screenrecording.BaseStartScreenRecordingOptions;
11import io.appium.java_client.screenrecording.BaseStopScreenRecordingOptions;
12import io.appium.java_client.screenrecording.CanRecordScreen;
13import io.appium.java_client.touch.WaitOptions;
14import io.appium.java_client.touch.offset.PointOption;
15import org.apache.commons.lang3.NotImplementedException;
16import org.openqa.selenium.Dimension;
17import org.openqa.selenium.Point;
18import org.openqa.selenium.WebDriver;
19
20import java.time.Duration;
21import java.util.function.Function;
22
23import static com.epam.jdi.light.common.Exceptions.exception;
24import static com.epam.jdi.light.driver.WebDriverFactory.getDriver;
25import static com.epam.jdi.light.mobile.MobileUtils.executeDriverMethod;
26import static java.lang.Math.round;
27
28public class MobileScreen {
29
30    private static Dimension screenSize = null;
31    private static Point screenCenter = null;
32
33    // Android devices can provide the dimensions only in NATIVE_APP context
34    public static Dimension getScreenSize() {
35        if (screenSize == null) {
36            WebDriver driver = getDriver();
37            if (driver instanceof IOSDriver) {
38                screenSize = driver.manage().window().getSize();
39            } else if (driver instanceof AndroidDriver) {
40                String initialContext = MobileContextHolder.getContext();
41                MobileContextHolder.setContext("NATIVE_APP");
42                screenSize = getDriver().manage().window().getSize();
43                MobileContextHolder.setContext(initialContext);
44            } else {
45                throw exception("Cannot use this method. The driver needs to extend/implement the AppiumDriver class");
46            }
47            screenCenter = new Point(screenSize.width / 2, screenSize.height / 2);
48        }
49        return screenSize;
50    }
51    @JDIAction
52    private static void scroll(Point startingPoint, int xOffset, int yOffset) {
53        executeDriverMethod(PerformsTouchActions.class, (PerformsTouchActions driver) -> {
54            new TouchAction<>(driver)
55                    .press(PointOption.point(startingPoint))
56                    .waitAction(WaitOptions.waitOptions(Duration.ofSeconds(1)))
57                    .moveTo(PointOption.point(startingPoint.moveBy(xOffset, yOffset)))
58                    .release().perform();
59        });
60    }
61    private static void scrollVertically(int offset) {
62        Dimension dimension = getScreenSize();
63        int height = dimension.getHeight();
64        for (int i = 0; i < Math.abs(offset) / (height / 2); i++) {
65            scroll(screenCenter, 0, Integer.signum(offset) * (height / 2 - 1));
66        }
67        scroll(screenCenter, 0, offset % (height / 2));
68    }
69    private static void scrollHorizontally(int offset) {
70        Dimension dimension = getScreenSize();
71        int width = dimension.getWidth();
72        for (int i = 0; i < Math.abs(offset) / (width / 2); i++) {
73            scroll(screenCenter, Integer.signum(offset) * ( width / 2 - 1), 0);
74        }
75        scroll(screenCenter, offset % (width / 2), 0);
76    }
77
78    @JDIAction("Scroll up by {0} px")
79    public static void scrollUp(int offset) {
80        scrollVertically(offset);
81    }
82    @JDIAction("Scroll down by {0} px")
83    public static void scrollDown(int offset) {
84        scrollVertically(-offset);
85    }
86    @JDIAction("Scroll right by {0} px")
87    public static void scrollRight(int offset) {
88        scrollHorizontally(-offset);
89    }
90    @JDIAction("Scroll left by {0} px")
91    public static void scrollLeft(int offset) {
92        scrollHorizontally(offset);
93    }
94
95    public static void scrollToTop() {
96        throw new NotImplementedException("Not implemented yet");
97    }
98    public static void scrollToBottom() {
99        throw new NotImplementedException("Not implemented yet");
100    }
101
102    private static void pinch(Point startPoint1, Point startPoint2, Point endPoint1, Point endPoint2) {
103        executeDriverMethod(PerformsTouchActions.class, (PerformsTouchActions driver) -> {
104            TouchAction<?> ta1 = new TouchAction<>(driver)
105                    .press(PointOption.point(startPoint1))
106                    .waitAction(WaitOptions.waitOptions(Duration.ofSeconds(1)))
107                    .moveTo(PointOption.point(endPoint1))
108                    .release();
109            TouchAction<?> ta2 = new TouchAction<>(driver)
110                    .press(PointOption.point(startPoint2))
111                    .waitAction(WaitOptions.waitOptions(Duration.ofSeconds(1)))
112                    .moveTo(PointOption.point(endPoint2))
113                    .release();
114            new MultiTouchAction(driver).add(ta1).add(ta2).perform();
115        });
116    }
117    @JDIAction("Zoom in")
118    public static void zoomIn() {
119        Dimension dimension = getScreenSize();
120        pinch(screenCenter.moveBy(1, 1), screenCenter,
121                new Point(dimension.width - 1, dimension.height - 1), new Point(0, 0));
122    }
123    @JDIAction("Zoom out")
124    public static void zoomOut() {
125        Dimension dimension = getScreenSize();
126        pinch(new Point(dimension.width - 1, dimension.height - 1), new Point(0, 0),
127                screenCenter, screenCenter);
128    }
129    @JDIAction("Zoom in by {0}")
130    public static void zoomIn(double ratio) {
131        if ((ratio < 0 ) || (ratio > 1)) {
132            throw exception("The zoom ratio needs to be between 0 and 1");
133        } else {
134            Dimension dimension = getScreenSize();
135            pinch(screenCenter.moveBy(1, 1), screenCenter,
136                    screenCenter.moveBy((int) round(ratio * dimension.width / 2), (int) round(ratio * dimension.height / 2)),
137                    screenCenter.moveBy(-(int) round(ratio * dimension.width / 2), -(int) round(ratio * dimension.height / 2)));
138        }
139    }
140    @JDIAction("Zoom out by {0}")
141    public static void zoomOut(double ratio) {
142        if ((ratio < 0 ) || (ratio > 1)) {
143            throw exception("The zoom ratio needs to be between 0 and 1");
144        } else {
145            Dimension dimension = getScreenSize();
146            pinch(screenCenter.moveBy((int) round(ratio * dimension.width / 2), (int) round(ratio * dimension.height / 2)),
147                    screenCenter.moveBy(-(int) round(ratio * dimension.width / 2), -(int) round(ratio * dimension.height / 2)),
148                    screenCenter, screenCenter);
149        }
150    }
151
152    public static String startRecordingScreen() {
153        return executeDriverMethod(CanRecordScreen.class,
154                (Function<CanRecordScreen, String>) CanRecordScreen::startRecordingScreen);
155    }
156    public static <T extends BaseStartScreenRecordingOptions<?>> String startRecordingScreen(T options) {
157        return executeDriverMethod(CanRecordScreen.class,
158                (CanRecordScreen driver) ->  driver.startRecordingScreen(options));
159    }
160    public static String stopRecordingScreen() {
161        return executeDriverMethod(CanRecordScreen.class,
162                (Function<CanRecordScreen, String>) CanRecordScreen::stopRecordingScreen);
163    }
164    public static <T extends BaseStopScreenRecordingOptions<?>> String stopRecordingScreen(T options) {
165        return executeDriverMethod(CanRecordScreen.class,
166                (CanRecordScreen driver) ->  driver.stopRecordingScreen(options));
167    }
168}
169
Full Screen

CanRecordScreen.java

Source: CanRecordScreen.java Github

copy
1/*
2 * Licensed under the Apache License, Version 2.0 (the "License");
3 * you may not use this file except in compliance with the License.
4 * See the NOTICE file distributed with this work for additional
5 * information regarding copyright ownership.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package io.appium.java_client.screenrecording;
18
19import static io.appium.java_client.MobileCommand.START_RECORDING_SCREEN;
20import static io.appium.java_client.MobileCommand.STOP_RECORDING_SCREEN;
21import static io.appium.java_client.MobileCommand.startRecordingScreenCommand;
22import static io.appium.java_client.MobileCommand.stopRecordingScreenCommand;
23
24import io.appium.java_client.CommandExecutionHelper;
25import io.appium.java_client.ExecutesMethod;
26
27public interface CanRecordScreen extends ExecutesMethod {
28
29    /**
30     * Start asynchronous screen recording process.
31     *
32     * @param <T> The platform-specific {@link BaseStartScreenRecordingOptions}
33     * @param options see the documentation on the {@link BaseStartScreenRecordingOptions}
34     *                descendant for the particular platform.
35     * @return `not used`.
36     */
37    @SuppressWarnings("rawtypes")
38    default <T extends BaseStartScreenRecordingOptions> String startRecordingScreen(T options) {
39        return CommandExecutionHelper.execute(this, startRecordingScreenCommand(options));
40    }
41
42    /**
43     * Start asynchronous screen recording process with default options.
44     *
45     * @return `not used`.
46     */
47    default String startRecordingScreen() {
48        return this.execute(START_RECORDING_SCREEN).getValue().toString();
49    }
50
51    /**
52     * Gather the output from the previously started screen recording to a media file.
53     *
54     * @param <T> The platform-specific {@link BaseStopScreenRecordingOptions}
55     * @param options see the documentation on the {@link BaseStopScreenRecordingOptions}
56     *                descendant for the particular platform.
57     * @return Base-64 encoded content of the recorded media file or an empty string
58     *     if the file has been successfully uploaded to a remote location (depends on the actual options).
59     */
60    @SuppressWarnings("rawtypes")
61    default <T extends BaseStopScreenRecordingOptions> String stopRecordingScreen(T options) {
62        return CommandExecutionHelper.execute(this, stopRecordingScreenCommand(options));
63    }
64
65    /**
66     * Gather the output from the previously started screen recording to a media file
67     * with default options.
68     *
69     * @return Base-64 encoded content of the recorded media file.
70     */
71    default String stopRecordingScreen() {
72        return this.execute(STOP_RECORDING_SCREEN).getValue().toString();
73    }
74}
75
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

Most used methods in BaseStartScreenRecordingOptions

Run Selenium Automation Tests on LambdaTest Cloud Grid

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

Test now for Free
LambdaTestX

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

Allow Cookie
Sarah

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

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

Sarah Elson (Product & Growth Lead)