Saturday, October 30, 2021

Java: Convert Word to Password-Protected PDF

 Spire.Doc for Java allows developers to convert Word documents to password-protected PDF documents by using the Document.saveToFile(String, ToPdfParameterList) method. The ToPdfParameterList parameter controls how a Word document will be converted to PDF, for example, whether to encrypt the document while converting.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

    <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.doc</artifactId>
            <version>4.10.9</version>
        </dependency>
    </dependencies>

    Convert Word to Password-Protected PDF

    The following are the steps to convert a Word document to password-protected PDF:

    • Create a Document instance.
    • Load a Word document using Document.loadFromFile() method.
    • Create a ToPdfParameterList instance.
    • Set open password and permission password for PDF using ToPdfParameterList.getPdfSecurity().encrypt() method.
    • Save the Word document to PDF with password using Document.saveToFile(String, ToPdfParameterList) method.
    • Java
    import com.spire.doc.Document;
    import com.spire.doc.ToPdfParameterList;
    import com.spire.pdf.security.PdfEncryptionKeySize;
    import com.spire.pdf.security.PdfPermissionsFlags;
    
    public class ConvertWordToPasswordProtectedPDF {
        public static void main(String[] args){
    
            //Create a Document instance
            Document document = new Document();
            //Load a Word document
            document.loadFromFile("Sample.docx");
    
            //Create a ToPdfParameterList instance
            ToPdfParameterList toPdf = new ToPdfParameterList();
            //Set open password and permission password for PDF
            String password = "password";
            toPdf.getPdfSecurity().encrypt(password, password, PdfPermissionsFlags.None, PdfEncryptionKeySize.Key_128_Bit);
    
            //Save the Word document to PDF with password
            document.saveToFile("ToPdfWithPassword.pdf", toPdf);
        }
    }

    Java: Convert Word to Password-Protected PDF

    Apply for a Temporary License

    If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

    Friday, October 29, 2021

    Basic Selenium Interview Questions

     1. What is automation testing, and what are its advantages?

    Automation testing or Test Automation is a process of automating the manual testing process of an application or a system by using testing tools that allow you to create scripts that can be executed repeatedly, generating detailed test reports of the application or system under test.

    Advantages of automated testing are:

    • It supports both the performance and functional testing of an application or system.
    • It facilitates the execution of repeated test cases.
    • It allows the parallel execution of the test cases.
    • It improves the accuracy and efficiency of the system by reducing the manual intervention of humans to generate test cases.
    • It helps in testing a large scale test matrix.
    • It saves valuable time and money for the testing team involved in the project.

    2. Why should Selenium be selected as a testing tool for web applications or systems?

    Selenium provides the following advantages, which make it an excellent automated testing framework:

    • It is free and open-source software with a large user base and supports providing community.
    • It has cross-browser compatibility and supports multiple browsers like Google Chrome, Mozilla Firefox, Internet Explorer, Edge, Opera, Safari, etc.
    • It supports multiple operating systems such as Windows, Linux, macOS, etc.
    • It facilitates the usage of multiple programming languages including Scala, Ruby, Python, PHP, Perl, Java, Groovy, C#, etc.
    • It provides support for distributed testing as well.

    3. What are the disadvantages of using Selenium as a testing tool?

    The following are the disadvantages of using Selenium as a testing tool:

    • Tests web applications only: Selenium supports the testing of only web-based applications. Mobile applications, Captcha, and Barcode readers cannot be tested using Selenium unless integrated with third-party tools like Appium and TestNG.
    • No built-in reporting and test management facility: Selenium can generate reports only using third-party tools like TestNG or JUnit.
    • Unavailability of reliable tech support: Since Selenium is an open-source tool, no dedicated support for user issues is available.
    • May require the knowledge of programming languages: Some prior programming knowledge is required to use Selenium.

    4. What is meant by Selenium Suite and what are its different components?

    Selenium is a package of several testing tools and is therefore often referred to as a Selenium Suite with each of these tools designed to cater to a different testing requirement.

    Following are the different components of Selenium Suite:

    • Selenium Integrated Development Environment (IDE): It is a Firefox/Chrome plug-in that is developed to speed up the creation of automation scripts by recording the user actions on the web browser and exporting them as a reusable script.
    • Selenium Remote Control (RC): It is a server that enables users to generate test scripts in their preferred programming language. It accepts commands from the test scripts and sends them to the browser as Selenium core JavaScript commands, for the browser to behave accordingly.
    • Selenium WebDriver: It is a programming interface that helps create and run test cases by directly communicating with the web browser and using its native compatibility to automate. Unlike RC, it doesn’t require an additional server to create and run test cases.
    • Selenium Grid: It allows parallel execution of tests on different browsers and operating systems by distributing commands to different machines simultaneously.

    5. What is meant by Selenese? Explain different types of Selenium commands

    The language used for writing test scripts in Selenium IDE is called Selenese. It is a set of commands used to test your web application or system. Selenium commands could be divided into 3 major categories:

    1. Actions: These are the commands interacting directly with web applications.
    2. Accessors: These are the commands which allow users to store values to a user-defined variable.
    3. Assertions: They enable a comparison of the current state of the application with its expected state.

    6. What is meant by a locator and name a few different types of locators present in Selenium.

    A locator is an address for uniquely identifying web elements within a web page. There are different type of locators present in Selenium to identify web elements uniquely and accurately like:

    • ID
    • ClassName
    • Name
    • TagName
    • LinkText
    • PartialLinkText
    • Xpath
    • CSS Selector
    • DOM

    7. State the major difference between “assert” and “verify” commands in Selenium.

    Both “assert” and “verify” commands check whether the given condition is true or false and the only difference between them is that:

    • Assert: assert condition stops the execution of the testing if the given condition is false else would continue with the further tests.
    • Verify: verify the condition doesn’t stop the flow of execution irrespective of the condition being true or false.

    8. What is meant by an exception test in Selenium?

    An exception test is a test that expects an exception to be thrown inside a test class. It expects a @Test annotation followed by the expected exception name in the brackets.

    Eg: @Test(expectedException = NoSuchElementException.class) is an exception test for missing elements in Selenium.

    9. What is meant by XPath in Selenium. Explain XPath Absolute and XPath Relative.

    XPath, also defined as XML-Path (Extensible Markup Language Path), is a language used to query XML documents and provide functionalities like locating elements in Selenium by iterating through each element in a webpage. In XPath, data is stored in a key-value pair format similar to an HTML tag. It uses a single slash, i.e. ‘ / ’ for creating an absolute path, and a double slash, i.e. ‘ // ’ for creating a relative path for an element to be located on a webpage.

    10. Can selenium be used to launch web browsers?

    Yes, Selenium provides good support to launch web browsers like Google Chrome, Mozilla Firefox, Internet Explorer, etc.

    The following commands can be used to launch web browsers using Selenium:

    • WebDriver driver = new FirefoxDriver();
    • WebDriver driver = new ChromeDriver();
    • WebDriver driver = new InternetExplorerDriver();

    Advanced Selenium Interview Questions:

    11. Explain the difference between driver.close() and driver.quit() command in Selenium?

    Following is the major difference between both the commands:

    • driver.close() command closes the currently active window on which the user is working or the window being currently accessed by the web driver.
    • driver.quit() command, unlike the driver.close() command closes all the windows opened by the program and hence should be used with care.

    Both the commands don’t take any parameter and don’t return any value either.

    12. Explain the various navigation commands supported by Selenium?

    Selenium has the support of majorly 4 navigation commands:

    1. navigate().back(): This command is used for taking the user to the last webpage of the browser history.
    2. navigate().forward(): This command is used for taking the user to the next web page of the browser history.
    3. navigate().refresh(): This command is used for reloading the web components of a webpage by refreshing it.
    4. navigate().to(): This command is used for navigating to a particular URL in a new web browser. It takes the URL to be migrated to, as a parameter.

    13. Explain the same-origin policy and how Selenium handles it?

    Same Origin policy is a feature adopted for security purposes that allows a web browser to run scripts from one webpage to access the contents of another webpage provided both the pages have the same origin. The URL scheme, hostname, and port number combo are referred to as the origin. This policy was introduced to prevent access to sensitive data on one webpage by another for ill purposes. Consider a Java program used by scaler.com, the program can access domain pages like scaler.com/mentors, scaler.com/courses but none from different domains like facebook.com.

    The Selenium Server (Selenium RC) acts as a client configured HTTP proxy and "tricks" the browser into believing that Selenium Core and the web application being tested come from the same origin.

    14. Explain the difference between findElement() and findElements() in Selenium.

    Following is the major difference between the two commands:

    • findElement(): command is used for finding a particular element on a web page, it is used to return an object of the first found element by the locator.
    • Eg: WebElement element = driver.findElement(By.id(example));
    • findElements(): command is used for finding all the elements in a web page specified by the locator value. The return type of this command is the list of all the matching web elements.
    • Eg: List <WebElement> elementList = driver.findElements(By.id(example));

    15. Explain the pause feature in Selenium IDE.

    The pause feature is built to handle exceptions in the test script by allowing the user to pause at the statement causing the exception and enter the debug mode by clicking on the pause icon on the top right corner of the IDE. This feature prevents the entire test case's failure and gives the user a chance to correct the error instantly.

    16. With the help of code snippets, explain how we can create right-click and mouse hover actions in Selenium.

    The following code can replicate right-click action:

    actions action = newActions(driver);
    WebElement element = driver.findElement(By.id("elementId")); 
    action.contextClick(element).perform(); 
    

    The following code can replicate mouse hover action:

    actions action = newActions(driver);
    WebElement element = driver.findElement(By.id("elementId"));
    action.moveToElement(element).perform();

    17. Can we handle a windows-based pop-up in Selenium, and if not, then what are the alternatives?

    No, Selenium doesn’t support windows based pop-ups as it’s an automated testing tool built for web application based testing. However, with the support of third-party tools like AutoIT, Robot class, etc., windows-based pop-ups can be handled in selenium.

    18. Can you capture a screenshot using Selenium? If yes, write a simple code to illustrate the same.

    Yes, using a web driver in Selenium, we can capture the screenshot. Following is the code to do the same:

    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import java.io.File;
    import java.io.IOException;
    import org.apache.commons.io.FileUtils;
    import org.openqa.selenium.OutputType;
    import org.openqa.selenium.TakesScreenshot;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    
    public class TakeScreenshot {
    
    WebDriver drv;
    
        @ Before
        public void setUp() throws Exception {
        driver = new FirefoxDriver();
        drv.get("https://google.com");
    
    }
    
        @ After
        public void tearDown() throws Exception {
        drv.quit();
        }
    
        @ Test
        public void test() throws IOException {
    
        // Capture the screenshot
        File scrFile = ((TakeScreenshot)drv).getScreenshotAs(OutputType.FILE);
    
        // Code for pasting screenshot to a user-specified location
        FileUtils.copyFile(scrFile, new File("C:\\Screenshot\\Scr.jpg"))
        }
    
    }

    19. Explain different types of framework and connection of Selenium with Robot Framework.

    Following are the different type of frameworks:

    1. Behavior-Driven Development Framework: This type of framework provides a readable and easily understandable format to Business Analysts, Developers, Testers, etc.
    2. Data-Driven Testing Framework: This type of framework helps separate test data from the test-script logic by storing test data in some external database in the form of key-value pairs. These keys can be used for accessing as well as populating data into the test scripts.
    3. Keyword-Driven Testing Framework: This type of framework is an extension of the data-driven testing framework. In addition to separating test data and the test-script logic, it also separates a part of the test script code by storing it in an external data file.
    4. Library Architecture Testing Framework: This type of framework groups common steps into functions under a library and calls these functions as and when required.
    5. Module-Based Testing Framework: This type of framework divides each test application into several isolated and logical modules, with each module having its distinct test script.
    6. Hybrid Testing Framework: This type of framework is a combination of the above-mentioned frameworks leveraging all their good features.
    7. Robot Framework is a modular open-source automation framework that can interact with 3rd party libraries and functions. To execute a web testing library such as Selenium, a test automation runner or an automation wrapper is required, which is provided to it in the form of Robot Framework. Other popular test runners to serve the same purpose are MSTest, TestNG, Nunit, Junit, etc.

    The above diagram shows the connection of the Robot framework to the Selenium library.

    20. Demonstrate usage of Selenium through a test application.

    You need the following prerequisites to run a demo Selenium test script:

    • Java SDK in your respective Operating System.
    • Java-based IDE such as Eclipse or IntelliJ.
    • Selenium Web Driver to be added as a dependency to Java IDE.
    package scalerAcademy;
     
    import org.openqa.selenium.firefox.FirefoxDriver;
     
    import org.openqa.selenium.WebDriver;
     
     
    public class MyFirstTestClass {
     
     
      public static void main(String[] args) throws InterruptedException {
     
    //It sets the system property to the given value.
    System.setProperty("webdriver.gecko.driver","D:\\Softwares\\geckodriver.exe”);        
     
    WebDriver driver = new FirefoxDriver();
     
              driver.get("https://www.google.com/");
     
              //Launch website in the browser 
              driver.manage().window().maximize();
     
      //The sleep pauses the execution of the thread for 5000 ms.
              Thread.sleep(5000);
     
              driver.quit();
     
      }
     
    }
    

    Once you run the above script in a Java IDE, you’ll get the following execution logs displayed in your IDE window.

    21. Explain basic steps of Selenium testing and its widely used commands via a practical application.

    Selenium testing can be divided into the following seven basic elements:

    1. Creating an instance of a web driver: This is the first step for all the usages of a Selenium webdriver API. An instance of a webdriver interface is created using a constructor of a particular browser. This webdriver instance is used to invoke methods and to access other interfaces. Following are the most commonly used commands for initialising a web driver:
    2. Firefox:
      
      WebDriver driver = new FirefoxDriver();
      
      Chrome:
      
      WebDriver driver = new ChromeDriver(); 
      
      Safari Driver:
      
      WebDriver driver = new SafariDriver(); 
      
      Internet Explorer: 
      
      WebDriver driver = new InternetExplorerDriver(); 
      
    3. Navigating to a webpage: The second step after initializing an instance of a webdriver, to navigate to a particular webpage you want to test. Following are the most commonly used commands for webpage navigation:
    4. Navigate to URL: 
      driver.get(“https://www.interviewbit.com”) 
      driver.navigateo.to(“https://www.interviewbit.com”) 
      
      Refresh page:
      driver.navigate().refresh()
      
      Navigate forward in browser history:
      driver.navigate().forward()
      
      Navigate backward in browser history:
      driver.navigate().backward()
      
    5. Locating an HTML element on the webpage: To interact with a web element and perform actions on it like clicking a button or entering text, we first need to locate the desired elements such as the button or the textbox on the web page. Following are the most commonly used commands for web element navigation:
    6. Locating by ID:
      driver.findElement(By.id("q")).sendKeys("Selenium 3");
      
      Location by Name:
      driver.findElement(By.name("q")).sendKeys ("Selenium 3");
      
      Location by Xpath:
      driver.findElement(By.xpath("//input[@id==’q’])).sendKeys("Selenium 3");
      
      Locating Hyperlinks by Link Text:
      driver.FindElement(By.LinkText("edit this page")).Click();
      
      Locating by ClassName
      driver.findElement(By.className("profileheader"));
      
      Locating by TagName
      driver.findElement(By.tagName("select')).click();
      
      Locating by LinkText
      driver.findElement(By.linkText("NextPage")).click();
      
      Locating by PartialLinkText
      driverlindElement(By.partialLinkText(" NextP")).click();
      
    7. Performing actions on an HTML element: Once we have located the HTML element, the next step is interacting with it. Following are the most commonly used commands for performing actions on HTML element:
    8. Entering a username
      usernameElement.sendKeys("InterviewBit");
      
      Entering a password
      passwordElement.sendKeys("Raw");
      
      Submitting a text input element
      passwordElement.submit(); 
      
      Submitting a form element:
      formElement.submit();  
      
    9. Anticipating browser response from the action: Once an action is performed, anticipating a response from the browser to test comes under this step. It takes a second or two for the action to reach the browser, and hence wait is often required for this step. There are two main types of wait conditions:
      • Implicit Wait: It sets a fixed, definite time for all the webdriver interactions. It’s slightly unreliable as web driver response times are usually unpredictable.
      • Eg: driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      • Explicit Wait: This type of wait condition sets an expected condition to occur on the web page or a maximum wait time for all the webdriver interactions.
      • Eg: WebElement messageElement = wait.until(      ExpectedConditions.presenceOfElementLocated(By.id("loginResponse")) );
    10. Running tests and recording their results using a test framework: in this step, we run tests in an automated test script to evaluate an application's function and performance. Various test frameworks are used for this step, such as:
      • JUnit for Java
      • NUnit for C#
      • Unittest or Pyunit for Python
      • RUnit for Ruby

      Most frameworks use some sort of asset statement to verify their test results from the expected results.

      Eg: assertEquals (expectedMessage, actualMessage);
    11. Concluding a test: In this step, we conclude a test by invoking a quit method on the driver variable. This step closes all the webpages, quits the WebDriver server, and releases the driver.
    12. Eg: driver.quit();

    The following is an example of an app that covers all the steps mentioned above:

    import org.openqa.selenium.By,
    import org.openqa.selenium.WebElement, 
    
    import org.openqa.selenium.support.ni.ExpectedConditiof, import org.openqa.selenium.support.ni.WebOriverWait,
    
    import org.junit.Assert;
    
    public class Example {
    
    public static void main(String[] args) {
    
    // Creating a driver instance
    WebDriver driver = new FirefoxDriver(), 
    
    // Navigate to a web page
    ­driver.get("http://www.foo.com");
    
    // Enter text to submit the form
    WebElement usernameElement = driver.findElement( By.name("username"));
    WebElement passwordElement = driver.findElement(By.name(”password"));
    WebElement formElement = driver.findElement(By.id(”loginForm")); 
    
    usernameElement.sendKeys("Scaler Academy");
    passwordElement.sendKeys("Raw"); 
    
    formElement.submit();      // submit by form element 
    
    
    //Putting an explicit wait
    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement messageElement = wait.until(
           ExpectedConditions.presenceofElementLocated(By.id(”loginResponse")) 
           ) ; 
    
    // Run a test
    String message              = messageElement.getrept();
    String successMsg      = "Welcome to foo. You logged in successfully.”;
    Assert.assertEquals (message, successMsg); 
    
    // Conclude a test
    driver.quit();
    }
    }

    Android MCQs

     1.

    API stands for _____

    2.

    What is an interface in Android?

    3.

    What does Manifest.xml in Android consist of?

    4.

    XML Layout files are stored in _____ directory.

    5.

    _____ has developed the Android.

    6.

    ADB stands for _____.

    7.

    Android is based on which kernel?

    8.

    What is JNI in Android?

    9.

    Android web browser is based on

    10.

    What is a breakpoint in Android?

    11.

    Which is the JSON exception in Android?

    12.

    How to obtain a response from an Android activity?

    13.

    Which are the important device characteristics that should be considered when you design and develop an Android application?

    14.

    After installation on a device, each Android application lives in _____?

    15.

    Which of the following layouts present in Android?

    How to DROP SEQUENCE in Oracle?

      Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...