Skip to content

Commit f6f4e0f

Browse files
committed
Added theme page
1 parent 81dba62 commit f6f4e0f

18 files changed

Lines changed: 545 additions & 4 deletions
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package com.stubbornjava.webapp;
2+
3+
import static com.stubbornjava.common.undertow.handlers.CustomHandlers.timed;
4+
5+
import org.slf4j.Logger;
6+
import org.slf4j.LoggerFactory;
7+
8+
import com.stubbornjava.HelperRoutes;
9+
import com.stubbornjava.PageRoutes;
10+
import com.stubbornjava.common.undertow.SimpleServer;
11+
import com.stubbornjava.common.undertow.handlers.CustomHandlers;
12+
import com.stubbornjava.guide.GuideRoutes;
13+
import com.stubbornjava.post.JavaLibRoutes;
14+
import com.stubbornjava.post.PostRoutes;
15+
import com.stubbornjava.undertow.handlers.MiddlewareBuilder;
16+
import com.stubbornjava.webapp.themes.ThemeRoutes;
17+
18+
import io.undertow.server.HttpHandler;
19+
import io.undertow.server.RoutingHandler;
20+
import io.undertow.server.handlers.BlockingHandler;
21+
import io.undertow.server.handlers.PathHandler;
22+
23+
public class StubbornJavaWebApp {
24+
private static final Logger logger = LoggerFactory.getLogger(StubbornJavaWebApp.class);
25+
26+
private static HttpHandler exceptionHandler(HttpHandler next) {
27+
return CustomHandlers.exception(next)
28+
// .addExceptionHandler(ResponseException.NotFound.class, HelperRoutes::notFound)
29+
.addExceptionHandler(Throwable.class, PageRoutes::error);
30+
}
31+
32+
private static HttpHandler wrapWithMiddleware(HttpHandler handler) {
33+
return MiddlewareBuilder.begin(PageRoutes::redirector)
34+
.next(BlockingHandler::new)
35+
.next(CustomHandlers::gzip)
36+
.next(ex -> CustomHandlers.accessLog(ex, logger))
37+
.next(CustomHandlers::statusCodeMetrics)
38+
.next(StubbornJavaWebApp::exceptionHandler)
39+
.complete(handler);
40+
}
41+
42+
// These routes do not require any authentication
43+
private static final HttpHandler basicRoutes = new RoutingHandler()
44+
.get("/", timed("getHome", PageRoutes::home))
45+
.get("/ping", timed("ping", PageRoutes::ping))
46+
47+
.get("/favicon.ico", timed("favicon", CustomHandlers.resource("images/")))
48+
.get("robots.txt", timed("robots", PageRoutes::robots))
49+
50+
.get("/posts/{slug}", timed("getPost", PostRoutes::getPost))
51+
52+
.get("/tags/{tag}/posts", timed("getRecentPostsWithTag", PostRoutes::recentPostsWithTag))
53+
54+
.get("/java-libraries", timed("getJavaLibraries", JavaLibRoutes::listLibraries))
55+
.get("/java-libraries/{library}", timed("getLibrary", JavaLibRoutes::getLibrary))
56+
.get("/libraries/{library}/posts", timed("getLibraryRedirect", JavaLibRoutes::getLibraryRedirect))
57+
58+
.get("/guides/{slug}", timed("getGuide", GuideRoutes::getGuide))
59+
60+
.get("/best-selling-html-css-themes-and-website-templates", timed("popularThemes", ThemeRoutes::popularThemes))
61+
62+
.get("/dev/metrics", timed("getMetrics", HelperRoutes::getMetrics))
63+
64+
.setFallbackHandler(timed("notFound", PageRoutes::notFound))
65+
;
66+
67+
private static final HttpHandler staticRoutes = new PathHandler(basicRoutes)
68+
.addPrefixPath("/css", timed("getCss", CustomHandlers.resource("css/")))
69+
.addPrefixPath("/js", timed("getJs", CustomHandlers.resource("js/")))
70+
.addPrefixPath("/assets/fonts", timed("getJs", CustomHandlers.resource("fonts/")))
71+
.addPrefixPath("/images", timed("getImages", CustomHandlers.resource("images/")))
72+
;
73+
74+
private static void startServer() {
75+
SimpleServer server = SimpleServer.simpleServer(wrapWithMiddleware(staticRoutes));
76+
server.start();
77+
}
78+
79+
public static void main(String[] args) {
80+
startServer();
81+
}
82+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.stubbornjava.webapp.themes;
2+
3+
import java.util.List;
4+
import java.util.Optional;
5+
6+
import org.jooq.lambda.Seq;
7+
import org.jsoup.Jsoup;
8+
import org.jsoup.nodes.Element;
9+
import org.jsoup.select.Elements;
10+
import org.slf4j.Logger;
11+
import org.slf4j.LoggerFactory;
12+
13+
import com.google.common.base.Strings;
14+
import com.stubbornjava.common.HttpClient;
15+
import com.stubbornjava.common.Json;
16+
import com.stubbornjava.common.Retry;
17+
18+
import okhttp3.HttpUrl;
19+
import okhttp3.OkHttpClient;
20+
import okhttp3.Request;
21+
22+
public class BootstrapBayScraper {
23+
private static final Logger log = LoggerFactory.getLogger(BootstrapBayScraper.class);
24+
private static final String affilaiteCode = "stubbornjava";
25+
private static final String HOST = "http://bootstrapbay.com";
26+
private static final String POPULAR_THEMES_URL =
27+
"http://bootstrapbay.com/themes?sort=sales";
28+
private static final OkHttpClient client = HttpClient.globalClient();
29+
30+
public static List<HtmlCssTheme> popularThemes() {
31+
HttpUrl url = HttpUrl.parse(POPULAR_THEMES_URL);
32+
Request request = new Request.Builder().url(url).get().build();
33+
String html = Retry.retryUntilSuccessfulWithBackoff(
34+
() -> client.newCall(request).execute()
35+
);
36+
37+
Elements elements = Jsoup.parse(html).select(".item");
38+
List<HtmlCssTheme> themes = Seq.seq(elements).map(BootstrapBayScraper::themeFromElement).toList();
39+
40+
return themes;
41+
}
42+
43+
private static HtmlCssTheme themeFromElement(Element element) {
44+
Element titleElement = element.select(".title a").first();
45+
String title = titleElement.text();
46+
String url = HttpUrl.parse(HOST + titleElement.attr("href"))
47+
.newBuilder()
48+
.addQueryParameter("ref", affilaiteCode)
49+
.build().toString();
50+
String imageUrl = HOST + element.select(".imgWrap img").attr("src");
51+
int downloads = Optional.of(element.select(".sales").text())
52+
.filter(val -> !Strings.isNullOrEmpty(val))
53+
.map(val -> val.replace(" sales", ""))
54+
.map(Integer::parseInt)
55+
.orElse(0);
56+
return new HtmlCssTheme(title, url, imageUrl, downloads);
57+
}
58+
59+
public static void main(String[] args) {
60+
List<HtmlCssTheme> themes = popularThemes();
61+
log.debug(Json.serializer().toPrettyString(themes));
62+
}
63+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.stubbornjava.webapp.themes;
2+
3+
public class HtmlCssTheme {
4+
private final String title;
5+
private final String url;
6+
private final String imageUrl;
7+
private final int downloads;
8+
public HtmlCssTheme(String title, String url, String imageUrl, int downloads) {
9+
super();
10+
this.title = title;
11+
this.url = url;
12+
this.imageUrl = imageUrl;
13+
this.downloads = downloads;
14+
}
15+
public String getTitle() {
16+
return title;
17+
}
18+
public String getUrl() {
19+
return url;
20+
}
21+
public String getImageUrl() {
22+
return imageUrl;
23+
}
24+
public int getDownloads() {
25+
return downloads;
26+
}
27+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.stubbornjava.webapp.themes;
2+
3+
import java.util.List;
4+
5+
import org.jooq.lambda.Seq;
6+
import org.jsoup.Jsoup;
7+
import org.jsoup.nodes.Element;
8+
import org.jsoup.select.Elements;
9+
import org.slf4j.Logger;
10+
import org.slf4j.LoggerFactory;
11+
12+
import com.stubbornjava.common.HttpClient;
13+
import com.stubbornjava.common.Json;
14+
import com.stubbornjava.common.Retry;
15+
16+
import okhttp3.HttpUrl;
17+
import okhttp3.OkHttpClient;
18+
import okhttp3.Request;
19+
20+
public class TemplateMonsterScraper {
21+
private static final Logger log = LoggerFactory.getLogger(TemplateMonsterScraper.class);
22+
private static final String affilaiteCode = "stubbornjava";
23+
private static final String HOST = "https://www.templatemonster.com";
24+
private static final String POPULAR_THEMES_URL =
25+
"https://www.templatemonster.com/best-selling-website-templates/";
26+
private static final OkHttpClient client = HttpClient.globalClient();
27+
28+
public static List<HtmlCssTheme> popularThemes() {
29+
HttpUrl url = HttpUrl.parse(POPULAR_THEMES_URL);
30+
Request request = new Request.Builder().url(url).get().build();
31+
String html = Retry.retryUntilSuccessfulWithBackoff(
32+
() -> client.newCall(request).execute()
33+
);
34+
35+
Elements elements = Jsoup.parse(html).select("#products .thumbnail");
36+
List<HtmlCssTheme> themes = Seq.seq(elements).map(TemplateMonsterScraper::themeFromElement).toList();
37+
38+
return themes;
39+
}
40+
41+
private static HtmlCssTheme themeFromElement(Element element) {
42+
String title = element.select(".small-prev-data h3").text();
43+
String url = HttpUrl.parse(element.select(".small-prev-data a").attr("href"))
44+
.newBuilder()
45+
.addQueryParameter("aff", affilaiteCode)
46+
.build().toString();
47+
String imageUrl = element.select(".thumbnail-preview link").attr("href");
48+
int downloads = 0;
49+
return new HtmlCssTheme(title, url, imageUrl, downloads);
50+
}
51+
52+
public static void main(String[] args) {
53+
List<HtmlCssTheme> themes = popularThemes();
54+
log.debug(Json.serializer().toPrettyString(themes));
55+
}
56+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.stubbornjava.webapp.themes;
2+
3+
import java.util.List;
4+
import java.util.Optional;
5+
6+
import org.jooq.lambda.Seq;
7+
import org.jsoup.Jsoup;
8+
import org.jsoup.nodes.Element;
9+
import org.jsoup.select.Elements;
10+
import org.slf4j.Logger;
11+
import org.slf4j.LoggerFactory;
12+
13+
import com.google.common.base.Strings;
14+
import com.stubbornjava.common.HttpClient;
15+
import com.stubbornjava.common.Json;
16+
import com.stubbornjava.common.Retry;
17+
18+
import okhttp3.HttpUrl;
19+
import okhttp3.OkHttpClient;
20+
import okhttp3.Request;
21+
22+
public class ThemeForestScraper {
23+
private static final Logger log = LoggerFactory.getLogger(ThemeForestScraper.class);
24+
private static final String affilaiteCode = "StubbornJava";
25+
private static final String HOST = "https://themeforest.net";
26+
private static final String POPULAR_THEMES_URL =
27+
"https://themeforest.net/category/site-templates?view=list&sort=sales";
28+
// They have an issue with the SSL cert that Java can't recognize automatically.
29+
// Too lazy to set up in the trusted key store.
30+
private static final OkHttpClient client = HttpClient.trustAllSslClient(HttpClient.globalClient());
31+
32+
public static List<HtmlCssTheme> popularThemes() {
33+
HttpUrl url = HttpUrl.parse(POPULAR_THEMES_URL);
34+
Request request = new Request.Builder().url(url).get().build();
35+
String html = Retry.retryUntilSuccessfulWithBackoff(
36+
() -> client.newCall(request).execute()
37+
);
38+
39+
Elements elements = Jsoup.parse(html).select(".product-list__column-detail");
40+
List<HtmlCssTheme> themes = Seq.seq(elements).map(ThemeForestScraper::themeFromElement).toList();
41+
42+
return themes;
43+
}
44+
45+
private static HtmlCssTheme themeFromElement(Element element) {
46+
Element titleElement = element.select(".product-list__heading a").first();
47+
String title = titleElement.text();
48+
String url = HttpUrl.parse(HOST + titleElement.attr("href"))
49+
.newBuilder()
50+
.addQueryParameter("ref", affilaiteCode)
51+
.build().toString();
52+
String imageUrl = element.select(".item-thumbnail__image img").attr("data-preview-url");
53+
int downloads = Optional.of(element.select(".product-list__info-sale").text())
54+
.filter(val -> !Strings.isNullOrEmpty(val))
55+
.map(val -> val.replace(" Sales", ""))
56+
.map(Integer::parseInt)
57+
.orElse(0);
58+
return new HtmlCssTheme(title, url, imageUrl, downloads);
59+
}
60+
61+
public static void main(String[] args) {
62+
List<HtmlCssTheme> themes = popularThemes();
63+
log.debug(Json.serializer().toPrettyString(themes));
64+
}
65+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.stubbornjava.webapp.themes;
2+
3+
import java.time.LocalDate;
4+
import java.util.List;
5+
6+
import com.stubbornjava.Response;
7+
import com.stubbornjava.common.undertow.Exchange;
8+
9+
import io.undertow.server.HttpServerExchange;
10+
11+
public class ThemeRoutes {
12+
13+
public static void popularThemes(HttpServerExchange exchange) {
14+
List<HtmlCssTheme> themes = Themes.getPopularThemes(96);
15+
int year = LocalDate.now().getYear();
16+
Response response = Response.fromExchange(exchange)
17+
.with("year", year)
18+
.with("themes", themes)
19+
.withLibCounts()
20+
.withRecentPosts();
21+
Exchange.body().sendHtmlTemplate(exchange, "templates/src/pages/popular-themes", response);
22+
}
23+
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package com.stubbornjava.webapp.themes;
2+
3+
import java.util.Comparator;
4+
import java.util.List;
5+
import java.util.concurrent.TimeUnit;
6+
import java.util.function.Supplier;
7+
8+
import org.jooq.lambda.Seq;
9+
import org.slf4j.Logger;
10+
import org.slf4j.LoggerFactory;
11+
12+
import com.google.common.base.Suppliers;
13+
import com.google.common.collect.Lists;
14+
import com.stubbornjava.common.Json;
15+
16+
// {{start:themes}}
17+
public class Themes {
18+
private static final Logger log = LoggerFactory.getLogger(Themes.class);
19+
private Themes() {}
20+
21+
// A list of all the theme websites we currently support.
22+
private static List<Supplier<List<HtmlCssTheme>>> suppliers = Lists.newArrayList(
23+
BootstrapBayScraper::popularThemes,
24+
TemplateMonsterScraper::popularThemes,
25+
ThemeForestScraper::popularThemes,
26+
WrapBootstrapScraper::popularThemes
27+
);
28+
29+
// Sort by downloads desc then by name.
30+
private static final Comparator<HtmlCssTheme> popularSort =
31+
Comparator.comparing(HtmlCssTheme::getDownloads).reversed()
32+
.thenComparing(HtmlCssTheme::getTitle);
33+
34+
// Fetch all themes and sort them together.
35+
private static final List<HtmlCssTheme> fetchPopularThemes() {
36+
return Seq.seq(suppliers)
37+
.map(sup -> {
38+
try {
39+
return sup.get();
40+
} catch (Exception ex) {
41+
log.warn("Error fetching themes", ex);
42+
return Lists.<HtmlCssTheme>newArrayList();
43+
}
44+
})
45+
.flatMap(List::stream)
46+
.sorted(popularSort)
47+
.toList();
48+
}
49+
50+
/*
51+
* Fetch all themes and cache for 4 hours. It takes a little time
52+
* to scrape all the sites. We also want to be nice and not spam the sites.
53+
*/
54+
private static final Supplier<List<HtmlCssTheme>> themesSupplier =
55+
Suppliers.memoizeWithExpiration(Themes::fetchPopularThemes, 4L, TimeUnit.HOURS);
56+
57+
public static List<HtmlCssTheme> getPopularThemes(int num) {
58+
return Seq.seq(themesSupplier.get()).limit(num).toList();
59+
}
60+
61+
public static void main(String[] args) {
62+
List<HtmlCssTheme> themes = getPopularThemes(50);
63+
log.debug(Json.serializer().toPrettyString(themes));
64+
}
65+
}
66+
// {{end:themes}}

0 commit comments

Comments
 (0)