четверг, 20 декабря 2018 г.

1.Cont, 5.Dev. Java - principles OOP (abstraction, encapsulation, inheritance, polymorphism)

English version
Lesson: Object-Oriented Programming Concepts 
Шпаргалка по принципам ООП 

Encapsulation - hide the data
Inheritance - extend data and behaviors 
Polymorphism - the ability to take multiple forms
Abstraction - provides templates to be implemented

 Абстракция

Абстра́кция  — в объектно-ориентированном программировании это придание объекту характеристик, которые отличают его от всех других объектов, четко определяя его концептуальные границы. Основная идея состоит в том, чтобы отделить способ использования составных объектов данных от деталей их реализации в виде более простых объектов, подобно тому, как функциональная абстракция разделяет способ использования функции и деталей её реализации в терминах более примитивных функций, таким образом, данные обрабатываются функцией высокого уровня с помощью вызова функций низкого уровня.
Такой подход является основой объектно-ориентированного программирования. Это позволяет работать с объектами, не вдаваясь в особенности их реализации. В каждом конкретном случае применяется тот или иной подход: инкапсуляция, полиморфизм или наследование. Например, при необходимости обратиться к скрытым данным объекта, следует воспользоваться инкапсуляцией, создав, так называемую, функцию доступа или свойство.
Абстракция данных — популярная и в общем неверно определяемая техника программирования. Фундаментальная идея состоит в разделении несущественных деталей реализации подпрограммы и характеристик существенных для корректного ее использования. Такое разделение может быть выражено через специальный «интерфейс», сосредотачивающий описание всех возможных применений программы[1].
С точки зрения теории множеств, процесс представляет собой организацию для группы подмножеств своего множества. См. также Закон обратного отношения между содержанием и объемом понятия. 
Wiki
Examples in practice

Инкапсуляция

Инкапсуля́ция — свойство языка программирования, позволяющее пользователю не задумываться о сложности реализации используемого программного компонента (что у него внутри?), а взаимодействовать с ним посредством предоставляемого интерфейса (публичных методов и членов), а также объединить и защитить жизненно важные для компонента данные. При этом пользователю предоставляется только спецификация (интерфейс) объекта.
Пользователь может взаимодействовать с объектом только через этот интерфейс. Реализуется с помощью ключевого слова: public.
Пользователь не может использовать закрытые данные и методы. Реализуется с помощью ключевых слов: private, protected, internal.
Инкапсуляция — один из четырёх важнейших механизмов объектно-ориентированного программирования (наряду с абстракцией, полиморфизмом и наследованием).
Сокрытие реализации целесообразно применять в следующих случаях:
предельная локализация изменений при необходимости таких изменений,
прогнозируемость изменений (какие изменения в коде надо сделать для заданного изменения функциональности) и прогнозируемость последствий изменений.

пятница, 27 июля 2018 г.

воскресенье, 17 июня 2018 г.

AQA: Java – Get Random Item/Element From a List

Last modified: May 5, 2018, by

1. Introduction

Picking a random List element is a very basic operation but not so obvious to implement. In this article, we’ll show the most efficient way of doing this in different contexts.

2. Picking a Random Item/Items

In order to get a random item from a List instance, you need to generate a random index number and then fetch an item by this generated index number using List.get() method.
The key point here is to remember that you mustn’t use an index that exceeds your List’s capacity.


2.1. Single Random Item

In order to select a random index, you can use Random.nextInt(int bound) method:

public void givenList_shouldReturnARandomElement() {
    List<Integer> givenList = Arrays.asList(1, 2, 3);
    Random rand = new Random();
    int randomElement = givenList.get(rand.nextInt(givenList.size()));
}
Instead of Random class, you can always use static method Math.random() and multiply it with list size (Math.random() generates Double random value between 0 (inclusive) and 1 (exclusive), so remember to cast it to int after multiplication).

вторник, 5 июня 2018 г.

