Skip to content

Commit 4636ae8

Browse files
jirka.pinkas@gmail.comjirka.pinkas@gmail.com
authored andcommitted
completely rewritten pingGoogle / pingBing methods
1 parent 8c14336 commit 4636ae8

File tree

8 files changed

+462
-122
lines changed

8 files changed

+462
-122
lines changed

README.md

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Add this library to classpath:
1212
<dependency>
1313
<groupId>cz.jiripinkas</groupId>
1414
<artifactId>jsitemapgenerator</artifactId>
15-
<version>4.2</version>
15+
<version>4.3</version>
1616
</dependency>
1717

1818
If you want to use "ping google / bing" functionality, also add this library to classpath:
@@ -91,19 +91,29 @@ String sitemap = SitemapGenerator.of("https://example.com")
9191
.toString();
9292
```
9393

94-
or to store it to file & ping google:
94+
or to store it to file & ping Google:
9595

9696
```java
97+
Ping ping = Ping.builder()
98+
.engines(Ping.SearchEngine.GOOGLE)
99+
.build();
97100
SitemapGenerator.of("https://example.com")
98101
.addPage(WebPage.builder().maxPriorityRoot().changeFreqNever().lastModNow().build())
99102
.addPage("foo.html")
100103
.addPage("bar.html")
101104
// generate sitemap and save it to file ./sitemap.xml
102105
.toFile(Paths.get("sitemap.xml"))
103106
// inform Google that this sitemap has changed
104-
.ping(SearchEngine.GOOGLE); // this requires okhttp in classpath!!!
107+
.ping(ping); // this requires okhttp in classpath!!!
108+
.callOnSuccess(() -> System.out.println("Pinged Google")) // what will happen on success
109+
.catchOnFailure(e -> System.out.println("Could not ping Google!")); // what will happen on error
105110
```
106111

112+
Note: To ping Google / Bing, you can either use built-in support (requires OkHttp in classpath!!!),
113+
or you can use your own http client implementation. Supported http clients: Custom OkHttpClient,
114+
CloseableHttpClient (Apache Http Client), RestTemplate (from Spring). To use your own http client
115+
implementation just call on PingBuilder method: httpClient*() and pass inside your implementation.
116+
107117
### How to create sitemap index:
108118

109119
```java
@@ -115,7 +125,8 @@ String sitemapIndex = SitemapIndexGenerator.of("https://javalibs.com")
115125

116126
### How to create RSS channel:
117127

118-
... RSS ISN'T sitemap :-), but it's basically just a list of links (like sitemap) and if you need sitemap, then probably you also need RSS
128+
... RSS ISN'T sitemap :-), but it's basically just a list of links (like sitemap) and if you need sitemap,
129+
then probably you also need RSS. Note: RssGenerator has lots of common methods with SitemapGenerator.
119130

