Axel Nordh 3 лет назад
Родитель
Сommit
735bbe7fbd
3 измененных файлов с 613 добавлено и 658 удалено
  1. 5 9
      Odds/src/Main.java
  2. 294 295
      Odds/src/mysql/Mysql.java
  3. 314 354
      Odds/src/parser/OddsPortal.java

+ 5 - 9
Odds/src/Main.java

@@ -6,7 +6,7 @@ import parser.OddsPortal;
 
 public class Main {
 
-	public static void main(String[] args) throws IOException {
+	public static void main(String[] args) {
 		final OddsPortal op = new OddsPortal();
 		System.out.println("Getting Yesterdays matches");
 		op.getYesterdaysMatches();
@@ -17,9 +17,8 @@ public class Main {
 
 		op.getNextDaysMatches();
 
-		//		op.getHistoricMatches("soccer", "japan", "j2-league", "2020");
-
-		//		callingRScript();
+		// op.getHistoricMatches("soccer", "japan", "j2-league", "2020");
+		// callingRScript();
 	}
 
 	private static void callingRScript() throws IOException {
@@ -28,12 +27,9 @@ public class Main {
 
 		final Process exec = Runtime.getRuntime().exec("C:\\Program Files\\R\\R-3.6.3\\bin\\Rscript.exe " + rPath);
 
+		final BufferedReader stdInput = new BufferedReader(new InputStreamReader(exec.getInputStream()));
 
-		final BufferedReader stdInput = new BufferedReader(new
-				InputStreamReader(exec.getInputStream()));
-
-		final BufferedReader stdError = new BufferedReader(new
-				InputStreamReader(exec.getErrorStream()));
+		final BufferedReader stdError = new BufferedReader(new InputStreamReader(exec.getErrorStream()));
 
 		// Read the output from the command
 		System.out.println("Here is the standard output of the command:\n");

+ 294 - 295
Odds/src/mysql/Mysql.java

@@ -9,303 +9,302 @@ import java.sql.Statement;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
 
+import org.eclipse.jetty.util.log.Log;
+
 import object.CurrentParsing;
 
 public class Mysql {
 
-    private static final Mysql instance = new Mysql();
-
-    private static final String username = "OddsNy";
-    private static final String password = "Odds1_Ny_Password";
-    private static final String database = "new_odds";
-    private static final String url = "jdbc:mysql://nordh.xyz:3306/";
-    private static final String timezoneFix
-            = "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
-
-    private Connection conn;
-
-    protected Mysql() {
-        getConnection();
-    }
-
-    public static Mysql getInstance() {
-        return instance;
-    }
-
-    protected Connection getConnection() {
-        if (conn == null) {
-            try {
-                conn = DriverManager.getConnection(url + database + timezoneFix, username, password);
-            } catch (final SQLException e) {
-                throw new RuntimeException(e.getMessage(), e);
-            }
-        }
-        return conn;
-    }
-
-    public CurrentParsing getCurrentParsing() {
-        final CurrentParsing returnValue = new CurrentParsing();
-        try {
-            final Statement statement = conn.createStatement();
-            final String sql = "SELECT * FROM parsing";
-            final ResultSet rs = statement.executeQuery(sql);
-            while (rs.next()) {
-                returnValue.setDone(rs.getBoolean("done"));
-                returnValue.setCurrentYear(rs.getInt("year"));
-                returnValue.setCurrentDate(rs.getDate("gameDate"));
-                returnValue.setLeague(rs.getString("league"));
-                returnValue.setPage(rs.getInt("page"));
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-        }
-        return returnValue;
-    }
-
-    public int addLeague(String leagueName, String country, String sport) throws SQLException {
-        leagueName = leagueName.trim();
-        leagueName = leagueName.replaceAll(" ", "-");
-        leagueName = leagueName.replaceAll("\\.", "");
-        final int sportId = addSport(sport);
-        final int countryId = addCountry(country);
-        final String sql = "INSERT INTO League (name, sportId, countryId) VALUES (?, ?, ?) " + "ON DUPLICATE KEY UPDATE name = ?";
-        final PreparedStatement statement = conn.prepareStatement(sql);
-        statement.setString(1, leagueName);
-        statement.setInt(2, sportId);
-        statement.setInt(3, countryId);
-        statement.setString(4, leagueName);
-
-        statement.executeUpdate();
-
-        return getId("League", leagueName, countryId);
-    }
-
-    public int addCountry(String name) throws SQLException {
-        name = name.replaceAll(" ", "-");
-        name = name.replaceAll("\\.", "");
-        final String sql = "INSERT INTO Country (name) VALUES (?) ON DUPLICATE KEY UPDATE name = ?";
-        final PreparedStatement statement = conn.prepareStatement(sql);
-        statement.setString(1, name);
-        statement.setString(2, name);
-        statement.executeUpdate();
-
-        return getId("Country", name, -1);
-    }
-
-    public int addSport(String sport) throws SQLException {
-        sport = sport.replaceAll(" ", "-");
-        sport = sport.replaceAll("\\.", "");
-        final String sql = "INSERT INTO Sport (name) VALUES (?) ON DUPLICATE KEY UPDATE name = ?";
-        final PreparedStatement statement = conn.prepareStatement(sql);
-        statement.setString(1, sport);
-        statement.setString(2, sport);
-        statement.executeUpdate();
-        return getId("Sport", sport, -1);
-    }
-
-    private int getId(String table, String name, int countryId) throws SQLException {
-        String sql = "SELECT id FROM " + table + " WHERE name = ?";
-        if (countryId > -1) {
-            sql += " AND countryId = ?";
-        }
-
-        final PreparedStatement stmt = conn.prepareStatement(sql);
-        stmt.setString(1, name.trim());
-        if (countryId > -1) {
-            stmt.setInt(2, countryId);
-        }
-        final ResultSet insertRs = stmt.executeQuery();
-        int id = 0;
-        if (insertRs.next()) {
-            id = insertRs.getInt("id");
-        }
-        return id;
-    }
-
-    public int getLeagueId(int sportId, int countryId, String leagueName) throws SQLException {
-        final String sql = "SELECT id FROM League WHERE name = ? AND countryId = ? AND sportId = ?";
-        final PreparedStatement stmt = conn.prepareStatement(sql);
-        stmt.setString(1, leagueName.trim());
-        stmt.setInt(2, countryId);
-        stmt.setInt(3, sportId);
-
-        final ResultSet rs = stmt.executeQuery();
-
-        int id = 0;
-        while (rs.next()) {
-            id = rs.getInt("id");
-        }
-
-        return id;
-    }
-
-    public int getSportId(String sportName) {
-        final String sql = "SELECT id from Sport WHERE name = ?";
-        PreparedStatement stmt;
-        int id = 0;
-        try {
-            stmt = conn.prepareStatement(sql);
-            stmt.setString(1, sportName.trim());
-
-            final ResultSet rs = stmt.executeQuery();
-            while (rs.next()) {
-                id = rs.getInt("id");
-            }
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-        return id;
-    }
-
-    public int getCountryId(String country) throws SQLException {
-        final String sql = "SELECT id from Country WHERE name = ?";
-        final PreparedStatement stmt = conn.prepareStatement(sql);
-        stmt.setString(1, country.trim());
-
-        final ResultSet rs = stmt.executeQuery();
-        int id = 0;
-        while (rs.next()) {
-            id = rs.getInt("id");
-        }
-
-        return id;
-    }
-
-    public void addResult(String tableName, LocalDateTime gameDate, String homeTeam, String awayTeam, int homeScore,
-            int awayScore, boolean overtime, float odds1, float oddsX, float odds2, int countryId, String season, int leagueId,
-            int sportId) throws SQLException {
-
-        final int homeTeamId = getOrInsertTeam(homeTeam, countryId, leagueId, sportId);
-        final int awayTeamId = getOrInsertTeam(awayTeam, countryId, leagueId, sportId);
-
-        final String selectSql = "SELECT id FROM SoccerResults WHERE homeTeamId = ? AND awayTeamId = ? AND DATE(gameDate) = ?";
-
-        final PreparedStatement st = conn.prepareStatement(selectSql);
-        final String date = gameDate.format(DateTimeFormatter.ISO_DATE);
-        st.setInt(1, homeTeamId);
-        st.setInt(2, awayTeamId);
-        st.setString(3, date);
-
-        final ResultSet rs = st.executeQuery();
-
-        int gameId = -1;
-        while (rs.next()) {
-            gameId = rs.getInt("id");
-        }
-
-        if (gameId != -1) {
-            final String sql
-                    = "UPDATE " + tableName + " SET homeScore = ?, awayScore = ?, overtime = ?, odds1 = ?, oddsX = ?, odds2 = ? "
-                            + "WHERE homeTeamId = ? AND awayTeamId = ? AND DATE(gameDate) = ?";
-
-            final PreparedStatement statement = conn.prepareStatement(sql);
-            statement.setInt(1, homeScore);
-            statement.setInt(2, awayScore);
-            statement.setBoolean(3, overtime);
-            statement.setFloat(4, odds1);
-            statement.setFloat(5, oddsX);
-            statement.setFloat(6, odds2);
-            statement.setInt(7, homeTeamId);
-            statement.setInt(8, awayTeamId);
-            statement.setString(9, date);
-
-            statement.executeUpdate();
-
-        } else {
-            final String sql = "INSERT INTO " + tableName
-                    + " (homeTeamId, awayTeamId, homeScore, awayScore, overtime, odds1, oddsX, odds2, countryId, gameDate, season, leagueId) "
-                    + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE homeScore = ?, awayScore = ?, odds1 = ?, oddsX = ?, odds2 = ?";
-            final PreparedStatement stmt = conn.prepareStatement(sql);
-            stmt.setInt(1, homeTeamId);
-            stmt.setInt(2, awayTeamId);
-            stmt.setInt(3, homeScore);
-            stmt.setInt(4, awayScore);
-            stmt.setBoolean(5, overtime);
-            stmt.setFloat(6, odds1);
-            stmt.setFloat(7, oddsX);
-            stmt.setFloat(8, odds2);
-            stmt.setInt(9, countryId);
-            stmt.setString(10, gameDate.toString());
-            stmt.setString(11, season);
-            stmt.setInt(12, leagueId);
-            stmt.setInt(13, homeScore);
-            stmt.setInt(14, awayScore);
-            stmt.setFloat(15, odds1);
-            stmt.setFloat(16, oddsX);
-            stmt.setFloat(17, odds2);
-
-            stmt.execute();
-        }
-
-    }
-
-    private int getOrInsertTeam(String teamName, int countryId, int leagueId, int sportId) throws SQLException {
-        teamName = teamName.replace('\u00A0', ' ').trim();
-        int teamId = getId("Team", teamName, countryId);
-        if (teamId <= 0) {
-            final String insertSql = "INSERT INTO Team (name, sportId, countryId, leagueId) VALUES (? ,? ,? ,?)";
-            final PreparedStatement insertTeamStatement = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
-            insertTeamStatement.setString(1, teamName.trim());
-            insertTeamStatement.setInt(2, sportId);
-            insertTeamStatement.setInt(3, countryId);
-            insertTeamStatement.setInt(4, leagueId);
-
-            insertTeamStatement.executeUpdate();
-            final ResultSet generatedKeys = insertTeamStatement.getGeneratedKeys();
-            generatedKeys.next();
-            teamId = generatedKeys.getInt(1);
-        }
-
-        return teamId;
-    }
-
-    public void setParsingForLeague(int leagueId, int sportId, int countryId, LocalDateTime gameDate, int currentParsePage,
-            String parsedYear) {
-        final String sql
-                = "UPDATE League SET parsedYear = ?, parsedPage = ?, lastParsedGameDate = ? WHERE sportId = ? AND countryId = ? AND id = ?";
-        try {
-            final PreparedStatement stmt = conn.prepareStatement(sql);
-            stmt.setString(1, parsedYear);
-            stmt.setInt(2, currentParsePage);
-            stmt.setString(3, gameDate.toString());
-            stmt.setInt(4, sportId);
-            stmt.setInt(5, countryId);
-            stmt.setInt(6, leagueId);
-
-            stmt.executeUpdate();
-        } catch (final SQLException e) {
-            System.out.println("Failing sql: " + sql + ", " + parsedYear + ", " + currentParsePage + ", " + gameDate.toString()
-                    + ", " + sportId + ", " + countryId + ", " + leagueId);
-            e.printStackTrace();
-        }
-    }
-
-    public String getLastParsedYear(String leagueName, int countryId) {
-        String returnValue = "";
-
-        final String sql = "SELECT parsedYear FROM League WHERE name = ? AND countryId = ?";
-        try {
-            final PreparedStatement stmt = conn.prepareStatement(sql);
-            stmt.setString(1, leagueName);
-            stmt.setInt(2, countryId);
-
-            final ResultSet rs = stmt.executeQuery();
-
-            while (rs.next()) {
-                returnValue = rs.getString("parsedYear");
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-        }
-
-        return returnValue;
-    }
-
-    public Connection getDbConnection() {
-        if (conn == null) {
-            conn = getConnection();
-        }
-        return conn;
-    }
+	private static final Mysql instance = new Mysql();
+
+	private static final String USERNAME = "OddsNy";
+	private static final String PASSWORD = "Odds1_Ny_Password";
+	private static final String DATABASE = "new_odds";
+	private static final String URL = "jdbc:mysql://nordh.xyz:3306/";
+	private static final String TIMEZONE_FIX = "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
+
+	private Connection conn;
+
+	protected Mysql() {
+		getConnection();
+	}
+
+	public static Mysql getInstance() {
+		return instance;
+	}
+
+	protected Connection getConnection() {
+		if (conn == null) {
+			try {
+				conn = DriverManager.getConnection(URL + DATABASE + TIMEZONE_FIX, USERNAME, PASSWORD);
+			} catch (final SQLException e) {
+				throw new RuntimeException(e.getMessage(), e);
+			}
+		}
+		return conn;
+	}
+
+	public CurrentParsing getCurrentParsing() {
+		final CurrentParsing returnValue = new CurrentParsing();
+		final String sql = "SELECT * FROM parsing";
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				returnValue.setDone(rs.getBoolean("done"));
+				returnValue.setCurrentYear(rs.getInt("year"));
+				returnValue.setCurrentDate(rs.getDate("gameDate"));
+				returnValue.setLeague(rs.getString("league"));
+				returnValue.setPage(rs.getInt("page"));
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+		return returnValue;
+	}
+
+	public int addLeague(String leagueName, String country, String sport) throws SQLException {
+		leagueName = leagueName.trim();
+		leagueName = leagueName.replace(" ", "-");
+		leagueName = leagueName.replace("\\.", "");
+		final int sportId = addSport(sport);
+		final int countryId = addCountry(country);
+		final String sql = "INSERT INTO League (name, sportId, countryId) VALUES (?, ?, ?) "
+				+ "ON DUPLICATE KEY UPDATE name = ?";
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			stat.setString(1, leagueName);
+			stat.setInt(2, sportId);
+			stat.setInt(3, countryId);
+			stat.setString(4, leagueName);
+
+			stat.executeUpdate();
+		}
+		return getId("League", leagueName, countryId);
+	}
+
+	public int addCountry(String name) throws SQLException {
+		name = name.replace(" ", "-");
+		name = name.replace("\\.", "");
+		final String sql = "INSERT INTO Country (name) VALUES (?) ON DUPLICATE KEY UPDATE name = ?";
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			stat.setString(1, name);
+			stat.setString(2, name);
+			stat.executeUpdate();
+		}
+
+		return getId("Country", name, -1);
+	}
+
+	public int addSport(String sport) throws SQLException {
+		sport = sport.replace(" ", "-");
+		sport = sport.replace("\\.", "");
+		final String sql = "INSERT INTO Sport (name) VALUES (?) ON DUPLICATE KEY UPDATE name = ?";
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			stat.setString(1, sport);
+			stat.setString(2, sport);
+			stat.executeUpdate();
+		}
+		return getId("Sport", sport, -1);
+	}
+
+	private int getId(String table, String name, int countryId) throws SQLException {
+		String sql = "SELECT id FROM " + table + " WHERE name = ?";
+		int id = -1;
+		if (countryId > -1) {
+			sql += " AND countryId = ?";
+		}
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			stat.setString(1, name.trim());
+			if (countryId > -1) {
+				stat.setInt(2, countryId);
+			}
+			final ResultSet insertRs = stat.executeQuery();
+			if (insertRs.next()) {
+				id = insertRs.getInt("id");
+			}
+		}
+		return id;
+	}
+
+	public int getLeagueId(int sportId, int countryId, String leagueName) throws SQLException {
+		final String sql = "SELECT id FROM League WHERE name = ? AND countryId = ? AND sportId = ?";
+		int id = -1;
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			stat.setString(1, leagueName.trim());
+			stat.setInt(2, countryId);
+			stat.setInt(3, sportId);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				id = rs.getInt("id");
+			}
+		}
+		return id;
+	}
+
+	public int getSportId(String sportName) {
+		final String sql = "SELECT id from Sport WHERE name = ?";
+		int id = 0;
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			stat.setString(1, sportName.trim());
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				id = rs.getInt("id");
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+		return id;
+	}
+
+	public int getCountryId(String country) throws SQLException {
+		final String sql = "SELECT id from Country WHERE name = ?";
+		int id = -1;
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			stat.setString(1, country.trim());
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				id = rs.getInt("id");
+			}
+		}
+		return id;
+	}
+
+	public void addResult(String tableName, LocalDateTime gameDate, String homeTeam, String awayTeam, int homeScore,
+			int awayScore, boolean overtime, float odds1, float oddsX, float odds2, int countryId, String season,
+			int leagueId, int sportId) throws SQLException {
+
+		final int homeTeamId = getOrInsertTeam(homeTeam, countryId, leagueId, sportId);
+		final int awayTeamId = getOrInsertTeam(awayTeam, countryId, leagueId, sportId);
+
+		final String selectSql = "SELECT id FROM SoccerResults WHERE homeTeamId = ? AND awayTeamId = ? AND DATE(gameDate) = ?";
+		final ResultSet rs;
+		final String date = gameDate.format(DateTimeFormatter.ISO_DATE);
+		try (PreparedStatement stat = conn.prepareStatement(selectSql)) {
+			stat.setInt(1, homeTeamId);
+			stat.setInt(2, awayTeamId);
+			stat.setString(3, date);
+
+			rs = stat.executeQuery();
+		}
+
+		int gameId = -1;
+		while (rs.next()) {
+			gameId = rs.getInt("id");
+		}
+		if (gameId != -1) {
+			final String sql = "UPDATE " + tableName
+					+ " SET homeScore = ?, awayScore = ?, overtime = ?, odds1 = ?, oddsX = ?, odds2 = ? "
+					+ "WHERE homeTeamId = ? AND awayTeamId = ? AND DATE(gameDate) = ?";
+
+			try (PreparedStatement stat = conn.prepareStatement(sql)) {
+				stat.setInt(1, homeScore);
+				stat.setInt(2, awayScore);
+				stat.setBoolean(3, overtime);
+				stat.setFloat(4, odds1);
+				stat.setFloat(5, oddsX);
+				stat.setFloat(6, odds2);
+				stat.setInt(7, homeTeamId);
+				stat.setInt(8, awayTeamId);
+				stat.setString(9, date);
+
+				stat.executeUpdate();
+			}
+
+		} else {
+			final String sql = "INSERT INTO " + tableName
+					+ " (homeTeamId, awayTeamId, homeScore, awayScore, overtime, odds1, oddsX, odds2, countryId, gameDate, season, leagueId) "
+					+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE homeScore = ?, awayScore = ?, odds1 = ?, oddsX = ?, odds2 = ?";
+			try (PreparedStatement stat = conn.prepareStatement(sql)) {
+				stat.setInt(1, homeTeamId);
+				stat.setInt(2, awayTeamId);
+				stat.setInt(3, homeScore);
+				stat.setInt(4, awayScore);
+				stat.setBoolean(5, overtime);
+				stat.setFloat(6, odds1);
+				stat.setFloat(7, oddsX);
+				stat.setFloat(8, odds2);
+				stat.setInt(9, countryId);
+				stat.setString(10, gameDate.toString());
+				stat.setString(11, season);
+				stat.setInt(12, leagueId);
+				stat.setInt(13, homeScore);
+				stat.setInt(14, awayScore);
+				stat.setFloat(15, odds1);
+				stat.setFloat(16, oddsX);
+				stat.setFloat(17, odds2);
+
+				stat.execute();
+			}
+		}
+	}
+
+	private int getOrInsertTeam(String teamName, int countryId, int leagueId, int sportId) throws SQLException {
+		teamName = teamName.replace('\u00A0', ' ').trim();
+		int teamId = getId("Team", teamName, countryId);
+		if (teamId <= 0) {
+			final String insertSql = "INSERT INTO Team (name, sportId, countryId, leagueId) VALUES (? ,? ,? ,?)";
+			try (PreparedStatement stat = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS)) {
+				stat.setString(1, teamName.trim());
+				stat.setInt(2, sportId);
+				stat.setInt(3, countryId);
+				stat.setInt(4, leagueId);
+
+				stat.executeUpdate();
+				final ResultSet generatedKeys = stat.getGeneratedKeys();
+				generatedKeys.next();
+				teamId = generatedKeys.getInt(1);
+			}
+		}
+
+		return teamId;
+	}
+
+	public void setParsingForLeague(int leagueId, int sportId, int countryId, LocalDateTime gameDate,
+			int currentParsePage, String parsedYear) {
+		final String sql = "UPDATE League SET parsedYear = ?, parsedPage = ?, lastParsedGameDate = ? WHERE sportId = ? AND countryId = ? AND id = ?";
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			stat.setString(1, parsedYear);
+			stat.setInt(2, currentParsePage);
+			stat.setString(3, gameDate.toString());
+			stat.setInt(4, sportId);
+			stat.setInt(5, countryId);
+			stat.setInt(6, leagueId);
+
+			stat.executeUpdate();
+		} catch (final SQLException e) {
+			Log.getLog().info("Failing sql: %s, %s, %s, %s, %s, %s, %s", sql, parsedYear, currentParsePage,
+					gameDate.toString(), sportId, countryId, leagueId);
+			e.printStackTrace();
+		}
+	}
+
+	public String getLastParsedYear(String leagueName, int countryId) {
+		String returnValue = "";
+
+		final String sql = "SELECT parsedYear FROM League WHERE name = ? AND countryId = ?";
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			stat.setString(1, leagueName);
+			stat.setInt(2, countryId);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue = rs.getString("parsedYear");
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+
+		return returnValue;
+	}
+
+	public Connection getDbConnection() {
+		if (conn == null) {
+			conn = getConnection();
+		}
+		return conn;
+	}
 }