AQA: Selenium - Check Visibility of Web Elements Using Various Types WebDriver Commands – Selenium Tutorial #14

How to check visibility of web elements using various types of looping and conditional commands in WebDriver:
Previously in the series, we discussed about WebDriver’s Select class which is primarily used to handle web elements like dropdowns and selecting various options under the dropdowns.
Moving ahead in the Selenium series, we would be discussing about the various types of looping and conditional commands in WebDriver like isSelected(), isEnabled() and isDispalyed(). These methods are used to determine the visibility scope for the web elements.
So let us start with a brief introduction – WebDriver has a W3C specification that details out the information about the different visibility preferences based out on the types of the web elements upon which the actions are to be performed.
WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.
  • isDisplayed()
  • isSelected()
  • isEnabled()
For an improved understanding, let us discuss the aforementioned methods with code examples.
As a specimen, we would be using the “google.com” as an application under test and the “Learning_Selenium” project created in the previous tutorials for script generation.
Scenario to be automated
  1. Launch the web browser and open the application under test – http://google.com
  2. Verify the web page title
  3. Verify if the “Google Search” button is displayed
  4. Enter the keyword in the “Google Search” text box by which we would want to make the request
  5. Verify that the “Search button” is displayed and enabled
  6. Based on visibility of the Search button, click on the search button
What You Will Learn: [show]

WebDriver Code

Step 1: Create a new java class named as “VisibilityConditions” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “VisibilityConditions.java” class.
Below is the test script that is equivalent to the above-mentioned scenario:
1import org.openqa.selenium.By;
2import org.openqa.selenium.WebDriver;
3import org.openqa.selenium.WebElement;
4import org.openqa.selenium.firefox.FirefoxDriver;
5 
6public class VisibilityConditions {
7 
8       /**
9        * @param args
10        */
11 
12       public static void main(String[] args) {
13 
14              // objects and variables instantiation
15              WebDriver driver = new FirefoxDriver();
16              String appUrl = "https://google.com";
17 
18              // launch the firefox browser and open the application url
19              driver.get(appUrl);
20 
21              // maximize the browser window
22              driver.manage().window().maximize();
23 
24              // declare and initialize the variable to store the expected title of the webpage.
25              String expectedTitle = "Google";
26 
27              // fetch the title of the web page and save it into a string variable
28              String actualTitle = driver.getTitle();
29 
30              // compare the expected title of the page with the actual title of the page and print the result
31              if (expectedTitle.equals(actualTitle))
32              {
33                     System.out.println("Verification Successful - The correct title is displayed on the web page.");
34              }
35              else
36              {
37                     System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
38              }
39 
40              // verify if the “Google Search” button is displayed and print the result
41              boolean submitbuttonPresence=driver.findElement(By.id("gbqfba")).isDisplayed();
42              System.out.println(submitbuttonPresence);
43 
44              // enter the keyword in the “Google Search” text box by which we would want to make the request
45              WebElement searchTextBox = driver.findElement(By.id("gbqfq"));
46              searchTextBox.clear();
47              searchTextBox.sendKeys("Selenium");
48 
49              // verify that the “Search button” is displayed and enabled
50              boolean searchIconPresence = driver.findElement(By.id("gbqfb")).isDisplayed();
51              boolean searchIconEnabled = driver.findElement(By.id("gbqfb")).isEnabled();
52 
53              if (searchIconPresence==true && searchIconEnabled==true)
54              {
55                     // click on the search button
56                     WebElement searchIcon = driver.findElement(By.id("gbqfb"));
57                     searchIcon.click();
58              }
59 
60              // close the web browser
61              driver.close();
62              System.out.println("Test script executed successfully.");
63 
64              // terminate the program
65              System.exit(0);
66       }
67}

Code Walkthrough

Following are the ways in which we ascertain the presence of web elements on the web page.
boolean submitbuttonPresence=driver.findElement(By.id(“gbqfba”)).isDisplayed();

isDispalyed()