120131
```java
121132
String rss = RssGenerator.of("https://topjavablogs.com", "Top Java Blogs", "Best Java Blogs")

pom.xml

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<modelVersion>4.0.0</modelVersion>
44
<groupId>cz.jiripinkas</groupId>
55
<artifactId>jsitemapgenerator</artifactId>
6-
<version>4.2</version>
6+
<version>4.3</version>
77
<packaging>jar</packaging>
88
<name>Java sitemap generator</name>
99
<description>This library generates a web sitemap and can ping Google that it has changed. This project has been
@@ -30,6 +30,8 @@
3030
<junit.version>5.5.2</junit.version>
3131
<assertj.version>3.14.0</assertj.version>
3232
<mockito.version>3.1.0</mockito.version>
33+
<spring.version>5.2.1.RELEASE</spring.version>
34+
<httpclient.version>4.5.10</httpclient.version>
3335
</properties>
3436

3537
<developers>
@@ -47,6 +49,18 @@
4749
<version>${okhttp.version}</version>
4850
<optional>true</optional>
4951
</dependency>
52+
<dependency>
53+
<groupId>org.springframework</groupId>
54+
<artifactId>spring-web</artifactId>
55+
<version>${spring.version}</version>
56+
<optional>true</optional>
57+
</dependency>
58+
<dependency>
59+
<groupId>org.apache.httpcomponents</groupId>
60+
<artifactId>httpclient</artifactId>
61+
<version>${httpclient.version}</version>
62+
<optional>true</optional>
63+
</dependency>
5064
<dependency>
5165
<groupId>org.junit.jupiter</groupId>
5266
<artifactId>junit-jupiter-api</artifactId>

src/main/java/cz/jiripinkas/jsitemapgenerator/AbstractSitemapGenerator.java

Lines changed: 99 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
11
package cz.jiripinkas.jsitemapgenerator;
22

3-
import cz.jiripinkas.jsitemapgenerator.exception.WebmasterToolsException;
43
import cz.jiripinkas.jsitemapgenerator.exception.InvalidPriorityException;
54
import cz.jiripinkas.jsitemapgenerator.exception.InvalidUrlException;
5+
import cz.jiripinkas.jsitemapgenerator.exception.WebmasterToolsException;
6+
import okhttp3.OkHttpClient;
7+
import okhttp3.Request;
8+
import okhttp3.Response;
9+
import org.apache.http.HttpEntity;
10+
import org.apache.http.client.methods.CloseableHttpResponse;
11+
import org.apache.http.client.methods.HttpGet;
12+
import org.apache.http.impl.client.CloseableHttpClient;
13+
import org.apache.http.util.EntityUtils;
14+
import org.springframework.http.ResponseEntity;
15+
import org.springframework.web.client.RestTemplate;
616

717
import java.io.*;
818
import java.net.*;
@@ -203,88 +213,76 @@ public T toFile(File parent, String child) throws IOException {
203213
}
204214

205215
/**
206-
* Ping search engine that sitemap has changed. For Google it will call this URL:
207-
* https://www.google.com/ping?sitemap=URL_Encoded_sitemapUrl
208-
*
209-
* @param searchEngines Search engines to ping
210-
* @param sitemapUrl sitemap url
211-
*/
212-
public void ping(String sitemapUrl, SearchEngine ... searchEngines) {
213-
if(searchEngines.length == 0) {
214-
throw new UnsupportedOperationException("Must provide at least one search engine!");
215-
}
216-
for (SearchEngine searchEngine : searchEngines) {
217-
ping(searchEngine.getPingUrl(), sitemapUrl, searchEngine.getPrettyName());
218-
}
219-
}
220-
221-
/**
222-
* Ping search engine that sitemap has changed. Sitemap must be on this location:
223-
* baseUrl/sitemap.xml (for example http://www.javavids.com/sitemap.xml)
224-
*
225-
* @param doNotThrowExceptionOnFailure If this is true and it's not possible to ping search engine,
226-
* this method won't throw any exception, but will return false.
227-
* @param searchEngines Search engines to ping
228-
* @return If operation succeeded
216+
* Ping search engine(s) that sitemap has changed.
217+
* @param ping Ping object
218+
* @return true if operation succeeded. If ping.isThrowExceptionOnFailure() == false and operation doesn't succeed, returns false.
229219
*/
230-
public boolean ping(boolean doNotThrowExceptionOnFailure, SearchEngine ... searchEngines) {
231-
if(searchEngines.length == 0) {
232-
throw new UnsupportedOperationException("Must provide at least one search engine!");
233-
}
220+
public PingResponse ping(Ping ping) {
234221
try {
235-
ping(searchEngines);
236-
return true;
237-
} catch (Exception e) {
238-
if (doNotThrowExceptionOnFailure) {
239-
return false;
222+
for (Ping.SearchEngine searchEngine : ping.getSearchEngines()) {
223+
String resourceUrl;
224+
if (searchEngine == Ping.SearchEngine.GOOGLE) {
225+
resourceUrl = "https://www.google.com/ping?sitemap=";
226+
} else if (searchEngine == Ping.SearchEngine.BING) {
227+
resourceUrl = "https://www.bing.com/ping?sitemap=";
228+
} else {
229+
throw new UnsupportedOperationException("Unknown search engine: " + searchEngine);
230+
}
231+
String sitemapUrl;
232+
if (ping.getSitemapUrl() == null) {
233+
sitemapUrl = getAbsoluteUrl("sitemap.xml", false);
234+
} else {
235+
sitemapUrl = getAbsoluteUrl(ping.getSitemapUrl(), false);
236+
}
237+
boolean responseIsNot200 = false;
238+
if (ping.getHttpClientType() == null) {
239+
ping(resourceUrl, sitemapUrl, searchEngine.getPrettyName());
240+
} else if(ping.getHttpClientType() == Ping.HttpClientType.REST_TEMPLATE) {
241+
String pingUrl = resourceUrl + sitemapUrl;
242+
RestTemplate restTemplate = (RestTemplate) ping.getHttpClientImplementation();
243+
ResponseEntity<String> responseEntity = restTemplate.getForEntity(pingUrl, String.class);
244+
if (responseEntity.getStatusCodeValue() != 200) {
245+
responseIsNot200 = true;
246+
}
247+
} else if(ping.getHttpClientType() == Ping.HttpClientType.OK_HTTP) {
248+
String pingUrl = resourceUrl + URLEncoder.encode(sitemapUrl, "UTF-8");
249+
OkHttpClient okHttpClient = (OkHttpClient) ping.getHttpClientImplementation();
250+
Request request = new Request.Builder().url(pingUrl).build();
251+
try (Response response = okHttpClient.newCall(request).execute()) {
252+
if (!response.isSuccessful()) {
253+
responseIsNot200 = true;
254+
}
255+
}
256+
} else if(ping.getHttpClientType() == Ping.HttpClientType.APACHE_HTTP_CLIENT) {
257+
String pingUrl = resourceUrl + URLEncoder.encode(sitemapUrl, "UTF-8");
258+
CloseableHttpClient closeableHttpClient = (CloseableHttpClient) ping.getHttpClientImplementation();
259+
HttpGet httpGet = new HttpGet(pingUrl);
260+
try (CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpGet)) {
261+
HttpEntity httpEntity = httpResponse.getEntity();
262+
EntityUtils.consume(httpEntity);
263+
if(httpResponse.getStatusLine().getStatusCode() != 200) {
264+
responseIsNot200 = true;
265+
}
266+
}
267+
} else {
268+
throw new UnsupportedOperationException("Unknown HttpClientType!");
269+
}
270+
if(responseIsNot200) {
271+
throw new WebmasterToolsException(searchEngine.getPrettyName() + " could not be informed about new sitemap! Return code != 200");
272+
}
240273
}
241-
throw e;
242-
}
243-
}
244-
245-
/**
246-
* Ping search engine that sitemap has changed. For Google it will call this URL:
247-
* https://www.google.com/ping?sitemap=URL_Encoded_sitemapUrl
248-
*
249-
* @param sitemapUrl sitemap url
250-
* @param doNotThrowExceptionOnFailure If this is true and it's not possible to ping search engine,
251-
* this method won't throw any exception, but will return false.
252-
* @param searchEngines Search engines to ping
253-
* @return If operation succeeded
254-
*/
255-
public boolean ping(String sitemapUrl, boolean doNotThrowExceptionOnFailure, SearchEngine... searchEngines) {
256-
if(searchEngines.length == 0) {
257-
throw new UnsupportedOperationException("Must provide at least one search engine!");
258-
}
259-
try {
260-
ping(sitemapUrl, searchEngines);
261-
return true;
262274
} catch (Exception e) {
263-
if (doNotThrowExceptionOnFailure) {
264-
return false;
265-
}
266-
throw e;
275+
return new PingResponse(true, new WebmasterToolsException(e));
267276
}
268-
}
269-
270-
/**
271-
* Ping search engine that sitemap has changed. Sitemap must be on this location:
272-
* baseUrl/sitemap.xml (for example http://www.javavids.com/sitemap.xml)
273-
* @param searchEngines Search engines to ping
274-
*/
275-
public void ping(SearchEngine ... searchEngines) {
276-
if(searchEngines.length == 0) {
277-
throw new UnsupportedOperationException("Must provide at least one search engine!");
278-
}
279-
ping(baseUrl + "sitemap.xml", searchEngines);
277+
return new PingResponse(false);
280278
}
281279

282280
/**
283281
* Ping Google that sitemap has changed. Will call this URL:
284282
* https://www.google.com/ping?sitemap=URL_Encoded_sitemapUrl
285283
*
286284
* @param sitemapUrl sitemap url
287-
* @deprecated Use {@link #ping(String, SearchEngine...)}
285+
* @deprecated Use {@link #ping(Ping)}
288286
*/
289287
@Deprecated
290288
public void pingGoogle(String sitemapUrl) {
@@ -299,7 +297,7 @@ public void pingGoogle(String sitemapUrl) {
299297
* @param doNotThrowExceptionOnFailure If this is true and it's not possible to ping google,
300298
* this method won't throw any exception, but will return false.
301299
* @return If operation succeeded
302-
* @deprecated Use {@link #ping(String, boolean, SearchEngine...)}
300+
* @deprecated Use {@link #ping(Ping)}
303301
*/
304302
@Deprecated
305303
public boolean pingGoogle(String sitemapUrl, boolean doNotThrowExceptionOnFailure) {
@@ -319,7 +317,7 @@ public boolean pingGoogle(String sitemapUrl, boolean doNotThrowExceptionOnFailur
319317
* https://www.bing.com/ping?sitemap=URL_Encoded_sitemapUrl
320318
*
321319
* @param sitemapUrl sitemap url
322-
* @deprecated Use {@link #ping(String, SearchEngine...)}
320+
* @deprecated Use {@link #ping(Ping)}
323321
*/
324322
@Deprecated
325323
public void pingBing(String sitemapUrl) {
@@ -334,7 +332,7 @@ public void pingBing(String sitemapUrl) {
334332
* @param doNotThrowExceptionOnFailure If this is true and it's not possible to ping google,
335333
* this method won't throw any exception, but will return false.
336334
* @return If operation succeeded
337-
* @deprecated Use {@link #ping(String, boolean, SearchEngine...)}
335+
* @deprecated Use {@link #ping(Ping)}
338336
*/
339337
@Deprecated
340338
public boolean pingBing(String sitemapUrl, boolean doNotThrowExceptionOnFailure) {
@@ -353,7 +351,7 @@ public boolean pingBing(String sitemapUrl, boolean doNotThrowExceptionOnFailure)
353351
* Ping Google that sitemap has changed. Sitemap must be on this location:
354352
* baseUrl/sitemap.xml (for example http://www.javavids.com/sitemap.xml)
355353
*
356-
* @deprecated Use {@link #ping(SearchEngine...)}
354+
* @deprecated Use {@link #ping(Ping)}
357355
*/
358356
@Deprecated
359357
public void pingGoogle() {
@@ -367,7 +365,7 @@ public void pingGoogle() {
367365
* @param doNotThrowExceptionOnFailure If this is true and it's not possible to ping google,
368366
* this method won't throw any exception, but will return false.
369367
* @return If operation succeeded
370-
* @deprecated Use {@link #ping(boolean, SearchEngine...)}
368+
* @deprecated Use {@link #ping(Ping)}
371369
*/
372370
@Deprecated
373371
public boolean pingGoogle(boolean doNotThrowExceptionOnFailure) {
@@ -386,7 +384,7 @@ public boolean pingGoogle(boolean doNotThrowExceptionOnFailure) {
386384
* Ping Google that sitemap has changed. Sitemap must be on this location:
387385
* baseUrl/sitemap.xml (for example http://www.javavids.com/sitemap.xml)
388386
*
389-
* @deprecated Use {@link #ping(SearchEngine...)}
387+
* @deprecated Use {@link #ping(Ping)}
390388
*/
391389
@Deprecated
392390
public void pingBing() {
@@ -400,7 +398,7 @@ public void pingBing() {
400398
* @param doNotThrowExceptionOnFailure If this is true and it's not possible to ping google,
401399
* this method won't throw any exception, but will return false.
402400
* @return If operation succeeded
403-
* @deprecated Use {@link #ping(boolean, SearchEngine...)}
401+
* @deprecated Use {@link #ping(Ping)}
404402
*/
405403
@Deprecated
406404
public boolean pingBing(boolean doNotThrowExceptionOnFailure) {
@@ -421,10 +419,10 @@ private void ping(String resourceUrl, String sitemapUrl, String serviceName) {
421419
// ping Google / Bing
422420
int returnCode = httpClient.get(pingUrl);
423421
if (returnCode != 200) {
424-
throw new WebmasterToolsException(serviceName + " could not be informed about new sitemap!");
422+
throw new WebmasterToolsException(serviceName + " could not be informed about new sitemap! Return code != 200");
425423
}
426424
} catch (Exception ex) {
427-
throw new WebmasterToolsException(serviceName + " could not be informed about new sitemap!");
425+
throw new WebmasterToolsException(serviceName + " could not be informed about new sitemap!", ex);
428426
}
429427
}
430428

@@ -675,13 +673,32 @@ public void setHttpClient(HttpClient httpClient) {
675673
* Get absolute URL:
676674
* If webPageName is null, return baseUrl.
677675
* If webPageName is not null, check if webPageName is absolute (can be URL from CDN) or relative URL.
678-
* If it's relative URL, prepend baseUrl and return result
676+
* If it's relative URL, prepend baseUrl and return result.
677+
* This method escapes webPageName's special characters, thus it must not be called for ping Google / Bing functionality!
679678
*
680679
* @param webPageName WebPageName
681680
* @return Correct URL
682681
*/
683682
protected String getAbsoluteUrl(String webPageName) {
684-
webPageName = UrlUtil.escapeXmlSpecialCharacters(webPageName);
683+
return getAbsoluteUrl(webPageName, true);
684+
}
685+
686+
/**
687+
* Get absolute URL:
688+
* If webPageName is null, return baseUrl.
689+
* If webPageName is not null, check if webPageName is absolute (can be URL from CDN) or relative URL.
690+
* If it's relative URL, prepend baseUrl and return result
691+
*
692+
* @param webPageName WebPageName
693+
* @param escapeSpecialCharacters Escape special characters?
694+
* Special characters must be escaped if the URL will be stored to sitemap.
695+
* If this method is called for ping Google / Bing functionality, special characters must not be escaped.
696+
* @return Correct URL
697+
*/
698+
protected String getAbsoluteUrl(String webPageName, boolean escapeSpecialCharacters) {
699+
if(escapeSpecialCharacters) {
700+
webPageName = UrlUtil.escapeXmlSpecialCharacters(webPageName);
701+
}
685702
try {
686703
String resultString;
687704
if (webPageName != null) {

0 commit comments

Comments
 (0)