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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
| package com.kom1rok.pronobot.parser;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import org.jsoup.Connection;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.nodes.Document;
public abstract class AbstractParser {
private static int RETRY_LIMIT = 3;
protected Map<String,String> COOKIES;
private DateFormat siteDateFormat;
private DateFormat frenchDateFormat;
public AbstractParser() {
COOKIES = new HashMap<String, String>();
trustEveryone();
siteDateFormat = new SimpleDateFormat(getDateSitePattern());
frenchDateFormat = new SimpleDateFormat("dd-MM-yyyy");
}
/**
* Work done in the specific parser
* @param date
* @return pronostics for the given date
*/
protected abstract void fillPronoList(Calendar date, List<String> results);
/**
* Defines the pattern of date on the web site
* @return
*/
protected abstract String getDateSitePattern();
/**
* Url used for the login on given web site
* @return
*/
protected abstract String getLoginUrl();
/**
* Cookies's names
* @return
*/
protected abstract String[] getCookiesNames();
/**
* Retrieve the session's cookie in order to be logged on the web site.
* @return
*/
protected void getConnectionCookie(String username, String password) {
// Do nothing if it's not necessary
if(getLoginUrl() == null || getCookiesNames() == null) {
return;
}
System.out.println("Get cookie from URL : " + getLoginUrl());
try {
Connection.Response res = Jsoup.connect(getLoginUrl())
.data("login", username, "password", password)
.method(Method.POST)
.userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36")
.timeout(15 * 1000)
.execute();
for(String cookieName : getCookiesNames()) {
COOKIES.put(cookieName, res.cookie(cookieName));
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Ignore all SSL certificates so the https links can be read.
*/
private void trustEveryone() {
try {
HttpsURLConnection
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname,
SSLSession session) {
return true;
}
});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} catch (Exception e) {
// should never happen
e.printStackTrace();
}
}
/**
* Retrieve a document for a given url.
* @param url
* @return
*/
protected final Document getDocument(String url) {
return getDocument(url, null);
}
/**
* Retrieve a document for a given url.
* @param url
* @return
* @throws Exception
*/
protected final Document getDocument(String url, Map<String, String> cookie) {
Document doc = null;
int nbTry = 0;
if(url == null) { return null; }
while(doc == null && nbTry < RETRY_LIMIT) {
try {
Connection connection = Jsoup.connect(url).referrer(url).timeout(15 * 1000);
// Add cookies if given
if(cookie != null) {
connection = connection.cookies(cookie);
}
doc = connection.get();
} catch (HttpStatusException e) {
System.out.println("HttpStatusException catched, waiting 20sec and retry");
} catch (SocketTimeoutException e) {
// Retry at the end of this method
System.out.println("Time out catched, waiting 20sec and retry");
} catch (IOException e) {
System.out.println("An exception occured while accessing to url : " + url + " - " + e.toString());
}
if(doc == null) {
try {
System.out.println("Doc is null, waiting 20sec and retry");
nbTry++;
System.out.println("Try number " + nbTry);
Thread.sleep(20 * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
return doc;
}
/**
* Entry point of the parser.
* This method permits to retrieve the pronostics for the given date by using the parser.
* @param date
* @return
* @throws Exception
*/
public String getPronosticForDate(Calendar date) throws Exception {
List<String> pronos = new ArrayList<String>();
fillPronoList(date, pronos); // get pronostics from given url
return generateRow(getDateInFrenchFormat(date), pronos);
}
/**
* generate a String from the date and given pronostics
* @param date
* @param pronos
* @return
*/
private final String generateRow(String date, List<String> pronos) {
StringBuilder result = new StringBuilder();
result.append(date).append('\t');
if(pronos != null && !pronos.isEmpty()) {
// the list contains the four first pronostics of the course
Iterator<String> it = pronos.iterator();
while(it.hasNext()) {
result.append(it.next());
if(it.hasNext()) {
result.append('\t');
}
}
}
result.append('\n');
System.out.println(result.toString());
return result.toString();
}
protected String getDateInSiteFormat(Calendar date) {
return siteDateFormat.format(date.getTime());
}
protected String getDateInFrenchFormat(Calendar date) {
return frenchDateFormat.format(date.getTime());
}
} |
Partager