isDisplayed() is the method used to verify presence of a web element within the webpage. The method is designed to result from a Boolean value with each success and failure. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.
Thus the above code snippet verifies for the presence of submit button on the google web page and returns a true value if the submit button is present and visible else returns a false value if the submit button is not present on the web page.
boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();
The method deals with the visibility of all kinds of web elements not just limiting to any one type.

isEnabled()

isEnabled() is the method used to verify if the web element is enabled or disabled within the webpage. Like isDisplayed() method, it is designed to result in a Boolean value with each success and failure. The method returns a “true” value if the specified web element is enabled on the web page and a “false” value if the web element is not enabled (state of being disabled) on the web page.
Thus the above code snippet verifies if the submit button is enabled or not and returns a Boolean value depending on the result.
The isEnabled() method is significant in scenarios where we want to ascertain that only if “Condition A” is fulfilled, then the element(principally button) is enabled. Refer the following illustration for the same.
Webdriver commands 1
In the above figure, Register button is enabled only when the agreement checkbox is selected.
Akin to above methods, we have a method referenced as “isSelected()” which tests if the specified web element is selected or not.
boolean searchIconSelected = driver.findElement(By.id(“male”)).isSelected();

isSelected()

isSelected() is the method used to verify if the web element is selected or not. isSelected() method is pre-dominantly used with radio buttons, dropdowns and checkboxes. Analogous to above methods, it is designed to result a Boolean value with each success and failure.
Thus the above code snippet verifies if the male radio button is selected or not and returns a Boolean value depending on the result. Refer the following image for the same.

Conclusion

In this tutorial, we tried to make you acquainted with the WebDriver’s looping and conditional operations. These conditional methods often deal with almost all types of visibility options for web elements.
Article Summary:
  • WebDriver has a W3C specification that details out the information about the different visibility preferences based out on the types of the web elements.
  • isDisplayed() is the method used to verify a presence of a web element within the webpage. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.
  • isDisplayed() is capable to check for the presence of all kinds of web elements available.
  • isEnabled() is the method used to verify if the web element is enabled or disabled within the webpage.
  • isEnabled() is primarily used with buttons.
  • isSelected() is the method used to verify if the web element is selected or not. isSelected() method is predominantly used with radio buttons, dropdowns and checkboxes.
Next Tutorial #15: While working on web applications, often we are re-directed to different web pages by refreshing the entire web page and re-loading the new web elements. At times there can be Ajax calls as well. Thus, a time lag can be seen while reloading the web pages and reflecting the web elements. Thus, our next tutorial in-line is all about dealing with such time lags by using implicit and explicit waits.
Note for the Readers: Till then, the reader can automate and test the visibility scope for the web elements using WebDriver’s methods.

вторник, 15 мая 2018 г.

AQA: Java - Простой пример работы с Property файлами в Java

Property файлы присутствуют практически в каждом проекте, и сейчас я вам покажу простой пример их использования, а также расскажу, зачем они и где используются.

Шаг 0. Создание проекта

Начнем с того что создадим простой Maven проект, указав название и имя пакета:

prop_1

Структура, которая получится в конце проекта довольно таки простая.


Как видите у нас только два файла, первый – Main.java, а второй – config.properties.


четверг, 3 мая 2018 г.

AQA: Selenium - WebDriver - Database Testing using Selenium: Step by Step Guide


Selenium Webdriver is limited to Testing your applications using Browser. To use Selenium Webdriver for Database Verification you need to use the JDBC ("Java Database Connectivity").
JDBC (Java Database Connectivity) is a SQL level API that allows you to execute SQL statements. It is responsible for the connectivity between the Java Programming language and a wide range of databases. The JDBC API provides the following classes and interfaces
  • Driver Manager
  • Driver
  • Connection
  • Statement
  • ResultSet
  • SQLException
In order to test your Database using Selenium, you need to observe the following 3 steps
1. Make a connection to the Database
2. Send Queries to the Database
3. Process the results
Database Testing using Selenium: Step by Step Guide