+ 314 - 354
Odds/src/parser/OddsPortal.java

@@ -10,6 +10,8 @@ import java.util.Locale;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
+import org.eclipse.jetty.util.log.Log;
+
 import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
 import com.gargoylesoftware.htmlunit.WebClient;
 import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
@@ -25,358 +27,316 @@ import mysql.Mysql;
 
 public class OddsPortal implements ParserJoinedFunctions {
 
-    private LocalDateTime baseDate;
-    private int currentParsePage;
-    private int sportId;
-    private int countryId;
-    private int leagueId;
-    private LocalDateTime gameDate;
-
-    public void getYesterdaysMatches() {
-        baseDate = LocalDateTime.now().plusDays(-1);
-        final String date = LocalDate.now().plusDays(-1).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
-        getMatchesByDate(date);
-    }
-
-    public void getTodaysMatches() {
-        baseDate = LocalDateTime.now();
-        final String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
-        getMatchesByDate(date);
-    }
-
-    public void getTomorrowsMatches() {
-        baseDate = LocalDateTime.now().plusDays(1);
-        final String dateTomorrow = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
-        getMatchesByDate(dateTomorrow);
-    }
-
-    public void getNextDaysMatches() {
-        baseDate = LocalDateTime.now().plusDays(2);
-        final String dateTomorrow = LocalDate.now().plusDays(2).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
-        getMatchesByDate(dateTomorrow);
-    }
-
-    // https://stackoverflow.com/questions/14439991/skip-particular-javascript-execution-in-html-unit
-    // Skip url
-    private void getMatchesByDate(String date) {
-        final String soccerUrl = "https://oddsportal.com/matches/soccer/" + date;
-        // final String hockeyUrl = "https://oddsportal.com/matches/hockey/" + date;
-
-        final WebClient webClient = new WebClient();
-        webClient.getOptions().setUseInsecureSSL(true);
-        webClient.getOptions().setCssEnabled(false);
-        webClient.getOptions().setJavaScriptEnabled(true);
-        webClient.getOptions().setThrowExceptionOnScriptError(false);
-        Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
-
-        webClient.waitForBackgroundJavaScript(3000);
-        parseSoccerMatches(soccerUrl, webClient, date);
-
-        webClient.close();
-    }
-
-    private void parseSoccerMatches(final String soccerUrl, final WebClient webClient, String date) {
-        try {
-            System.out.println("Getting Webpage");
-            final HtmlPage soccerMatches = webClient.getPage(soccerUrl);
-            final HtmlTable matchesTable = soccerMatches.getFirstByXPath("//table[contains(@class, table-main)]");
-            final List<HtmlTableRow> rows = matchesTable.getRows();
-            String countryName = "";
-            String leagueName = "";
-            int i = 1;
-            final int size = rows.size();
-            for (final HtmlTableRow tr : rows) {
-                System.out.println("Processing " + i++ + " of " + size);
-                if (tr.getAttribute("class").equals("dark center")) {
-                    final List<HtmlAnchor> countryLeague = tr.getByXPath(".//a");
-                    countryName = countryLeague.get(0).asNormalizedText().toLowerCase().trim();
-                    leagueName = countryLeague.get(1).asNormalizedText().toLowerCase().trim();
-                    leagueName = leagueName.replaceAll(" ", "-");
-                    leagueName = leagueName.replaceAll("\\.", "");
-                    countryName = countryName.replaceAll(" ", "-");
-                    countryName = countryName.replaceAll("\\.", "");
-                } else {
-                    final List<HtmlTableCell> cells = tr.getCells();
-                    final String[] time = cells.get(0).asNormalizedText().split(":");
-                    final String[] teams = cells.get(1).asNormalizedText().split(" - ");
-                    float odds1 = 0F;
-                    float oddsX = 0F;
-                    float odds2 = 0F;
-                    int homeScore = -1;
-                    int awayScore = -1;
-                    boolean overtime = false;
-
-                    boolean abandon = false;
-
-                    try {
-                        for (final HtmlTableCell tc : cells) {
-                            if (tc.getAttribute("class").contains("live-score")) {
-                                abandon = true;
-                                break;
-                            }
-                            // Score
-                            if (tc.getAttribute("class").contains("table-score")) {
-                                final String[] scoreValue = tc.asNormalizedText().split(":");
-                                homeScore = Integer.valueOf(scoreValue[0]);
-                                if (scoreValue[1].matches("\\D+")) {
-                                    overtime = true;
-                                }
-                                awayScore = Integer.valueOf(scoreValue[1].replaceAll("\\D+", ""));
-                            }
-                            if (tc.getAttribute("class").contains("odds-nowrp")) {
-                                if (tc.asNormalizedText().matches("[+-][0-9][0-9][0-9]")) {
-                                    if (odds1 == 0F) {
-                                        odds1 = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
-                                    } else if (oddsX == 0F) {
-                                        oddsX = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
-                                    } else if (odds2 == 0F) {
-                                        odds2 = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
-                                    }
-                                } else if (tc.asNormalizedText().matches("[0-9].[0-9]+")) {
-                                    if (odds1 == 0F) {
-                                        odds1 = Float.valueOf(tc.asNormalizedText());
-                                    } else if (oddsX == 0F) {
-                                        oddsX = Float.valueOf(tc.asNormalizedText());
-                                    } else if (odds2 == 0F) {
-                                        odds2 = Float.valueOf(tc.asNormalizedText());
-                                    }
-                                }
-                            }
-
-                        }
-                    } catch (final NumberFormatException e) {
-                        System.out.println("Failed to get the match between " + teams[0].trim() + " and " + teams[1].trim()
-                                + " at " + baseDate.withHour(Integer.valueOf(time[0])).withMinute(Integer.valueOf(time[1]))
-                                + " odds1: " + odds1 + " oddsX: " + oddsX + " odds2: " + odds2 + " homeScore " + homeScore
-                                + " awayScore " + awayScore + " overtime: " + (overtime ? "true" : "false"));
-                        continue;
-                    }
-
-                    if (abandon) {
-                        continue;
-                    }
-                    final Mysql mysql = Mysql.getInstance();
-                    final int leagueId = mysql.addLeague(leagueName, countryName, "soccer");
-                    final int countryId = mysql.getCountryId(countryName);
-                    final int sportId = mysql.getSportId("soccer");
-
-                    // String season = mysql.getLastParsedYear(leagueName, countryId); // TODO This
-                    // don't work
-                    String season = String.valueOf(LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyyMMdd")).getYear());
-                    if (Strings.isNullOrEmpty(season)) {
-                        season = String.valueOf(LocalDateTime.now().getYear());
-                    }
-
-                    final LocalDateTime dt = baseDate.withHour(Integer.valueOf(time[0])).withMinute(Integer.valueOf(time[1]))
-                            .withSecond(0).withNano(0);
-                    mysql.addResult("SoccerResults",
-                            dt,
-                            teams[0].trim(),
-                            teams[1].trim(),
-                            homeScore,
-                            awayScore,
-                            overtime,
-                            odds1,
-                            oddsX,
-                            odds2,
-                            countryId,
-                            season,
-                            leagueId,
-                            sportId);
-                }
-            }
-        } catch (FailingHttpStatusCodeException | IOException e) {
-            e.printStackTrace();
-        } catch (final SQLException e) {
-            e.printStackTrace();
-        }
-    }
-
-    public void getHistoricMatches(String sport, String country, String league, String year) {
-        final String url = "https://www.oddsportal.com/";
-        final String resultsPage = "/results";
-        final WebClient webClient = new WebClient();
-        webClient.getOptions().setUseInsecureSSL(true);
-        webClient.getOptions().setCssEnabled(false);
-        webClient.getOptions().setJavaScriptEnabled(true);
-        webClient.getOptions().setThrowExceptionOnScriptError(false);
-        Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
-
-        league = league.replaceAll(" ", "-");
-        league = league.replaceAll("\\.", "");
-        country = country.replaceAll(" ", "-");
-        league = league.replaceAll("\\.", "");
-        final Mysql mysql = Mysql.getInstance();
-
-        currentParsePage = 1;
-
-        final String urlYearPart;
-        if (year.equals(String.valueOf(LocalDate.now().getYear()))) {
-            urlYearPart = "";
-        } else {
-            urlYearPart = "-" + year;
-        }
-
-        try {
-            sportId = mysql.getSportId(sport);
-            countryId = mysql.getCountryId(country);
-            leagueId = mysql.getLeagueId(sportId, countryId, league);
-            String season = "";
-
-            final HtmlPage leaguePage
-                    = webClient.getPage(url + "/" + sport + "/" + country + "/" + league + urlYearPart + resultsPage);
-            final List<HtmlAnchor> yearFilter = leaguePage.getByXPath("//ul[contains(@class,'main-filter')]//a");
-            for (final HtmlAnchor a : yearFilter) {
-                System.out.println("Year filter: " + a.getHrefAttribute());
-                final String active = ((HtmlSpan) a.getParentNode().getParentNode()).getAttribute("class");
-                if (active.contains("active") && !active.contains("inactive")) {
-                    season = a.asNormalizedText();
-                    year = season.replace('/', '-');
-                }
-            }
-
-            HtmlDivision tournamentTableDiv = leaguePage.getHtmlElementById("tournamentTable");
-            HtmlTable tournamentTable = (HtmlTable) tournamentTableDiv.getFirstChild();
-
-            gameDate = LocalDateTime.now();
-            final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH);
-            parseTournamentTable(sportId, countryId, leagueId, season, tournamentTable, gameDate, dateFormatter);
-            final HtmlDivision paginationLinksDiv = (HtmlDivision) tournamentTableDiv.getLastChild();
-            final List<HtmlAnchor> pagiantionLinks
-                    = paginationLinksDiv.getByXPath(".//a[contains(@href, 'page') and not(.//span[contains(@class, 'arrow')])]");
-            for (final HtmlAnchor a : pagiantionLinks) {
-                System.out.println("Continuing with Pagination: " + a.getHrefAttribute());
-                // When done with start page click pagiantion
-                final int parsePage = Integer.valueOf(a.getTextContent());
-                if (parsePage > currentParsePage) {
-                    a.click();
-                    webClient.waitForBackgroundJavaScript(1000);
-
-                    tournamentTableDiv = leaguePage.getHtmlElementById("tournamentTable");
-                    tournamentTable = (HtmlTable) tournamentTableDiv.getFirstChild();
-                    parseTournamentTable(sportId, countryId, leagueId, season, tournamentTable, gameDate, dateFormatter);
-                    currentParsePage = parsePage;
-                }
-                // process new tournament table content
-            }
-        } catch (FailingHttpStatusCodeException | IOException e) {
-            e.printStackTrace();
-        } catch (final SQLException sqle) {
-            sqle.printStackTrace();
-        } catch (final ClassCastException cce) {
-            System.out.println("No pagination table");
-            // cce.printStackTrace();
-        } finally {
-            Mysql.getInstance().setParsingForLeague(leagueId, sportId, countryId, gameDate, currentParsePage, year);
-        }
-        webClient.close();
-        System.out.println("DONE with " + country + " (" + countryId + ") league " + league + "(" + leagueId + ")");
-    }
-
-    private void parseTournamentTable(int sportId, int countryId, int leagueId, String season, HtmlTable tournamentTable,
-            LocalDateTime gameDate, DateTimeFormatter dateFormatter) throws SQLException {
-        for (final HtmlTableRow tr : tournamentTable.getRows()) {
-            if (tr.getAttribute("class").contains("deactivate")) {
-                String homeTeam;
-                String awayTeam;
-                int homeScore = -1;
-                int awayScore = -1;
-                float odds1 = 0f;
-                float oddsX = 0f;
-                float odds2 = 0f;
-                boolean overtime = false;
-
-                final HtmlTableCell timeCell = tr.getCell(0);
-                final HtmlTableCell participantsCell = tr.getCell(1);
-
-                // Game Time
-                final String[] timeValue = timeCell.asNormalizedText().split(":");
-                gameDate = gameDate.withHour(Integer.valueOf(timeValue[0]));
-                gameDate = gameDate.withMinute(Integer.valueOf(timeValue[1]));
-
-                // Teams
-                final String[] participantsValue = participantsCell.asNormalizedText().split(" - ");
-                homeTeam = participantsValue[0].trim();
-                awayTeam = participantsValue[1].trim();
-
-                final List<HtmlTableCell> cells = tr.getCells();
-                for (final HtmlTableCell tc : cells) {
-                    // Score
-                    if (tc.getAttribute("class").contains("table-score")) {
-                        final String[] scoreValue = tc.asNormalizedText().split(":");
-                        if (scoreValue[0].matches("\\D+")) {
-                            continue;
-                        }
-                        homeScore = Integer.valueOf(scoreValue[0]);
-                        if (scoreValue[1].matches("\\D+")) {
-                            overtime = true;
-                        }
-                        awayScore = Integer.valueOf(scoreValue[1].replaceAll("\\D+", ""));
-                    }
-
-                    if (tc.getAttribute("class").contains("odds-nowrp")) {
-                        if (tc.asNormalizedText().matches("[+-][0-9][0-9][0-9]")) {
-                            if (odds1 == 0F) {
-                                odds1 = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
-                            } else if (oddsX == 0F) {
-                                oddsX = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
-                            } else if (odds2 == 0F) {
-                                odds2 = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
-                            }
-                        } else if (tc.asNormalizedText().matches("[0-9].[0-9]+")) {
-                            if (odds1 == 0F) {
-                                odds1 = Float.valueOf(tc.asNormalizedText());
-                            } else if (oddsX == 0F) {
-                                oddsX = Float.valueOf(tc.asNormalizedText());
-                            } else if (odds2 == 0F) {
-                                odds2 = Float.valueOf(tc.asNormalizedText());
-                            }
-                        }
-                    }
-                }
-
-                if (gameDate != null && homeTeam != null && awayTeam != null && odds1 != 0 && oddsX != 0 && odds2 != 0
-                        && !Strings.isNullOrEmpty(season)) { // All set.. update sql result table
-                    System.out.println("Adding game between " + homeTeam + " and " + awayTeam + " with score " + homeScore + "-"
-                            + awayScore);
-                    Mysql.getInstance().addResult("SoccerResults",
-                            gameDate,
-                            homeTeam,
-                            awayTeam,
-                            homeScore,
-                            awayScore,
-                            overtime,
-                            odds1,
-                            oddsX,
-                            odds2,
-                            countryId,
-                            season,
-                            leagueId,
-                            sportId);
-                } else {
-                    System.out.println(String.format(
-                            "Not adding, missing somethind.. gameDate: %s, homeTeam %s, awayTeam %s, odds1 %s, oddsX %s, odds2 %s, "
-                                    + "season %s",
-                            gameDate,
-                            homeTeam,
-                            awayTeam,
-                            odds1,
-                            oddsX,
-                            odds2,
-                            season));
-                }
-
-            } else if (tr.getAttribute("class").contains("center nob-border")) { // Datum rader
-                final List<HtmlSpan> dateSpan = tr.getByXPath(".//span[contains(@class, 'datet')]");
-                final String dateString = dateSpan.get(0).asNormalizedText();
-                if (dateString.toLowerCase().contains("yesterday")) {
-                    gameDate = LocalDateTime.now().minusDays(1);
-                } else if (dateString.toLowerCase().contains("today")) {
-                    gameDate = LocalDateTime.now();
-                } else {
-                    gameDate = LocalDate.parse(dateString, dateFormatter).atStartOfDay();
-                }
-            }
-        }
-    }
+	private static final String CLASS = "class";
+	private static final String DATE_PATTERN = "yyyyMMdd";
+	private LocalDateTime baseDate;
+	private int sportId;
+	private int countryId;
+	private int leagueId;
+	private LocalDateTime gameDate;
+
+	public void getYesterdaysMatches() {
+		baseDate = LocalDateTime.now().plusDays(-1);
+		final String date = LocalDate.now().plusDays(-1).format(DateTimeFormatter.ofPattern(DATE_PATTERN));
+		getMatchesByDate(date);
+	}
+
+	public void getTodaysMatches() {
+		baseDate = LocalDateTime.now();
+		final String date = LocalDate.now().format(DateTimeFormatter.ofPattern(DATE_PATTERN));
+		getMatchesByDate(date);
+	}
+
+	public void getTomorrowsMatches() {
+		baseDate = LocalDateTime.now().plusDays(1);
+		final String dateTomorrow = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern(DATE_PATTERN));
+		getMatchesByDate(dateTomorrow);
+	}
+
+	public void getNextDaysMatches() {
+		baseDate = LocalDateTime.now().plusDays(2);
+		final String dateTomorrow = LocalDate.now().plusDays(2).format(DateTimeFormatter.ofPattern(DATE_PATTERN));
+		getMatchesByDate(dateTomorrow);
+	}
+
+	// https://stackoverflow.com/questions/14439991/skip-particular-javascript-execution-in-html-unit
+	// Skip url
+	private void getMatchesByDate(String date) {
+		final String soccerUrl = "https://oddsportal.com/matches/soccer/" + date;
+		// final String hockeyUrl = "https://oddsportal.com/matches/hockey/" + date;
+
+		final WebClient webClient = new WebClient();
+		webClient.getOptions().setUseInsecureSSL(true);
+		webClient.getOptions().setCssEnabled(false);
+		webClient.getOptions().setJavaScriptEnabled(true);
+		webClient.getOptions().setThrowExceptionOnScriptError(false);
+		Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
+
+		webClient.waitForBackgroundJavaScript(3000);
+		parseSoccerMatches(soccerUrl, webClient, date);
+
+		webClient.close();
+	}
+
+	private void parseSoccerMatches(final String soccerUrl, final WebClient webClient, String date) {
+		try {
+			final HtmlPage soccerMatches = webClient.getPage(soccerUrl);
+			final HtmlTable matchesTable = soccerMatches.getFirstByXPath("//table[contains(@class, table-main)]");
+			final List<HtmlTableRow> rows = matchesTable.getRows();
+			String countryName = "";
+			String leagueName = "";
+			int i = 1;
+			for (final HtmlTableRow tr : rows) {
+				if (tr.getAttribute(CLASS).equals("dark center")) {
+					final List<HtmlAnchor> countryLeague = tr.getByXPath(".//a");
+					countryName = countryLeague.get(0).asNormalizedText().toLowerCase().trim();
+					leagueName = countryLeague.get(1).asNormalizedText().toLowerCase().trim();
+					leagueName = leagueName.replace(" ", "-");
+					leagueName = leagueName.replace("\\.", "");
+					countryName = countryName.replace(" ", "-");
+					countryName = countryName.replace("\\.", "");
+				} else {
+					final List<HtmlTableCell> cells = tr.getCells();
+					final String[] time = cells.get(0).asNormalizedText().split(":");
+					final String[] teams = cells.get(1).asNormalizedText().split(" - ");
+					float odds1 = 0F;
+					float oddsX = 0F;
+					float odds2 = 0F;
+					int homeScore = -1;
+					int awayScore = -1;
+					boolean overtime = false;
+
+					boolean abandon = false;
+
+					try {
+						for (final HtmlTableCell tc : cells) {
+							if (tc.getAttribute(CLASS).contains("live-score")) {
+								abandon = true;
+								break;
+							}
+							// Score
+							if (tc.getAttribute(CLASS).contains("table-score")) {
+								final String[] scoreValue = tc.asNormalizedText().split(":");
+								homeScore = Integer.valueOf(scoreValue[0]);
+								if (scoreValue[1].matches("\\D+")) {
+									overtime = true;
+								}
+								awayScore = Integer.valueOf(scoreValue[1].replaceAll("\\D+", ""));
+							}
+							if (tc.getAttribute(CLASS).contains("odds-nowrp")) {
+								if (tc.asNormalizedText().matches("[+-][0-9][0-9][0-9]")) {
+									if (odds1 == 0F) {
+										odds1 = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
+									} else if (oddsX == 0F) {
+										oddsX = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
+									} else if (odds2 == 0F) {
+										odds2 = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
+									}
+								} else if (tc.asNormalizedText().matches("[0-9].[0-9]+")) {
+									if (odds1 == 0F) {
+										odds1 = Float.valueOf(tc.asNormalizedText());
+									} else if (oddsX == 0F) {
+										oddsX = Float.valueOf(tc.asNormalizedText());
+									} else if (odds2 == 0F) {
+										odds2 = Float.valueOf(tc.asNormalizedText());
+									}
+								}
+							}
+
+						}
+					} catch (final NumberFormatException e) {
+						Log.getLog().info(
+								"Failed to get the match between %s and %s at %s odds1 %s oddsX %s odds2 %s homeScore %s awayScore %s overtime %s",
+								teams[0].trim(), teams[1].trim(),
+								baseDate.withHour(Integer.valueOf(time[0])).withMinute(Integer.valueOf(time[1])), odds1,
+								oddsX, odds2, homeScore, awayScore, (overtime ? "true" : "false"));
+						continue;
+					}
+
+					if (abandon) {
+						continue;
+					}
+					final Mysql mysql = Mysql.getInstance();
+					final int leaguesId = mysql.addLeague(leagueName, countryName, "soccer");
+					final int countrysId = mysql.getCountryId(countryName);
+					final int sportsId = mysql.getSportId("soccer");
+
+					// String season = mysql.getLastParsedYear(leagueName, countryId); // TODO This
+					// don't work
+					String season = String
+							.valueOf(LocalDate.parse(date, DateTimeFormatter.ofPattern(DATE_PATTERN)).getYear());
+					if (Strings.isNullOrEmpty(season)) {
+						season = String.valueOf(LocalDateTime.now().getYear());
+					}
+
+					final LocalDateTime dt = baseDate.withHour(Integer.valueOf(time[0]))
+							.withMinute(Integer.valueOf(time[1])).withSecond(0).withNano(0);
+					mysql.addResult("SoccerResults", dt, teams[0].trim(), teams[1].trim(), homeScore, awayScore,
+							overtime, odds1, oddsX, odds2, countrysId, season, leaguesId, sportsId);
+				}
+			}
+		} catch (FailingHttpStatusCodeException | IOException | SQLException e) {
+			e.printStackTrace();
+		}
+	}
+
+	public void getHistoricMatches(String sport, String country, String league, String year) {
+		final String url = "https://www.oddsportal.com/";
+		final String resultsPage = "/results";
+		final WebClient webClient = new WebClient();
+		webClient.getOptions().setUseInsecureSSL(true);
+		webClient.getOptions().setCssEnabled(false);
+		webClient.getOptions().setJavaScriptEnabled(true);
+		webClient.getOptions().setThrowExceptionOnScriptError(false);
+		Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
+
+		league = league.replace(" ", "-");
+		league = league.replace("\\.", "");
+		country = country.replace(" ", "-");
+		league = league.replace("\\.", "");
+		final Mysql mysql = Mysql.getInstance();
+
+		int currentParsePage = 1;
+
+		final String urlYearPart;
+		if (year.equals(String.valueOf(LocalDate.now().getYear()))) {
+			urlYearPart = "";
+		} else {
+			urlYearPart = "-" + year;
+		}
+
+		try {
+			sportId = mysql.getSportId(sport);
+			countryId = mysql.getCountryId(country);
+			leagueId = mysql.getLeagueId(sportId, countryId, league);
+			String season = "";
+
+			final HtmlPage leaguePage = webClient
+					.getPage(url + "/" + sport + "/" + country + "/" + league + urlYearPart + resultsPage);
+			final List<HtmlAnchor> yearFilter = leaguePage.getByXPath("//ul[contains(@class,'main-filter')]//a");
+			for (final HtmlAnchor a : yearFilter) {
+				final String active = ((HtmlSpan) a.getParentNode().getParentNode()).getAttribute(CLASS);
+				if (active.contains("active") && !active.contains("inactive")) {
+					season = a.asNormalizedText();
+					year = season.replace('/', '-');
+				}
+			}
+
+			HtmlDivision tournamentTableDiv = leaguePage.getHtmlElementById("tournamentTable");
+			HtmlTable tournamentTable = (HtmlTable) tournamentTableDiv.getFirstChild();
+
+			gameDate = LocalDateTime.now();
+			final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH);
+			parseTournamentTable(sportId, countryId, leagueId, season, tournamentTable, gameDate, dateFormatter);
+			final HtmlDivision paginationLinksDiv = (HtmlDivision) tournamentTableDiv.getLastChild();
+			final List<HtmlAnchor> pagiantionLinks = paginationLinksDiv
+					.getByXPath(".//a[contains(@href, 'page') and not(.//span[contains(@class, 'arrow')])]");
+			for (final HtmlAnchor a : pagiantionLinks) {
+				// When done with start page click pagiantion
+				final int parsePage = Integer.parseInt(a.getTextContent());
+				if (parsePage > currentParsePage) {
+					a.click();
+					webClient.waitForBackgroundJavaScript(1000);
+
+					tournamentTableDiv = leaguePage.getHtmlElementById("tournamentTable");
+					tournamentTable = (HtmlTable) tournamentTableDiv.getFirstChild();
+					parseTournamentTable(sportId, countryId, leagueId, season, tournamentTable, gameDate,
+							dateFormatter);
+					currentParsePage = parsePage;
+				}
+				// process new tournament table content
+			}
+		} catch (FailingHttpStatusCodeException | IOException | SQLException e) {
+			e.printStackTrace();
+		} catch (final ClassCastException cce) {
+		} finally {
+			Mysql.getInstance().setParsingForLeague(leagueId, sportId, countryId, gameDate, currentParsePage, year);
+		}
+		webClient.close();
+		Log.getLog().info("DONE with " + country + " (" + countryId + ") league " + league + "(" + leagueId + ")");
+	}
+
+	private void parseTournamentTable(int sportId, int countryId, int leagueId, String season,
+			HtmlTable tournamentTable, LocalDateTime gameDate, DateTimeFormatter dateFormatter) throws SQLException {
+		for (final HtmlTableRow tr : tournamentTable.getRows()) {
+			if (tr.getAttribute(CLASS).contains("deactivate")) {
+				String homeTeam;
+				String awayTeam;
+				int homeScore = -1;
+				int awayScore = -1;
+				float odds1 = 0f;
+				float oddsX = 0f;
+				float odds2 = 0f;
+				boolean overtime = false;
+
+				final HtmlTableCell timeCell = tr.getCell(0);
+				final HtmlTableCell participantsCell = tr.getCell(1);
+
+				// Game Time
+				final String[] timeValue = timeCell.asNormalizedText().split(":");
+				if (gameDate != null) {
+					gameDate = gameDate.withHour(Integer.valueOf(timeValue[0]));
+					gameDate = gameDate.withMinute(Integer.valueOf(timeValue[1]));
+				}
+
+				// Teams
+				final String[] participantsValue = participantsCell.asNormalizedText().split(" - ");
+				homeTeam = participantsValue[0].trim();
+				awayTeam = participantsValue[1].trim();
+
+				final List<HtmlTableCell> cells = tr.getCells();
+				for (final HtmlTableCell tc : cells) {
+					// Score
+					if (tc.getAttribute(CLASS).contains("table-score")) {
+						final String[] scoreValue = tc.asNormalizedText().split(":");
+						if (scoreValue[0].matches("\\D+")) {
+							continue;
+						}
+						homeScore = Integer.valueOf(scoreValue[0]);
+						if (scoreValue[1].matches("\\D+")) {
+							overtime = true;
+						}
+						awayScore = Integer.valueOf(scoreValue[1].replaceAll("\\D+", ""));
+					}
+
+					if (tc.getAttribute(CLASS).contains("odds-nowrp")) {
+						if (tc.asNormalizedText().matches("[+-][0-9][0-9][0-9]")) {
+							if (odds1 == 0F) {
+								odds1 = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
+							} else if (oddsX == 0F) {
+								oddsX = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
+							} else if (odds2 == 0F) {
+								odds2 = convertAmericanOddsToDecimal(Integer.valueOf(tc.asNormalizedText()));
+							}
+						} else if (tc.asNormalizedText().matches("[0-9].[0-9]+")) {
+							if (odds1 == 0F) {
+								odds1 = Float.valueOf(tc.asNormalizedText());
+							} else if (oddsX == 0F) {
+								oddsX = Float.valueOf(tc.asNormalizedText());
+							} else if (odds2 == 0F) {
+								odds2 = Float.valueOf(tc.asNormalizedText());
+							}
+						}
+					}
+				}
+
+				if (gameDate != null && homeTeam != null && awayTeam != null && odds1 != 0 && oddsX != 0 && odds2 != 0
+						&& !Strings.isNullOrEmpty(season)) { // All set.. update sql result table
+					Mysql.getInstance().addResult("SoccerResults", gameDate, homeTeam, awayTeam, homeScore, awayScore,
+							overtime, odds1, oddsX, odds2, countryId, season, leagueId, sportId);
+				}
+
+			} else if (tr.getAttribute(CLASS).contains("center nob-border")) { // Datum rader
+				final List<HtmlSpan> dateSpan = tr.getByXPath(".//span[contains(@class, 'datet')]");
+				final String dateString = dateSpan.get(0).asNormalizedText();
+				if (dateString.toLowerCase().contains("yesterday")) {
+					gameDate = LocalDateTime.now().minusDays(1);
+				} else if (dateString.toLowerCase().contains("today")) {
+					gameDate = LocalDateTime.now();
+				} else {
+					gameDate = LocalDate.parse(dateString, dateFormatter).atStartOfDay();
+				}
+			}
+		}
+	}
 }