minor improvements
Signed-off-by: Stephan Richter <s.richter@srsoftware.de>
This commit is contained in:
@@ -11,8 +11,6 @@ spotless {
|
||||
target("**/src/**/java/**/*.java")
|
||||
removeUnusedImports()
|
||||
importOrder()
|
||||
//cleanthat()
|
||||
clangFormat("18.1.8").style("file:config/clang-format")
|
||||
licenseHeader("/* © SRSoftware 2024 */")
|
||||
toggleOffOn()
|
||||
}
|
||||
|
||||
@@ -30,21 +30,18 @@ public interface Appointment {
|
||||
*/
|
||||
String description();
|
||||
|
||||
|
||||
/**
|
||||
* The date and time when the appointment is scheduled to end
|
||||
* @return an optionals LocalDateTime
|
||||
*/
|
||||
Optional<LocalDateTime> end();
|
||||
|
||||
|
||||
/**
|
||||
* represent this event as ical entry
|
||||
* @return the ical string
|
||||
*/
|
||||
String ical();
|
||||
|
||||
|
||||
/**
|
||||
* ID of the appointment – unique within this system
|
||||
* @return the appointment`s id
|
||||
@@ -75,14 +72,12 @@ public interface Appointment {
|
||||
*/
|
||||
LocalDateTime start();
|
||||
|
||||
|
||||
/**
|
||||
* tags i.e. keywords may be used to filter appointments
|
||||
* @return the set of tags associated with the current appointment
|
||||
*/
|
||||
Set<String> tags();
|
||||
|
||||
|
||||
/**
|
||||
* the title of the appointment
|
||||
* @return the title
|
||||
|
||||
@@ -60,7 +60,6 @@ public class Application {
|
||||
|
||||
server.start();
|
||||
// TODO: schedule imports
|
||||
// TODO: update URL, when tags are selected
|
||||
// TODO: allow list start time as URL param
|
||||
// TODO: provide ICAL and WEBDAV links
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ public class BaseAppointment implements Appointment {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String ical() {
|
||||
public String ical() { // TODO: implement
|
||||
return "converting event (%s) to ical not implemented".formatted(title);
|
||||
}
|
||||
|
||||
@@ -199,4 +199,4 @@ public class BaseAppointment implements Appointment {
|
||||
public Set<Link> links() {
|
||||
return links;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +58,6 @@ public abstract class BaseImporter implements Importer {
|
||||
return extractDescriptionTag(eventTag);
|
||||
}
|
||||
|
||||
|
||||
protected Result<String> extractDescription(Tag eventTag) {
|
||||
Result<Tag> titleTag = extractDescriptionTag(eventTag);
|
||||
if (titleTag.optional().isEmpty()) return transform(titleTag);
|
||||
@@ -73,7 +72,6 @@ public abstract class BaseImporter implements Importer {
|
||||
return error("not implemented");
|
||||
}
|
||||
|
||||
|
||||
protected Result<LocalDateTime> extractEnd(Tag eventTag) {
|
||||
Result<Tag> endTag = extractEndTag(eventTag);
|
||||
if (endTag.optional().isEmpty()) return transform(endTag);
|
||||
@@ -114,79 +112,75 @@ public abstract class BaseImporter implements Importer {
|
||||
return Payload.of(event);
|
||||
}
|
||||
|
||||
|
||||
private Result<Appointment> extractEvent(Result<Tag> domResult, Link eventPage) {
|
||||
return switch (domResult) {
|
||||
case Payload<Tag> payload -> extractEvent(payload.get(), eventPage);
|
||||
case Error<Tag> err -> err.transform();
|
||||
default -> invalidParameter(domResult);
|
||||
};
|
||||
}
|
||||
case Payload<Tag> payload -> extractEvent(payload.get(), eventPage);
|
||||
case Error<Tag> err -> err.transform();
|
||||
default -> invalidParameter(domResult);
|
||||
};
|
||||
}
|
||||
|
||||
protected abstract Result<Tag> extractEventTag(Result<Tag> pageResult);
|
||||
protected abstract Result<Tag> extractEventTag(Result<Tag> pageResult);
|
||||
|
||||
protected abstract Result<List<String>> extractEventUrls(Result<Tag> programPage);
|
||||
protected abstract Result<List<String>> extractEventUrls(Result<Tag> programPage);
|
||||
|
||||
protected List<Link> extractLinks(Tag appointmentTag) {
|
||||
var links = new ArrayList<Link>();
|
||||
|
||||
protected List<Link> extractLinks(Tag appointmentTag) {
|
||||
var links = new ArrayList<Link>();
|
||||
extractLinksTag(appointmentTag) //
|
||||
.map(this::extractLinkAnchors)
|
||||
.optional()
|
||||
.stream()
|
||||
.flatMap(List::stream)
|
||||
.forEach(anchor -> {
|
||||
var href = anchor.get("href");
|
||||
if (href == null) return;
|
||||
if (!href.contains("://")) href = baseUrl() + href;
|
||||
var text = anchor.inner(0).orElse(href);
|
||||
Payload //
|
||||
.of(href)
|
||||
.map(BaseImporter::url)
|
||||
.map(url -> link(url, text))
|
||||
.optional()
|
||||
.ifPresent(links::add);
|
||||
});
|
||||
return links;
|
||||
}
|
||||
|
||||
extractLinksTag(appointmentTag) //
|
||||
.map(this::extractLinkAnchors)
|
||||
.optional()
|
||||
.stream()
|
||||
.flatMap(List::stream).forEach(anchor -> {
|
||||
var href = anchor.get("href");
|
||||
if (href == null) return;
|
||||
if (!href.contains("://")) href = baseUrl() + href;
|
||||
var text = anchor.inner(0).orElse(href);
|
||||
Payload //
|
||||
.of(href)
|
||||
.map(BaseImporter::url)
|
||||
.map(url -> link(url,text))
|
||||
.optional()
|
||||
.ifPresent(links::add);
|
||||
});
|
||||
return links;
|
||||
}
|
||||
public abstract Result<List<Tag>> extractLinkAnchors(Result<Tag> tagResult);
|
||||
|
||||
public abstract Result<List<Tag>> extractLinkAnchors(Result<Tag> tagResult);
|
||||
protected Result<Tag> extractLinksTag(Tag eventTag) {
|
||||
return extractDescriptionTag(eventTag);
|
||||
}
|
||||
|
||||
protected Result<Tag> extractLinksTag(Tag eventTag) {
|
||||
return extractDescriptionTag(eventTag);
|
||||
}
|
||||
protected Result<String> extractLocation(Tag eventTag) {
|
||||
Result<Tag> locationTag = extractLocationTag(eventTag);
|
||||
if (locationTag.optional().isEmpty()) return transform(locationTag);
|
||||
return Payload.of(locationTag.optional().get().toString(2));
|
||||
}
|
||||
|
||||
protected Result<String> extractLocation(Tag eventTag) {
|
||||
Result<Tag> locationTag = extractLocationTag(eventTag);
|
||||
if (locationTag.optional().isEmpty()) return transform(locationTag);
|
||||
return Payload.of(locationTag.optional().get().toString(2));
|
||||
}
|
||||
protected abstract Result<Tag> extractLocationTag(Tag eventTag);
|
||||
|
||||
protected abstract Result<Tag> extractLocationTag(Tag eventTag);
|
||||
protected Result<LocalDateTime> extractStart(Tag eventTag) {
|
||||
Result<Tag> startTag = extractStartTag(eventTag);
|
||||
if (startTag.optional().isEmpty()) return transform(startTag);
|
||||
return parseStartDate(startTag.optional().get().strip());
|
||||
}
|
||||
|
||||
protected abstract Result<Tag> extractStartTag(Tag eventTag);
|
||||
|
||||
protected Result<LocalDateTime> extractStart(Tag eventTag) {
|
||||
Result<Tag> startTag = extractStartTag(eventTag);
|
||||
if (startTag.optional().isEmpty()) return transform(startTag);
|
||||
return parseStartDate(startTag.optional().get().strip());
|
||||
}
|
||||
protected abstract List<String> extractTags(Tag eventTag);
|
||||
|
||||
protected abstract Result<Tag> extractStartTag(Tag eventTag);
|
||||
|
||||
|
||||
protected abstract List<String> extractTags(Tag eventTag);
|
||||
|
||||
protected Result<String> extractTitle(Tag eventTag) {
|
||||
Result<Tag> titleTag = extractTitleTag(eventTag);
|
||||
if (titleTag.optional().isEmpty()) return transform(titleTag);
|
||||
var inner = titleTag.optional().flatMap(tag -> tag.inner(2));
|
||||
return inner.isPresent() ? Payload.of(inner.get()) :
|
||||
error("No title found");
|
||||
protected Result<String> extractTitle(Tag eventTag) {
|
||||
Result<Tag> titleTag = extractTitleTag(eventTag);
|
||||
if (titleTag.optional().isEmpty()) return transform(titleTag);
|
||||
var inner = titleTag.optional().flatMap(tag -> tag.inner(2));
|
||||
return inner.isPresent() ? Payload.of(inner.get()) :
|
||||
error("No title found");
|
||||
}
|
||||
|
||||
protected abstract Result<Tag> extractTitleTag(Tag eventTag);
|
||||
|
||||
|
||||
@Override
|
||||
public Stream<Appointment> fetch() {
|
||||
var url = Payload.of(programURL());
|
||||
@@ -249,24 +243,24 @@ public abstract class BaseImporter implements Importer {
|
||||
|
||||
protected Result<Tag> parseXML(Result<InputStream> inputStream) {
|
||||
return switch (inputStream) {
|
||||
case Payload<InputStream> payload -> XMLParser.parse(payload.get());
|
||||
case Error<InputStream> error -> error.transform();
|
||||
default -> invalidParameter(inputStream);
|
||||
};
|
||||
}
|
||||
case Payload<InputStream> payload -> XMLParser.parse(payload.get());
|
||||
case Error<InputStream> error -> error.transform();
|
||||
default -> invalidParameter(inputStream);
|
||||
};
|
||||
}
|
||||
|
||||
protected Result<InputStream> preload(Result<InputStream> inputStream) {
|
||||
switch (inputStream) {
|
||||
case Payload<InputStream> payload:
|
||||
try {
|
||||
return Payload.of(XMLParser.preload(payload.get()));
|
||||
} catch (IOException e) {
|
||||
return error(e, "Failed to buffer data from %s", payload);
|
||||
}
|
||||
case Error<InputStream> error:
|
||||
return error.transform();
|
||||
default:
|
||||
return invalidParameter(inputStream);
|
||||
protected Result<InputStream> preload(Result<InputStream> inputStream) {
|
||||
switch (inputStream) {
|
||||
case Payload<InputStream> payload:
|
||||
try {
|
||||
return Payload.of(XMLParser.preload(payload.get()));
|
||||
} catch (IOException e) {
|
||||
return error(e, "Failed to buffer data from %s", payload);
|
||||
}
|
||||
case Error<InputStream> error:
|
||||
return error.transform();
|
||||
default:
|
||||
return invalidParameter(inputStream);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,7 +278,6 @@ public abstract class BaseImporter implements Importer {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected static Result<Integer> toNumericMonth(String month) {
|
||||
month = month.toLowerCase();
|
||||
if (month.startsWith("ja")) return Payload.of(1);
|
||||
@@ -302,7 +295,6 @@ public abstract class BaseImporter implements Importer {
|
||||
return error("Failed to recognize \"%s\" as a month!", month);
|
||||
}
|
||||
|
||||
|
||||
protected static Result<URL> url(Result<String> urlResult) {
|
||||
if (urlResult.optional().isEmpty()) return transform(urlResult);
|
||||
var url = urlResult.optional().get();
|
||||
|
||||
@@ -16,7 +16,7 @@ public interface Database {
|
||||
* @param appointment the appointment to store
|
||||
* @return a clone of the provided appointment with id field set
|
||||
*/
|
||||
public Result<Appointment> add(Appointment appointment);
|
||||
Result<Appointment> add(Appointment appointment);
|
||||
|
||||
Result<List<String>> findTags(String infix);
|
||||
|
||||
@@ -28,7 +28,7 @@ public interface Database {
|
||||
* @param till restrict appointments to times before this date time
|
||||
* @return list of appointments in this time span
|
||||
*/
|
||||
public Result<List<Appointment>> list(LocalDateTime from, LocalDateTime till, Integer count, Integer offset);
|
||||
Result<List<Appointment>> list(LocalDateTime from, LocalDateTime till, Integer count, Integer offset);
|
||||
|
||||
/**
|
||||
* list appointments
|
||||
@@ -37,7 +37,7 @@ public interface Database {
|
||||
* @param offset the number of appointments to skip
|
||||
* @return the list of appointments fetched from the db
|
||||
*/
|
||||
public List<Appointment> listByTags(Set<String> tags, Integer count, Integer offset);
|
||||
List<Appointment> listByTags(Set<String> tags, Integer count, Integer offset);
|
||||
|
||||
Result<Appointment> loadEvent(long id);
|
||||
|
||||
|
||||
@@ -58,7 +58,6 @@ public class MariaDB implements Database {
|
||||
throw new RuntimeException("%s.createTables() not implemented!");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Result<Appointment> add(Appointment appointment) {
|
||||
try {
|
||||
@@ -290,7 +289,6 @@ public class MariaDB implements Database {
|
||||
return Payload.of(appointment);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<Appointment> listByTags(Set<String> tags, Integer count, Integer offset) {
|
||||
return List.of();
|
||||
|
||||
@@ -14,7 +14,6 @@ public class NotFound<None> extends Error<None> {
|
||||
return new NotFound<>(message.formatted(fills), null, null);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public <NewType> NotFound<NewType> transform() {
|
||||
return new NotFound<>(message(), data(), exceptions());
|
||||
|
||||
@@ -51,8 +51,8 @@ public class ApiEndpoint extends PathHandler {
|
||||
if (opt.isEmpty()) return transform(res);
|
||||
var event = opt.get();
|
||||
var title = getHeader(ex, TITLE);
|
||||
if (title.isEmpty()) return error("Missing title header");
|
||||
if (!title.get().equals(event.title())) return error("Title mismatch!");
|
||||
if (title.isEmpty()) return HttpError.of(400,"Missing title header");
|
||||
if (!title.get().equals(event.title())) return HttpError.of(400,"Title mismatch!");
|
||||
return db.add(opt.get()).map(ApiEndpoint::toJson);
|
||||
} catch (IOException e) {
|
||||
return error(e, "Failed to read event data from request body");
|
||||
@@ -67,7 +67,7 @@ public class ApiEndpoint extends PathHandler {
|
||||
try {
|
||||
aid = Long.parseLong(id);
|
||||
} catch (Exception e) {
|
||||
return HttpError.of(400, "%s is not a valid appointment id!", id);
|
||||
return HttpError.of(404, "%s is not a valid appointment id!", id);
|
||||
}
|
||||
var opt = getHeader(ex, "title");
|
||||
if (opt.isEmpty()) return HttpError.of(412, "title missing");
|
||||
@@ -83,7 +83,6 @@ public class ApiEndpoint extends PathHandler {
|
||||
return db.removeAppointment(event.id());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean doDelete(String path, HttpExchange ex) throws IOException {
|
||||
if ("/event".equals(path)) return sendContent(ex, delete(path, ex));
|
||||
@@ -94,233 +93,219 @@ public class ApiEndpoint extends PathHandler {
|
||||
public boolean doGet(String path, HttpExchange ex) throws IOException {
|
||||
return switch (path) {
|
||||
case "/event" -> sendContent(ex,getEvent(ex).map(ApiEndpoint::toJson).map(ApiEndpoint::httpError));
|
||||
case "/events/json" -> sendContent(ex,eventList(ex).map(ApiEndpoint::toJsonList).map(ApiEndpoint::httpError));
|
||||
case "/events/ical"-> sendContent(ex,eventList(ex).map(ApiEndpoint::toIcal).map(ApiEndpoint::httpError));
|
||||
case "/tags" -> listTags(ex);
|
||||
default -> unknownPath(ex,path);
|
||||
};
|
||||
case "/events/json" -> sendContent(ex,eventList(ex).map(ApiEndpoint::toJsonList).map(ApiEndpoint::httpError));
|
||||
case "/tags" -> listTags(ex);
|
||||
default -> unknownPath(ex, path);
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doPatch(String path, HttpExchange ex) throws IOException {
|
||||
if ("/event".equals(path)) return sendContent(ex, updateEvent(ex));
|
||||
return unknownPath(ex, path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doPost(String path, HttpExchange ex) throws IOException {
|
||||
if ("/event".equals(path)) return sendContent(ex, createEvent(ex));
|
||||
return unknownPath(ex, path);
|
||||
}
|
||||
|
||||
private Result<List<Appointment>> eventList(HttpExchange ex) {
|
||||
var param = queryParam(ex);
|
||||
var tags = nullable(param.get(TAGS)).stream()
|
||||
.flatMap(s -> Arrays.stream(s.split(",")))
|
||||
.map(s -> s.trim().toLowerCase())
|
||||
.toList();
|
||||
|
||||
Result<LocalDateTime> start = parseDate(param.get(START));
|
||||
if (start == null) start = parsePast(param.get(PAST));
|
||||
if (start instanceof de.srsoftware.tools.Error<LocalDateTime> err) return err.transform();
|
||||
var startDate = (start == null) ? null: start.optional().orElse(null);
|
||||
Integer offset = null;
|
||||
|
||||
var o = param.get(OFFSET);
|
||||
if (o != null) try {
|
||||
offset = Integer.parseInt(o);
|
||||
} catch (NumberFormatException e) {
|
||||
return HttpError.of(400,"Offset (offset=%s) is not a number!", o);
|
||||
}
|
||||
|
||||
|
||||
Integer count = null;
|
||||
o = param.get(COUNT);
|
||||
if (o != null) try {
|
||||
count = Integer.parseInt(o);
|
||||
} catch (NumberFormatException e) {
|
||||
return HttpError.of(400,"Count (count=%s) is not a number!", o);
|
||||
}
|
||||
|
||||
return db.list(startDate, null, count, offset).map(res -> filterByTags(res, tags));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doPatch(String path, HttpExchange ex) throws IOException {
|
||||
if ("/event".equals(path)) return sendContent(ex, updateEvent(ex));
|
||||
return unknownPath(ex, path);
|
||||
private Result<List<Appointment>> filterByTags(Result<List<Appointment>> res, List<String> tags) {
|
||||
if (tags == null || tags.isEmpty()) return res;
|
||||
var opt = res.optional();
|
||||
if (opt.isEmpty()) return transform(res);
|
||||
var list = opt.get().stream().filter(event -> tagsMatch(event, tags)).toList();
|
||||
return Payload.of(list);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doPost(String path, HttpExchange ex) throws IOException {
|
||||
if ("/event".equals(path)) return sendContent(ex, createEvent(ex));
|
||||
return unknownPath(ex, path);
|
||||
}
|
||||
|
||||
private Result<List<Appointment>> eventList(HttpExchange ex) {
|
||||
var param = queryParam(ex);
|
||||
var tags = nullable(param.get(TAGS)) //
|
||||
.stream()
|
||||
.flatMap(s -> Arrays.stream(s.split(",")))
|
||||
.map(s -> s.trim().toLowerCase())
|
||||
.toList();
|
||||
|
||||
Result<LocalDateTime> start = parseDate(param.get(START));
|
||||
if (start == null) start = parsePast(param.get(PAST));
|
||||
if (start instanceof de.srsoftware.tools.Error<LocalDateTime> err) return err.transform();
|
||||
var startDate = (start == null) ? null:
|
||||
start.optional().orElse(null);
|
||||
Integer offset = null;
|
||||
|
||||
var o = param.get(OFFSET);
|
||||
if (o != null) {
|
||||
try {
|
||||
offset = Integer.parseInt(o);
|
||||
} catch (NumberFormatException e) {
|
||||
return error("Offset (offset=%s) is not a number!", o);
|
||||
}
|
||||
}
|
||||
|
||||
Integer count = null;
|
||||
o = param.get(COUNT);
|
||||
if (o != null) {
|
||||
try {
|
||||
count = Integer.parseInt(o);
|
||||
} catch (NumberFormatException e) {
|
||||
return error("Count (count=%s) is not a number!", o);
|
||||
}
|
||||
}
|
||||
|
||||
return db.list(startDate, null, count, offset).map(res -> filterByTags(res, tags));
|
||||
}
|
||||
|
||||
|
||||
private Result<List<Appointment>> filterByTags(Result<List<Appointment>> res, List<String> tags) {
|
||||
if (tags == null || tags.isEmpty()) return res;
|
||||
var opt = res.optional();
|
||||
if (opt.isEmpty()) return transform(res);
|
||||
var list = opt.get().stream().filter(event -> tagsMatch(event, tags)).toList();
|
||||
return Payload.of(list);
|
||||
}
|
||||
|
||||
|
||||
private Result<Appointment> getEvent(HttpExchange ex) {
|
||||
var params = queryParam(ex);
|
||||
var o = params.get(ID);
|
||||
if (o == null) return error("id parameter missing!");
|
||||
try {
|
||||
long id = Long.parseLong(o);
|
||||
return db.loadEvent(id);
|
||||
} catch (NumberFormatException e) {
|
||||
return error(e, "Illegal format for id parameter (%s)", o);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Result<T> httpError(Result<T> res) {
|
||||
if (res instanceof NotFound<T> notFound) return HttpError.of(404, notFound.message());
|
||||
return res;
|
||||
}
|
||||
|
||||
private boolean listTags(HttpExchange ex) throws IOException {
|
||||
var params = queryParam(ex);
|
||||
var infix = params.get("infix");
|
||||
if (infix == null) return sendContent(ex, error("No infix set in method call parameters"));
|
||||
var res = db.findTags(infix).map(ApiEndpoint::sortTags);
|
||||
return sendContent(ex, res);
|
||||
}
|
||||
|
||||
public static Result<LocalDateTime> parseDate(String s) {
|
||||
if (s == null) return null;
|
||||
var matcher = DATE_TIME.matcher(s);
|
||||
if (matcher.find()) {
|
||||
int year = Integer.parseInt(matcher.group(1));
|
||||
int month = Integer.parseInt(matcher.group(2));
|
||||
int day = nullable(matcher.group(4)).map(Integer::parseInt).orElse(1);
|
||||
int hour = nullable(matcher.group(6)).map(Integer::parseInt).orElse(0);
|
||||
int minute = nullable(matcher.group(7)).map(Integer::parseInt).orElse(0);
|
||||
int second = nullable(matcher.group(9)).map(Integer::parseInt).orElse(0);
|
||||
return Payload.of(LocalDateTime.of(year, month, day, hour, minute, second));
|
||||
}
|
||||
return error("invalid date time format: %s", s);
|
||||
}
|
||||
|
||||
|
||||
public static Result<LocalDateTime> parsePast(String s) {
|
||||
var start = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
|
||||
if (s == null) return Payload.of(start);
|
||||
var matcher = PAST_PATTERN.matcher(s);
|
||||
if (matcher.find()) {
|
||||
for (int i = 0; i <= matcher.groupCount(); i++) System.out.printf("%s: %s\n", i, matcher.group(i));
|
||||
|
||||
int num = nullable(matcher.group(1)).map(Integer::parseInt).orElse(0);
|
||||
switch (nullable(matcher.group(2)).orElse("")) {
|
||||
case "m":
|
||||
start = start.minusMonths(num);
|
||||
break;
|
||||
case "y":
|
||||
start = start.minusYears(num);
|
||||
break;
|
||||
}
|
||||
var all = matcher.group(3);
|
||||
if ("all".equals(all)) return null;
|
||||
return Payload.of(start);
|
||||
}
|
||||
return error("invalid past format: %s", s);
|
||||
}
|
||||
|
||||
private static Result<List<String>> sortTags(Result<List<String>> listResult) {
|
||||
if (listResult.optional().isEmpty()) return listResult;
|
||||
List<String> list = listResult.optional().get();
|
||||
while (list.size() > 15) {
|
||||
int longest = list.stream().map(String::length).reduce(0, Integer::max);
|
||||
var subset = list.stream().filter(s -> s.length() < longest).toList();
|
||||
if (subset.size() < 3) return Payload.of(list);
|
||||
list = subset;
|
||||
}
|
||||
return Payload.of(list);
|
||||
}
|
||||
|
||||
|
||||
private static boolean tagsMatch(Appointment event, List<String> tags) {
|
||||
return new HashSet<>(event.tags().stream().map(String::toLowerCase).toList()).containsAll(tags);
|
||||
}
|
||||
|
||||
|
||||
private Result<BaseAppointment> toEvent(JSONObject json) {
|
||||
var description = json.has(DESCRIPTION) ? nullIfEmpty(json.getString(DESCRIPTION)) : null;
|
||||
var title = json.has(TITLE) ? nullIfEmpty(json.getString(TITLE)) : null;
|
||||
if (title == null) return error("title missing");
|
||||
var start = json.has(START) ? nullIfEmpty(json.getString(START)) : null;
|
||||
if (start == null) return error("start missing");
|
||||
var startDate = nullable(start).map(dt -> LocalDateTime.parse(dt, ISO_DATE_TIME)).orElse(null);
|
||||
var end = json.has(END) ? nullIfEmpty(json.getString(END)) : null;
|
||||
var endDate = nullable(end).map(dt -> LocalDateTime.parse(dt, ISO_DATE_TIME)).orElse(null);
|
||||
var location = json.has(LOCATION) ? json.getString(LOCATION) : null;
|
||||
if (location == null) return error("location missing");
|
||||
var aid = json.has(AID) ? json.getLong(AID) : 0;
|
||||
var event = new BaseAppointment(aid, title, description, startDate, endDate, location);
|
||||
if (json.has(ATTACHMENTS)) {
|
||||
json.getJSONArray(ATTACHMENTS).forEach(att -> {
|
||||
Payload //
|
||||
.of(att.toString())
|
||||
.map(BaseImporter::url)
|
||||
.map(BaseImporter::toAttachment)
|
||||
.optional()
|
||||
.ifPresent(event::add);
|
||||
});
|
||||
}
|
||||
if (json.has(LINKS)) {
|
||||
json.getJSONArray(LINKS).forEach(o -> {
|
||||
if (o instanceof JSONObject j) toLink(j).optional().ifPresent(event::addLinks);
|
||||
});
|
||||
}
|
||||
if (json.has(TAGS)) json.getJSONArray(TAGS).forEach(o -> event.tags(o.toString()));
|
||||
return Payload.of(event);
|
||||
}
|
||||
|
||||
|
||||
private static Result<String> toIcal(Result<List<Appointment>> res) {
|
||||
var opt = res.optional();
|
||||
if (opt.isEmpty()) return transform(res);
|
||||
var list = opt.get().stream().map(Appointment::ical).collect(Collectors.joining("\n"));
|
||||
return Payload.of(list);
|
||||
}
|
||||
|
||||
|
||||
private static Result<JSONObject> toJson(Result<? extends Appointment> res) {
|
||||
var opt = res.optional();
|
||||
if (opt.isEmpty()) return transform(res);
|
||||
return Payload.of(opt.get().json());
|
||||
}
|
||||
|
||||
private static Result<List<JSONObject>> toJsonList(Result<List<Appointment>> res) {
|
||||
var opt = res.optional();
|
||||
if (opt.isEmpty()) return transform(res);
|
||||
var list = opt.get().stream().map(Appointment::json).toList();
|
||||
return Payload.of(list);
|
||||
}
|
||||
protected static Result<Link> toLink(JSONObject json) {
|
||||
try {
|
||||
var description = json.getString(DESCRIPTION);
|
||||
return Payload.of(json.getString(URL)).map(BaseImporter::url).map(url -> BaseImporter.link(url, description));
|
||||
|
||||
} catch (Exception e) {
|
||||
return error(e, "Failed to create link from %s", json);
|
||||
}
|
||||
}
|
||||
private boolean unknownPath(HttpExchange ex, String path) throws IOException {
|
||||
return sendContent(ex, HttpError.of(404, "%s is not known to this API", path));
|
||||
}
|
||||
|
||||
|
||||
private Result<JSONObject> updateEvent(HttpExchange ex) {
|
||||
try {
|
||||
var res = toEvent(json(ex));
|
||||
var opt = res.optional();
|
||||
if (opt.isEmpty()) return transform(res);
|
||||
var event = opt.get();
|
||||
var title = getHeader(ex, TITLE);
|
||||
if (title.isEmpty()) return error("Missing title header");
|
||||
if (!title.get().equals(event.title())) return error("Title mismatch!");
|
||||
return db.update(opt.get()).map(ApiEndpoint::toJson);
|
||||
} catch (IOException e) {
|
||||
return error(e, "Failed to read event data from request body");
|
||||
}
|
||||
private Result<Appointment> getEvent(HttpExchange ex) {
|
||||
var params = queryParam(ex);
|
||||
var o = params.get(ID);
|
||||
if (o == null) return HttpError.of(400,"id parameter missing!");
|
||||
try {
|
||||
return db.loadEvent(Long.parseLong(o));
|
||||
} catch (NumberFormatException e) {
|
||||
return HttpError.of(400,e, "Illegal format for id parameter (%s)", o);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Result<T> httpError(Result<T> res) {
|
||||
if (res instanceof NotFound<T> notFound) return HttpError.of(404, notFound.message());
|
||||
return res;
|
||||
}
|
||||
|
||||
private boolean listTags(HttpExchange ex) throws IOException {
|
||||
var params = queryParam(ex);
|
||||
var infix = nullIfEmpty(params.get("infix"));
|
||||
if (infix == null) return sendContent(ex, HttpError.of(400,"No infix set in method call parameters"));
|
||||
var res = db.findTags(infix).map(ApiEndpoint::sortTags);
|
||||
return sendContent(ex, res);
|
||||
}
|
||||
|
||||
public static Result<LocalDateTime> parseDate(String s) {
|
||||
if (s == null) return null;
|
||||
var matcher = DATE_TIME.matcher(s);
|
||||
if (matcher.find()) {
|
||||
int year = Integer.parseInt(matcher.group(1));
|
||||
int month = Integer.parseInt(matcher.group(2));
|
||||
int day = nullable(matcher.group(4)).map(Integer::parseInt).orElse(1);
|
||||
int hour = nullable(matcher.group(6)).map(Integer::parseInt).orElse(0);
|
||||
int minute = nullable(matcher.group(7)).map(Integer::parseInt).orElse(0);
|
||||
int second = nullable(matcher.group(9)).map(Integer::parseInt).orElse(0);
|
||||
return Payload.of(LocalDateTime.of(year, month, day, hour, minute, second));
|
||||
}
|
||||
return error("invalid date time format: %s", s);
|
||||
}
|
||||
|
||||
public static Result<LocalDateTime> parsePast(String s) {
|
||||
var start = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
|
||||
if (s == null) return Payload.of(start);
|
||||
var matcher = PAST_PATTERN.matcher(s);
|
||||
if (matcher.find()) {
|
||||
int num = nullable(matcher.group(1)).map(Integer::parseInt).orElse(0);
|
||||
var g2 = nullable(matcher.group(2)).orElse("");
|
||||
switch (g2) {
|
||||
case "m":
|
||||
start = start.minusMonths(num);
|
||||
break;
|
||||
case "y":
|
||||
start = start.minusYears(num);
|
||||
break;
|
||||
}
|
||||
var all = matcher.group(3);
|
||||
if ("all".equals(all)) return null;
|
||||
return Payload.of(start);
|
||||
}
|
||||
return error("invalid past format: %s", s);
|
||||
}
|
||||
|
||||
private static Result<List<String>> sortTags(Result<List<String>> listResult) {
|
||||
if (listResult.optional().isEmpty()) return listResult;
|
||||
List<String> list = listResult.optional().get();
|
||||
while (list.size() > 15) {
|
||||
int longest = list.stream().map(String::length).reduce(0, Integer::max);
|
||||
var subset = list.stream().filter(s -> s.length() < longest).toList();
|
||||
if (subset.size() < 3) return Payload.of(list);
|
||||
list = subset;
|
||||
}
|
||||
return Payload.of(list);
|
||||
}
|
||||
|
||||
private static boolean tagsMatch(Appointment event, List<String> tags) {
|
||||
return new HashSet<>(event.tags().stream().map(String::toLowerCase).toList()).containsAll(tags);
|
||||
}
|
||||
|
||||
private Result<BaseAppointment> toEvent(JSONObject json) {
|
||||
var description = json.has(DESCRIPTION) ? nullIfEmpty(json.getString(DESCRIPTION)) : null;
|
||||
var title = json.has(TITLE) ? nullIfEmpty(json.getString(TITLE)) : null;
|
||||
if (title == null) return error("title missing");
|
||||
var start = json.has(START) ? nullIfEmpty(json.getString(START)) : null;
|
||||
if (start == null) return error("start missing");
|
||||
var startDate = nullable(start).map(dt -> LocalDateTime.parse(dt, ISO_DATE_TIME)).orElse(null);
|
||||
var end = json.has(END) ? nullIfEmpty(json.getString(END)) : null;
|
||||
var endDate = nullable(end).map(dt -> LocalDateTime.parse(dt, ISO_DATE_TIME)).orElse(null);
|
||||
var location = json.has(LOCATION) ? json.getString(LOCATION) : null;
|
||||
if (location == null) return error("location missing");
|
||||
var aid = json.has(AID) ? json.getLong(AID) : 0;
|
||||
var event = new BaseAppointment(aid, title, description, startDate, endDate, location);
|
||||
if (json.has(ATTACHMENTS)) {
|
||||
json.getJSONArray(ATTACHMENTS).forEach(att -> {
|
||||
Payload //
|
||||
.of(att.toString())
|
||||
.map(BaseImporter::url)
|
||||
.map(BaseImporter::toAttachment)
|
||||
.optional()
|
||||
.ifPresent(event::add);
|
||||
});
|
||||
}
|
||||
if (json.has(LINKS)) json.getJSONArray(LINKS).forEach(o -> {
|
||||
if (o instanceof JSONObject j) toLink(j).optional().ifPresent(event::addLinks);
|
||||
});
|
||||
|
||||
if (json.has(TAGS)) json.getJSONArray(TAGS).forEach(o -> event.tags(o.toString()));
|
||||
return Payload.of(event);
|
||||
}
|
||||
|
||||
private static Result<String> toIcal(Result<List<Appointment>> res) {
|
||||
var opt = res.optional();
|
||||
if (opt.isEmpty()) return transform(res);
|
||||
var list = opt.get().stream().map(Appointment::ical).collect(Collectors.joining("\n"));
|
||||
return Payload.of(list);
|
||||
}
|
||||
|
||||
private static Result<JSONObject> toJson(Result<? extends Appointment> res) {
|
||||
var opt = res.optional();
|
||||
return opt.isEmpty() ? transform(res) : Payload.of(opt.get().json());
|
||||
}
|
||||
|
||||
private static Result<List<JSONObject>> toJsonList(Result<List<Appointment>> res) {
|
||||
var opt = res.optional();
|
||||
if (opt.isEmpty()) return transform(res);
|
||||
var list = opt.get().stream().map(Appointment::json).toList();
|
||||
return Payload.of(list);
|
||||
}
|
||||
|
||||
protected static Result<Link> toLink(JSONObject json) {
|
||||
try {
|
||||
var description = json.getString(DESCRIPTION);
|
||||
return Payload.of(json.getString(URL))
|
||||
.map(BaseImporter::url)
|
||||
.map(url -> BaseImporter.link(url, description));
|
||||
} catch (Exception e) {
|
||||
return error(e, "Failed to create link from %s", json);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean unknownPath(HttpExchange ex, String path) throws IOException {
|
||||
return sendContent(ex, HttpError.of(404, "%s is not known to this API", path));
|
||||
}
|
||||
|
||||
private Result<JSONObject> updateEvent(HttpExchange ex) {
|
||||
try {
|
||||
var res = toEvent(json(ex));
|
||||
var opt = res.optional();
|
||||
if (opt.isEmpty()) return transform(res);
|
||||
var event = opt.get();
|
||||
var title = getHeader(ex, TITLE);
|
||||
if (title.isEmpty()) return HttpError.of(400,"Missing title header");
|
||||
if (!title.get().equals(event.title())) return HttpError.of(400,"Title mismatch!");
|
||||
return db.update(opt.get()).map(ApiEndpoint::toJson);
|
||||
} catch (IOException e) {
|
||||
return error(e, "Failed to read event data from request body");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import java.io.IOException;
|
||||
|
||||
public class IndexHandler extends PathHandler {
|
||||
PathHandler staticPages;
|
||||
|
||||
public IndexHandler(PathHandler staticPages) {
|
||||
this.staticPages = staticPages;
|
||||
}
|
||||
@@ -14,10 +15,9 @@ public class IndexHandler extends PathHandler {
|
||||
@Override
|
||||
public boolean doGet(String path, HttpExchange ex) throws IOException {
|
||||
return switch (path) {
|
||||
case "/" -> staticPages.doGet("/index", ex);
|
||||
case "/favicon.ico" -> staticPages.doGet("/images/%s".formatted(path), ex);
|
||||
default -> super.doGet(path, ex);
|
||||
};
|
||||
|
||||
}
|
||||
case "/" -> staticPages.doGet("/index", ex);
|
||||
case "/favicon.ico" -> staticPages.doGet("/images/%s".formatted(path), ex);
|
||||
default -> super.doGet(path, ex);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
|
||||
public class StaticHandler extends PathHandler {
|
||||
private final Optional<String> staticPath;
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ function openIcal(){
|
||||
var pos = url.indexOf('?');
|
||||
if (pos>1) url = url.substring(0,pos);
|
||||
if (!url.endsWith('/')) url += '/';
|
||||
url += 'api/ical'+query;
|
||||
url += 'api/events/ical'+query;
|
||||
var elem = create('a');
|
||||
elem.setAttribute('href',url);
|
||||
elem.setAttribute('download','calendar.ical');
|
||||
|
||||
@@ -266,6 +266,14 @@ paths:
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
'400':
|
||||
description: invalid input
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: string
|
||||
example: {"message":"No infix set in method call parameters"}
|
||||
|
||||
components:
|
||||
schemas:
|
||||
Appointment:
|
||||
|
||||
Reference in New Issue
Block a user