1) Make a connection to the Database

In order to make a connection to the database the syntax is
DriverManager.getConnection(URL, "userid", "password" )
Here,
  • Userid is the username configured in the database
  • Password of the configured user
  • URL is of format jdbc:< dbtype>://ipaddress:portnumber/db_name"
  • <dbtype>- The driver for the database you are trying to connect. To connect to oracle database this value will be "oracle"
    For connecting to database with name "emp" in MYSQL URL will bejdbc:mysql://localhost:3036/emp
And the code to create connection looks like
Connection con = DriverManager.getConnection(dbUrl,username,password);
You also need to load the JDBC Driver using the code
Class.forName("com.mysql.jdbc.Driver");

2) Send Queries to the Database

Once connection is made, you need to execute queries.
You can use the Statement Object to send queries.
Statement stmt = con.createStatement();   
Once the statement object is created use the executeQuery method to execute the SQL queries
stmt.executeQuery(select *  from employee;);

3) Process the results

Results from the executed query are stored in the ResultSet Object.
Java provides loads of advance methods to process the results. Few of the methods are listed below
Database Testing using Selenium: Step by Step Guide

 Example of Database Testing with Selenium

понедельник, 16 апреля 2018 г.

AQA: Selenium + Java: Page Object Model



What it is? 
Page Object is a Design Pattern for enhancing test maintenance and reducing code duplication.
A page object is an object-oriented class that serves as an interface to a page of your AUT.
The tests then use the methods of this page object class whenever they need to interact with the UI of that page.

The benefit is?
- if the UI changes for the page, the tests themselves don’t need to change, only the
code within the page object needs to change;
- Subsequently all changes to support that new UI are located in one place;
- enchancing test maintenance;
- reducing code duplication;
- There is a clean separation between test code and page specific code such as locators (or their use if you’re using a UI Map) and layout;
- There is a single repository for the services or operations offered by the page rather than having these services scattered throughout the tests;

- In both cases this allows any modifications required due to UI changes to all be made in one place;

Summary: 
- The public methods represent the services that the page offers
- Try not to expose the internals of the page
- Generally don't make assertions
- Methods return other PageObjects
- Need not represent an entire page
- Different results for the same action are modelled as different methods

Links: 
- docs.seleniumhq.org;
- git - PageObjects;
- git - PageFactory;
- Михаил Поляруш - video:
- page-object-model;
- Introduction to Page Object Model Framework;
- Simple Page Object Model example;
- Оптимизация теста с помощью Page Object. Часть 1. Создание классов с описанием веб-страниц;
- Оптимизация теста с помощью Page Object. Часть 2. Создание теста;
- Применение Property файлов в автотестах на Java;
- Использование паттерна Page Object;
- Подготовка Page Object Model - пример на автоматизации ФБ;

вторник, 10 апреля 2018 г.

AQA: Java: Java 9 – Exploring the REPL

1. Introduction

This article is about jshell, an interactive REPL (Read-Evaluate-Print-Loop) console that is bundled with the JDK for the upcoming Java 9 release. For those not familiar with the concept, a REPL allows to interactively run arbitrary snippets of code and evaluate their results.
A REPL can be useful for things such as quickly checking the viability of an idea or figuring out e.g. a formatted string for String or SimpleDateFormat.

2. Running

To get started we need to run the REPL, which is done by invoking:
1
$JAVA_HOME/bin/jshell
If more detailed messaging from the shell is desired, a -v flag can be used:
1
$JAVA_HOME/bin/jshell -v
Once it is ready, we will be greeted by a friendly message and a familiar Unix-style prompt at the bottom.

3. Defining and Invoking Methods

Methods can be added by typing their signature and body:
1
2
jshell> void helloWorld() { System.out.println("Hello world");}
|  created method helloWorld()
Here we defined the ubiquitous “hello world” method.  It can be invoked using normal Java syntax:
1
2
jshell> helloWorld()
Hello world

