-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUrlCheckController.java
More file actions
69 lines (57 loc) · 2.54 KB
/
UrlCheckController.java
File metadata and controls
69 lines (57 loc) · 2.54 KB
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
package hexlet.code.controller;
import hexlet.code.model.Url;
import hexlet.code.model.UrlCheck;
import hexlet.code.repository.UrlCheckRepository;
import hexlet.code.repository.UrlRepository;
import hexlet.code.util.NamedRoutes;
import static hexlet.code.util.AppSettings.FLASH_TYPE;
import static hexlet.code.util.AppSettings.FLASH_DANGER;
import static hexlet.code.util.AppSettings.FLASH_SUCCESS;
import static hexlet.code.util.AppSettings.FLASH;
import static hexlet.code.util.AppSettings.CHECK_ERROR;
import static hexlet.code.util.AppSettings.PAGE_OK;
import static hexlet.code.util.AppSettings.URL_BAD;
import io.javalin.http.Context;
import io.javalin.http.NotFoundResponse;
import java.sql.SQLException;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import kong.unirest.UnirestException;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
@Slf4j
public final class UrlCheckController {
private UrlCheckController() {
// Prevent instantiation - Sonar Warning
}
public static void check(Context ctx) throws SQLException {
Long urlId = ctx.pathParamAsClass("id", Long.class).get();
Url url = UrlRepository.find(urlId)
.orElseThrow(() -> new NotFoundResponse("Entity with id = " + urlId + " not found"));
log.info("Got URL ID: {}", urlId);
try {
HttpResponse<String> response = Unirest.get(url.getName()).asString();
Document document = Jsoup.parse(response.getBody());
int statusCode = response.getStatus();
log.info("Response getStatus: {}", statusCode);
String title = document.title();
String h1 = document.select("h1").text();
String description = document.select("meta[name=description]").attr("content");
UrlCheck urlCheck = new UrlCheck(urlId, statusCode, title, h1, description);
UrlCheckRepository.save(urlCheck);
log.info("check saved");
} catch (UnirestException e) {
ctx.sessionAttribute(FLASH, URL_BAD);
ctx.sessionAttribute(FLASH_TYPE, FLASH_DANGER);
ctx.redirect(NamedRoutes.urlPath(urlId));
} catch (Exception e) {
ctx.sessionAttribute(FLASH, CHECK_ERROR + e.getMessage());
ctx.sessionAttribute(FLASH_TYPE, FLASH_DANGER);
ctx.redirect(NamedRoutes.urlPath(urlId));
}
ctx.sessionAttribute(FLASH, PAGE_OK);
ctx.sessionAttribute(FLASH_TYPE, FLASH_SUCCESS);
ctx.redirect(NamedRoutes.urlPath(urlId));
}
}