4. Variables

Variables can be defined with the normal Java declaration syntax:
1
2
3
4
5
6
7
8
9
10
11
jshell> int i = 0;
i ==> 0
|  created variable i : int
 
jshell> String company = "Baeldung"
company ==> "Baeldung"
|  created variable company : String
 
jshell> Date date = new Date()
date ==> Sun Feb 26 06:30:16 EST 2017
|  created variable date : Date
Note that semicolons are optional.  Variables can also be declared without initialization:
1
2
3
jshell> File file
file ==> null
|  created variable file : File

5. Expressions

пятница, 6 апреля 2018 г.

AQA: Selenium - video collection

AQA: Selenium: Execute TestNg Project using batch file


Execute TestNg Project using batch file

Below description would help you to execute JAVA + TestNg Project using batch file.
Here, we have one sample class called SampleTest.java in JAVA Project which would open Google in chrome browser and verify the page title and then closes the browser at the end.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class SampleTest {
    WebDriver driver;
    @BeforeMethod
    public void setup() {
        String baseUrl = "http://www.google.com";
        // Initialize driver object
        System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/lib/chromedriver.exe");
        driver = new ChromeDriver();
        // Launch Application on browser
        driver.get(baseUrl);
    }
    @Test
    public void test01() {
        String expectedPageTitle = "Google";
        String actualPageTitle = "";
        // Fetch page title and store it in a variable
        actualPageTitle = driver.getTitle();
        // Print title
        System.out.println(actualPageTitle);
        if (actualPageTitle.equals(expectedPageTitle)) {
            System.out.println("Test case passed");
        } else {
            System.out.println("Test case Failed");
        }
    }
    @AfterMethod
    public void tearDonw() {
        // close browser
        driver.close();
    }
}

четверг, 5 апреля 2018 г.

AQA: tools: git - the simple guide. just a simple guide for getting started with git. no deep shit ;)


create a new repository

create a new directory, open it and perform a
git init
to create a new git repository.

checkout a repository

create a working copy of a local repository by running the command
git clone /path/to/repository
when using a remote server, your command will be
git clone username@host:/path/to/repository

workflow

your local repository consists of three "trees" maintained by git. the first one is your Working Directory which holds the actual files. the second one is the Index which acts as a staging area and finally the HEAD which points to the last commit you've made.


add & commit

You can propose changes (add it to the Index) using
git add <filename>
git add *
This is the first step in the basic git workflow. To actually commit these changes use
git commit -m "Commit message"
Now the file is committed to the HEAD, but not in your remote repository yet.

pushing changes

Your changes are now in the HEAD of your local working copy. To send those changes to your remote repository, execute
git push origin master
Change master to whatever branch you want to push your changes to.

If you have not cloned an existing repository and want to connect your repository to a remote server, you need to add it with
git remote add origin <server>
Now you are able to push your changes to the selected remote server


branching

Branches are used to develop features isolated from each other. The master branch is the "default" branch when you create a repository. Use other branches for development and merge them back to the master branch upon completion.



create a new branch named "feature_x" and switch to it using
git checkout -b feature_x
switch back to master
git checkout master
and delete the branch again
git branch -d feature_x
a branch is not available to others unless you push the branch to your remote repository
git push origin <branch>

update & merge

to update your local repository to the newest commit, execute
git pull
in your working directory to fetch and merge remote changes.
to merge another branch into your active branch (e.g. master), use
git merge <branch>
in both cases git tries to auto-merge changes. Unfortunately, this is not always possible and results in conflicts. You are responsible to merge those conflicts manually by editing the files shown by git. After changing, you need to mark them as merged with
git add <filename>
before merging changes, you can also preview them by using
git diff <source_branch> <target_branch>

tagging

it's recommended to create tags for software releases. this is a known concept, which also exists in SVN. You can create a new tag named 1.0.0 by executing
git tag 1.0.0 1b2e1d63ff
the 1b2e1d63ff stands for the first 10 characters of the commit id you want to reference with your tag. You can get the commit id by looking at the...


log

in its simplest form, you can study repository history using.. git log
You can add a lot of parameters to make the log look like what you want. To see only the commits of a certain author:
git log --author=bob
To see a very compressed log where each commit is one line:
git log --pretty=oneline
Or maybe you want to see an ASCII art tree of all the branches, decorated with the names of tags and branches:
git log --graph --oneline --decorate --all
See only which files have changed:
git log --name-status
These are just a few of the possible parameters you can use. For more, see git log --help


replace local changes

In case you did something wrong, which for sure never happens ;), you can replace local changes using the command
git checkout -- <filename>
this replaces the changes in your working tree with the last content in HEAD. Changes already added to the index, as well as new files, will be kept.
If you instead want to drop all your local changes and commits, fetch the latest history from the server and point your local master branch at it like this
git fetch origin
git reset --hard origin/master

useful hints

built-in git GUI
gitk
use colorful git output
git config color.ui true
show log on just one line per commit
git config format.pretty oneline
use interactive adding
git add -i

links & resources

graphical clients


guides


get help

среда, 4 апреля 2018 г.

AQA: Selenium: TestNG - used config

- add plugin to pom file:
    </dependencies>
  <build>
          <pluginManagement>
              <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                     <artifactId>maven-surefire-plugin</artifactId>
                     <version>2.21.0</version>
                    <!--configuration>
                     <suiteXmlFiles>
                     <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
                     </suiteXmlFiles>
                    </configuration-->
                </plugin>
              </plugins>
          </pluginManagement>
  </build>
</project>
- and config your testng.xml file:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite1" verbose="1" >
    <test name="Nopackage" >
        <classes>
            <class name="ua.aqa.aqa"/>
        </classes>
    </test>
</suite>

- than you can find your report in folder
"..\project\target\surefire-reports"

суббота, 10 марта 2018 г.

AQA: selenium: xpath - collection of examples and sources

AQA: Selenium: xpath - collection of examples and sources.

Xpath - декларативный язык запросов к элементам xml или (x)html документа и xslt преобразований.
Полезные источники:
Полная спецификация по Xpath 1.0 на русском здесь - http://citforum.ru/internet/xpath/xpath.shtml.
Xpath Online Tester - http://www.xpathtester.com/xpath/
Использование Xpath в Firebug
Для поиска DOM элементов по Xpath в Firebug есть встроенная ф-ция:
$x(xpath [, contextNode [, resultType]])
Тип результата:
XPathResult.NUMBER_TYPE
XPathResult.STRING_TYPE
XPathResult.BOOLEAN_TYPE
XPathResult.FIRST_ORDERED_NODE_TYPE
XPathResult.UNORDERED_NODE_ITERATOR_TYPE
Пример использования XPATH запросов в Firebug:
$x('//tr[@data-place]/@data-place')[0].value
$x('string(//tr[@data-place][1]/@data-place)')

Примеры

//div[contains(@class, 'CLASS') and normalize-space(text())='TEXT']
//a[normalize-space(text())='TEXT']
//*[normalize-space(text())='Купить']/ancestor-or-self::button

Базовый синтаксис

Пути

.             # текущий контекст
.//           # рекурсивный спуск (на ноль или более уровней от текущего контекста)
/html/body    # абсолютный путь
table//a      # относительный путь
a             # путь относительно текущего контекста
//*           # все в текущем контексте
li/*/a        # ссылки, являющиеся "внуками" для li
//a|//button  # ссылки и кнопки (объединение двух множеств узлов)

Отношения

a/i/parent::p           # непосредственный родитель, <p>
p/ancestor::*           # все родители (http://bit.ly/1ta7mh9)
p/following-sibling::*  # все следующие братья
p/preceding-sibling::*  # все предыдущие братья 
p/following::*          # все следующие элементы кроме потомков (http://bit.ly/1ta83H5)
p/preceding::*          # все предыдущие элементы кроме предков
p/descendant-or-self::* # контекстный узел и все его потомки
p/ancestor-or-self::*   # контекстный узел и все его предки

Получение узлов

/div/text()     # получить текстовые узлы
/div/text()[1]  # получить первый текстовый узел

Позиция элемента

a[1]                     # первый элемент
a[last()]                # последний элемент
a[i][2]                  # вторая ссылка, которая содержит элемент <i>
a[position() <= 3]       # Первые 3 ссылки
ul[li[1]="OK"]           # список (UL), первый элемент которого содержит значение 'OK'
tr[position() mod 2 = 1] # не четные элементы
tr[position() mod 2 = 0] # четные элементы
p/text()[2]              # второй текстовый узел

Атрибуты и фильтры

[] - указывает на фильтрацию элементов
input[@type=text]  # атрибуты задаются с префиксом @
input[@class='OK'] # 
p[not(@*)]         # параграфы без атрибутов
*[@style]          # все элементы с атрибутом style
a[. = "OK"]        # ссылки со значением "OK"
a/@id              # идентификаторы ссылок
a/@*               # все атрибуты ссылок
a[@id and @rel]    # ссылки, которые содержат атрибуты id и rel
a[@id][@rel]       # то же самое
a[i or b]          # ссылки содержат элемент <i> или <b>

Функции

Базовые функции Xpath - http://www.w3.org/TR/xpath/#corelib
name()                         [name()='a']                 # возвращает имя элемента
string(val)                    string(a[1]/@id)              # получить значение атрибута
substring(val, from, to)       substring(@id, 1, 6)          # вырезать часть строки
substring-after(val, from)     substring-after(@id, 'FROM') 
substring-before
string-length()      [string-length(text()) > 5]        # возвращает число символов в строке
count()              # возвращает количество элементов
concat()
normalize-space()    [normalize-space(text())='SEARCH']  # аналог trim, удаляет пробелы Пример: 
starts-with()        [starts-with(text(), 'SEARCH')]
contains()           [contains(name(), 'SEARCH')]
translate("bar","abc","ABC") # BAr

Математика

//p[ position() = floor(last() div 2 + 0.5) or position() = ceiling(last() div 2 + 0.5) ]
//tr[position() mod 2 = 0]

position()  # 
div         # деление
mod         # остаток от деления
ceiling()   # минимальное целое
floor()     # максимальное целое
round()
sum()

Группирование

(table/tbody/tr)[last()]  # последняя строка <tr> из всех таблиц
(//h1|//h2)[contains(text(), 'Text')] # заголовок первого или второго уровня, который содержит "Text"

Составные условия фильтрации

Все ссылки у которых атрибут data-id совпадает с этим же атрибутом у строки таблицы:
a[//tr/@data-id=@data-id]

четверг, 1 марта 2018 г.

AQA: create executable jar file with maven

1. Introduction

In this quick article we’ll focus on packaging a Maven project into an executable Jar file.
Usually, when creating a jar file, we want to execute it easily, without using the IDE; to that end, we’ll discuss the configuration and pros/cons of using each of these approaches for creating the executable.

2. Configuration

In order to create an executable jar, we don’t need any additional dependencies. We just need to create Maven Java project, and have at least one class with the main(…) method.
In our example, we created Java class named ExecutableMavenJar.
We also need to make sure that our pom.xml contains the the following elements:
1
2
3
4
5
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
The most important aspect here is the type – to create an executable jar, double check the configuration uses a jar type.
Now we can start using the various solutions.

2.1. Manual Configuration

SEO: Эксперимент: как Яндекс и Google учитывают ключевые слова в URL

Эксперимент: как Яндекс и Google учитывают ключевые слова в URL Эксперимент: как Яндекс и Google учитывают ключевые слова в URL Дата пу...