Skip to content

Instantly share code, notes, and snippets.

@asdf913
Last active October 24, 2026 02:09
Show Gist options
  • Select an option

  • Save asdf913/1762adc513dd89bcae5a74ecfa4c32d0 to your computer and use it in GitHub Desktop.

Select an option

Save asdf913/1762adc513dd89bcae5a74ecfa4c32d0 to your computer and use it in GitHub Desktop.
Hong Kong Public Library List - Area, District, Name, Address, Opening Hours and URL
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.ToIntFunction;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ConditionalFormattingRule;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.PatternFormatting;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.SheetConditionalFormatting;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.google.common.base.Stopwatch;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Table;
import com.google.common.collect.Table.Cell;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
public class Hkpl {
private static class OpeningHour {
private LocalTime opening, ending;
private Boolean open;
}
private static class Library {
private String area, district, name, address, url;
private Multimap<DayOfWeek, OpeningHour> openingHours;
private Triple<String, LocalTime, LocalTime> publicHolidayOpeningHour = null;
}
public static void main(final String[] args) throws IOException, URISyntaxException {
//
final Stopwatch stopwatch = Stopwatch.createStarted();
//
final File file = new File("hkpl.xlsx");
//
try (final Workbook wb = new XSSFWorkbook(); final OutputStream os = new FileOutputStream(file)) {
//
final List<Library> libraries = getLibraries();
//
Library library = null;
//
Sheet sheet = null;
//
Row row = null;
//
org.apache.poi.ss.usermodel.Cell cell = null;
//
CellStyle cellStyleHeading = null, cellStyleLocalTime = null;
//
final int maxAreaLength = orElse(
max(mapToInt(stream(libraries), x -> StringUtils.length(x != null ? x.area : null))), 0);
//
final int maxDistrictLength = orElse(
max(mapToInt(stream(libraries), x -> StringUtils.length(x != null ? x.district : null))), 0);
//
final int maxNameLength = orElse(
max(mapToInt(stream(libraries), x -> StringUtils.length(x != null ? x.name : null))), 0);
//
final int maxAddressLength = orElse(
max(mapToInt(stream(libraries), x -> StringUtils.length(x != null ? x.address : null))), 0);
//
final int maxUrlLength = orElse(
max(mapToInt(stream(libraries), x -> StringUtils.length(x != null ? x.url : null))), 0);
//
final List<DayOfWeek> dayOfWeeks = toList(stream(libraries)
.map(x -> x != null ? keySet(x.openingHours) : null).flatMap(Collection::stream).distinct());
//
int rowCount = 0;
//
Multimap<DayOfWeek, OpeningHour> openingHourMultimap = null;
//
Collection<OpeningHour> openingHours = null;
//
OpeningHour openingHour = null;
//
Boolean open = null;
//
LocalTime middle, right = null;
//
CreationHelper creationHelper = null;
//
Hyperlink hyperlink = null;
//
SheetConditionalFormatting scf = null;
//
ConditionalFormattingRule cfr = null;
//
for (int i = 0; i < IterableUtils.size(libraries); i++) {
//
if ((library = IterableUtils.get(libraries, i)) == null) {
//
continue;
//
} // if
//
if (wb.getNumberOfSheets() == 0 && (sheet = wb.createSheet()) != null) {
//
if ((row = sheet.createRow(sheet.getPhysicalNumberOfRows())) != null) {
//
// Area
//
setCellValue(cell = createCell(row, row.getPhysicalNumberOfCells()), "Area");
//
if (cellStyleHeading == null && wb != null
&& (cellStyleHeading = wb.createCellStyle()) != null) {
//
cellStyleHeading.setAlignment(HorizontalAlignment.CENTER);
//
cellStyleHeading.setVerticalAlignment(VerticalAlignment.CENTER);
//
} // if
//
setCellStyle(cell, cellStyleHeading);
//
sheet.addMergedRegion(new CellRangeAddress(cell.getRowIndex(), 1, cell.getColumnIndex(),
cell.getColumnIndex()));
//
// District
//
setCellValue(cell = createCell(row, row.getPhysicalNumberOfCells()), "District");
//
setCellStyle(cell, cellStyleHeading);
//
sheet.addMergedRegion(new CellRangeAddress(cell.getRowIndex(), 1, cell.getColumnIndex(),
cell.getColumnIndex()));
//
// Name
//
setCellValue(cell = createCell(row, row.getPhysicalNumberOfCells()), "Name");
//
setCellStyle(cell, cellStyleHeading);
//
sheet.addMergedRegion(new CellRangeAddress(cell.getRowIndex(), 1, cell.getColumnIndex(),
cell.getColumnIndex()));
//
// Address
//
setCellValue(cell = createCell(row, row.getPhysicalNumberOfCells()), "Address");
//
setCellStyle(cell, cellStyleHeading);
//
sheet.addMergedRegion(new CellRangeAddress(cell.getRowIndex(), 1, cell.getColumnIndex(),
cell.getColumnIndex()));
//
for (int j = 0; j < IterableUtils.size(dayOfWeeks); j++) {
//
setCellValue(cell = createCell(row, row.getPhysicalNumberOfCells() + j * 2),
getDisplayName(IterableUtils.get(dayOfWeeks, j), TextStyle.FULL, Locale.ENGLISH));
//
setCellStyle(cell, cellStyleHeading);
//
sheet.addMergedRegion(new CellRangeAddress(cell.getRowIndex(), cell.getRowIndex(),
cell.getColumnIndex(), cell.getColumnIndex() + 2));
//
} // for
//
setCellValue(
cell = createCell(row,
row.getPhysicalNumberOfCells() + IterableUtils.size(dayOfWeeks) * 2),
getLeft(library.publicHolidayOpeningHour));
//
setCellStyle(cell, cellStyleHeading);
//
sheet.addMergedRegion(new CellRangeAddress(cell.getRowIndex(), cell.getRowIndex(),
cell.getColumnIndex(), cell.getColumnIndex() + 2));
//
} // if
//
if ((row = sheet.createRow(sheet.getPhysicalNumberOfRows())) != null) {
//
for (int j = 0; j < IterableUtils.size(dayOfWeeks); j++) {
//
setCellValue(cell = createCell(row, 4 + j * 3), "Open");
//
setCellStyle(cell, cellStyleHeading);
//
setCellValue(cell = createCell(row, 5 + j * 3), "Opening");
//
setCellStyle(cell, cellStyleHeading);
//
setCellValue(cell = createCell(row, 6 + j * 3), "Ending");
//
setCellStyle(cell, cellStyleHeading);
//
} // for
//
setCellValue(cell = createCell(row,
row.getPhysicalNumberOfCells() + IterableUtils.size(dayOfWeeks) - 3), "Open");
//
setCellStyle(cell, cellStyleHeading);
//
setCellValue(
cell = createCell(row,
row.getPhysicalNumberOfCells() + IterableUtils.size(dayOfWeeks) - 3),
"Opening");
//
setCellStyle(cell, cellStyleHeading);
//
setCellValue(cell = createCell(row,
row.getPhysicalNumberOfCells() + IterableUtils.size(dayOfWeeks) - 3), "Ending");
//
setCellStyle(cell, cellStyleHeading);
//
} // if
//
// URL
//
setCellValue(cell = createCell(row = sheet.getRow(0),
(row != null ? row.getPhysicalNumberOfCells() : 0) + IterableUtils.size(dayOfWeeks) + 9),
"URL");
//
setCellStyle(cell, cellStyleHeading);
//
sheet.addMergedRegion(
new CellRangeAddress(cell.getRowIndex(), 1, cell.getColumnIndex(), cell.getColumnIndex()));
//
} // if
//
rowCount = orElse(max(mapToInt(
stream(entrySet(asMap(openingHourMultimap = library != null ? library.openingHours : null))),
x -> IterableUtils.size(getValue(x)))), 0);
//
for (int j = 0; j < rowCount; j++) {
//
if ((row = sheet.createRow(sheet.getPhysicalNumberOfRows())) != null) {
//
setCellValue(createCell(row, row.getPhysicalNumberOfCells()), library.area);
//
if (StringUtils.length(library.area) == maxAreaLength) {
//
sheet.autoSizeColumn(row.getPhysicalNumberOfCells() - 1);
//
} // if
//
setCellValue(createCell(row, row.getPhysicalNumberOfCells()), library.district);
//
if (StringUtils.length(library.district) == maxDistrictLength) {
//
sheet.autoSizeColumn(row.getPhysicalNumberOfCells() - 1);
//
} // if
//
setCellValue(createCell(row, row.getPhysicalNumberOfCells()), library.name);
//
if (StringUtils.length(library.name) == maxNameLength) {
//
sheet.autoSizeColumn(row.getPhysicalNumberOfCells() - 1);
//
} // if
//
setCellValue(createCell(row, row.getPhysicalNumberOfCells()), library.address);
//
if (StringUtils.length(library.address) == maxAddressLength) {
//
sheet.autoSizeColumn(row.getPhysicalNumberOfCells() - 1);
//
} // if
//
if (creationHelper == null && wb != null) {
//
creationHelper = wb.getCreationHelper();
//
} // if
//
if (cellStyleLocalTime == null && wb != null
&& (cellStyleLocalTime = wb.createCellStyle()) != null) {
//
cellStyleLocalTime.setAlignment(HorizontalAlignment.CENTER);
//
cellStyleLocalTime.setVerticalAlignment(VerticalAlignment.CENTER);
//
cellStyleLocalTime.setDataFormat(getFormat(createDataFormat(creationHelper), "hh:mm"));
//
} // if
//
for (int k = 0; k < IterableUtils.size(dayOfWeeks); k++) {
//
if (j < IterableUtils
.size(openingHours = get(openingHourMultimap, IterableUtils.get(dayOfWeeks, k)))
&& (openingHour = IterableUtils.get(openingHours, j)) != null) {
//
// open
//
if ((open = openingHour.open) != null) {
//
setCellValue(cell = createCell(row, 4 + k * 3), open.booleanValue());
//
setCellStyle(cell, cellStyleHeading);
//
setFillBackgroundColor(
createPatternFormatting(cfr = createConditionalFormattingRule(
scf = sheet.getSheetConditionalFormatting(),
String.format(
"=AND(INDIRECT(ADDRESS(1,%1$s))=TEXT(TODAY(),\"dddd\"),INDIRECT(ADDRESS(%2$s,%1$s))=TRUE)",
5 + k * 3, cell.getRowIndex() + 1))),
IndexedColors.GREEN.getIndex());
//
addConditionalFormatting(scf,
new CellRangeAddress[] { new CellRangeAddress(cell.getRowIndex(),
cell.getRowIndex(), cell.getColumnIndex(), cell.getColumnIndex()) },
cfr);
//
} // if
//
// opening
//
setCellValue(cell = createCell(row, 5 + k * 3),
atDate(openingHour.opening, LocalDate.now()));
//
setCellStyle(cell, cellStyleLocalTime);
//
setFillBackgroundColor(createPatternFormatting(cfr = createConditionalFormattingRule(
scf = sheet.getSheetConditionalFormatting(),
String.format(
"=AND((NOW()-TODAY())*1440>LEFT(TEXT(INDIRECT(ADDRESS(%1$s,%2$s)),\"HH:mm\"),2)*60+RIGHT(TEXT(INDIRECT(ADDRESS(%1$s,%2$s)),\"HH:mm\"),2),INDIRECT(ADDRESS(1,%3$s))=TEXT(TODAY(),\"dddd\"),(NOW()-TODAY())*1440<LEFT(TEXT(INDIRECT(ADDRESS(%1$s,%4$s)),\"HH:mm\"),2)*60+RIGHT(TEXT(INDIRECT(ADDRESS(%1$s,%4$s)),\"HH:mm\"),2))",
cell.getRowIndex() + 1, 6 + k * 3, 5 + k * 3, 7 + k * 3))),
IndexedColors.ORANGE.getIndex());
//
addConditionalFormatting(scf,
new CellRangeAddress[] { new CellRangeAddress(cell.getRowIndex(),
cell.getRowIndex(), cell.getColumnIndex(), cell.getColumnIndex()) },
cfr);
//
// ending
//
setCellValue(cell = createCell(row, 6 + k * 3),
atDate(openingHour.ending, LocalDate.now()));
//
setCellStyle(cell, cellStyleLocalTime);
//
setFillBackgroundColor(createPatternFormatting(cfr = createConditionalFormattingRule(
scf = sheet.getSheetConditionalFormatting(),
String.format(
"=AND((NOW()-TODAY())*1440<LEFT(TEXT(INDIRECT(ADDRESS(%1$s,%2$s)),\"HH:mm\"),2)*60+RIGHT(TEXT(INDIRECT(ADDRESS(%1$s,%2$s)),\"HH:mm\"),2),INDIRECT(ADDRESS(1,%3$s))=TEXT(TODAY(),\"dddd\"),(NOW()-TODAY())*1440>LEFT(TEXT(INDIRECT(ADDRESS(%1$s,%4$s)),\"HH:mm\"),2)*60+RIGHT(TEXT(INDIRECT(ADDRESS(%1$s,%4$s)),\"HH:mm\"),2))",
cell.getRowIndex() + 1, 7 + k * 3, 5 + k * 3, 6 + k * 3))),
IndexedColors.PINK.getIndex());
//
addConditionalFormatting(scf,
new CellRangeAddress[] { new CellRangeAddress(cell.getRowIndex(),
cell.getRowIndex(), cell.getColumnIndex(), cell.getColumnIndex()) },
cfr);
//
} else {
//
setCellValue(cell = createCell(row, 4 + k * 3), false);
//
setCellStyle(cell, cellStyleHeading);
//
setCellValue(createCell(row, 5 + k * 3), "");
//
setCellValue(createCell(row, 6 + k * 3), "");
//
} // if
//
} // for
//
if (j == 0) {
//
setCellValue(cell = createCell(row, row.getPhysicalNumberOfCells()),
Boolean.logicalAnd((middle = getMiddle(library.publicHolidayOpeningHour)) != null,
(right = getRight(library.publicHolidayOpeningHour)) != null));
//
setCellStyle(cell, cellStyleHeading);
//
setCellValue(cell = createCell(row, row.getPhysicalNumberOfCells()),
atDate(middle, LocalDate.now()));
//
setCellStyle(cell, cellStyleLocalTime);
//
setCellValue(cell = createCell(row, row.getPhysicalNumberOfCells()),
atDate(right, LocalDate.now()));
//
setCellStyle(cell, cellStyleLocalTime);
//
} else {
//
setCellValue(createCell(row, row.getPhysicalNumberOfCells()), "");
//
setCellValue(createCell(row, row.getPhysicalNumberOfCells()), "");
//
setCellValue(createCell(row, row.getPhysicalNumberOfCells()), "");
//
} // if
//
if ((cell = createCell(row, row.getPhysicalNumberOfCells())) != null) {
//
setAddress(hyperlink = createHyperlink(creationHelper, HyperlinkType.URL), library.url);
//
cell.setHyperlink(hyperlink);
//
} // if
//
setCellValue(cell, library.url);
//
if (StringUtils.length(library.url) == maxUrlLength) {
//
sheet.autoSizeColumn(row.getPhysicalNumberOfCells() - 1);
//
} // if
//
} // if
//
} // for
//
} // for
//
for (int i = 0; i < IterableUtils.size(dayOfWeeks) && sheet != null; i++) {
//
setFillBackgroundColor(
createPatternFormatting(
cfr = createConditionalFormattingRule(scf = sheet.getSheetConditionalFormatting(),
String.format("=INDIRECT(ADDRESS(1,%1$s))=TEXT(TODAY(),\"dddd\")", 5 + i * 3))),
IndexedColors.YELLOW.getIndex());
//
addConditionalFormatting(scf, new CellRangeAddress[] { new CellRangeAddress(0, 1
// sheet.getPhysicalNumberOfRows() - 1
, 4 + i * 3, 6 + i * 3) }, cfr);
//
} // for
//
if (sheet != null) {
//
sheet.setAutoFilter(new CellRangeAddress(0, sheet.getPhysicalNumberOfRows() - 1, 0,
6 + IterableUtils.size(dayOfWeeks) * 3));
//
} // if
//
wb.write(os);
//
System.out.println(file.getAbsolutePath());
//
System.out.println(stopwatch != null ? stopwatch.stop() : null);
//
} // try
//
}
private static void setAddress(final Hyperlink instance, final String address) {
if (instance != null) {
instance.setAddress(address);
}
}
private static Hyperlink createHyperlink(final CreationHelper instance, final HyperlinkType type) {
return instance != null ? instance.createHyperlink(type) : null;
}
private static org.apache.poi.ss.usermodel.Cell createCell(final Row instance, final int column) {
return instance != null ? instance.createCell(column) : null;
}
private static LocalDateTime atDate(final LocalTime instance, final LocalDate localDate) {
return instance != null ? instance.atDate(localDate) : null;
}
private static <L> L getLeft(final Triple<L, ?, ?> instance) {
return instance != null ? instance.getLeft() : null;
}
private static <M> M getMiddle(final Triple<?, M, ?> instance) {
return instance != null ? instance.getMiddle() : null;
}
private static <R> R getRight(final Triple<?, ?, R> instance) {
return instance != null ? instance.getRight() : null;
}
private static int addConditionalFormatting(final SheetConditionalFormatting instance,
final CellRangeAddress[] regions, final ConditionalFormattingRule rule) {
return instance != null ? instance.addConditionalFormatting(regions, rule) : 0;
}
private static void setFillBackgroundColor(final PatternFormatting instance, final short bg) {
if (instance != null) {
instance.setFillBackgroundColor(bg);
}
}
private static PatternFormatting createPatternFormatting(final ConditionalFormattingRule instance) {
return instance != null ? instance.createPatternFormatting() : null;
}
private static ConditionalFormattingRule createConditionalFormattingRule(final SheetConditionalFormatting instance,
final String formula) {
return instance != null ? instance.createConditionalFormattingRule(formula) : null;
}
private static DataFormat createDataFormat(final CreationHelper instance) {
return instance != null ? instance.createDataFormat() : null;
}
private static short getFormat(final DataFormat instance, final String format) {
return instance != null ? instance.getFormat(format) : 0;
}
private static <K, V> Collection<V> get(final Multimap<K, V> instance, final K key) {
return instance != null ? instance.get(key) : null;
}
private static <K, V> Map<K, Collection<V>> asMap(final Multimap<K, V> instance) {
return instance != null ? instance.asMap() : null;
}
private static <K, V> Collection<Entry<K, V>> entrySet(final Map<K, V> instance) {
return instance != null ? instance.entrySet() : null;
}
private static <V> V getValue(final Entry<?, V> instance) {
return instance != null ? instance.getValue() : null;
}
private static void setCellStyle(final org.apache.poi.ss.usermodel.Cell instance, final CellStyle style) {
if (instance != null) {
instance.setCellStyle(style);
}
}
private static String getDisplayName(final DayOfWeek instance, final TextStyle style, final Locale lcoale) {
return instance != null ? instance.getDisplayName(style, lcoale) : null;
}
private static <K> Set<K> keySet(final Multimap<K, ?> instance) {
return instance != null ? instance.keySet() : null;
}
private static int orElse(final OptionalInt instance, final int defaultValue) {
return instance != null ? instance.orElse(defaultValue) : defaultValue;
}
private static OptionalInt max(final IntStream instance) {
return instance != null ? instance.max() : null;
}
private static <T> IntStream mapToInt(final Stream<T> instance, final ToIntFunction<? super T> function) {
return instance != null ? instance.mapToInt(function) : null;
}
private static void setCellValue(final org.apache.poi.ss.usermodel.Cell instance, final LocalDateTime value) {
if (instance != null) {
instance.setCellValue(value);
}
}
private static void setCellValue(final org.apache.poi.ss.usermodel.Cell instance, final boolean value) {
if (instance != null) {
instance.setCellValue(value);
}
}
private static void setCellValue(final org.apache.poi.ss.usermodel.Cell instance, final String value) {
if (instance != null) {
instance.setCellValue(value);
}
}
private static List<Library> getLibraries() throws IOException, URISyntaxException {
//
List<Library> libraries = null;
//
final Table<String, String, String> table = getDistrictUrls();
//
if (table != null && table.cellSet() != null && table.cellSet().iterator() != null) {
//
Map<String, String> map = null;
//
ObjectMapper objectMapper = null;
//
Library library = null;
//
int openingHoursSize, openingHoursMaxSize = 0;
//
for (final Cell<String, String, String> cell : table.cellSet()) {
//
if (cell == null || (map = getLibrariesUrls(cell.getValue())) == null || entrySet(map) == null
|| entrySet(map).iterator() == null) {
//
continue;
//
} // if
//
for (final Entry<String, String> entry : entrySet(map)) {
//
if (entry == null) {
//
continue;
//
} // if
//
if (objectMapper == null) {
//
objectMapper = JsonMapper.builder()
.changeDefaultVisibility(
x -> x != null ? x.withVisibility(PropertyAccessor.ALL, Visibility.ANY) : x)
.build();
//
} // if
//
if ((library = getLibrary(getValue(entry))) != null) {
//
library.area = cell.getRowKey();
//
openingHoursMaxSize = Math.max(openingHoursMaxSize,
openingHoursSize = IterableUtils.size(keySet(library.openingHours)));
//
if (openingHoursMaxSize != openingHoursSize) {
//
throw new RuntimeException(StringUtils.joinWith(" ",
writeValueAsString(objectMapper, library), openingHoursSize, openingHoursMaxSize));
//
} // if
//
add(libraries = ObjectUtils.getIfNull(libraries, ArrayList::new), library);
//
} // if
//
} // for
//
} // for
//
} // if
//
return libraries;
//
}
private static String writeValueAsString(final ObjectMapper instance, final Object value) {
return instance != null ? instance.writeValueAsString(value) : null;
}
private static Library getLibrary(final String url) throws MalformedURLException, IOException, URISyntaxException {
//
final Document document = Jsoup.parse(new URI(url).toURL(), 0);
//
List<Node> ns = childNodes(testAndApply(x -> IterableUtils.size(x) == 1,
select(document, "div.breadcrumb_area"), x -> IterableUtils.get(x, 0), null));
//
Node n = null;
//
String text = null;
//
Library library = null;
//
final int size = IterableUtils.size(ns);
//
for (int i = 0; i < size; i++) {
//
// url
//
if ((library = ObjectUtils.getIfNull(library, Library::new)) != null) {
//
library.url = url;
//
} // if
//
// district
//
if ((n = IterableUtils.get(ns, i)) instanceof Element e && e != null
&& !contains(Arrays.asList(">", "Home", "Locate Libraries", "Library", "Libraries"), text = text(e))
&& (library = ObjectUtils.getIfNull(library, Library::new)) != null) {
//
if (library.district != null) {
//
throw new RuntimeException();
//
} // if
//
library.district = text;
//
} // if
//
// name
//
if (i == size - 1 && (library = ObjectUtils.getIfNull(library, Library::new)) != null) {
//
if (library.name != null) {
//
throw new RuntimeException();
//
} // if
//
library.name = StringUtils.trim(replace(text(Jsoup.parse(n.nodeValue())), ">", ""));
//
} // if
//
} // for
//
// address
//
List<Element> es = toList(filter(stream(select(document, "h3")),
x -> x != null && Objects.equals(x.nodeName(), "h3") && Objects.equals(x.nodeValue(), "Address")));
//
if (IterableUtils.size(es) > 1) {
//
throw new RuntimeException();
//
} // if
//
if ((library = ObjectUtils.getIfNull(library, Library::new)) != null) {
//
library.address = text(Jsoup.parse(text(nextElementSibling(
testAndApply(x -> IterableUtils.size(x) == 1, es, x -> IterableUtils.get(x, 0), null)))));
//
} // if
//
// Opening Hours
//
es = toList(filter(stream(select(document, "h2")), x -> x != null && Objects.equals(x.nodeName(), "h2")
&& Objects.equals(x.nodeValue(), "Opening Hours")));
//
if (IterableUtils.size(es) > 1) {
//
throw new RuntimeException();
//
} // if
//
es = children(nextElementSibling(
testAndApply(x -> IterableUtils.size(x) == 1, es, x -> IterableUtils.get(x, 0), null)));
//
Element e = null;
//
DayOfWeek dayOfWeek = null;
//
String[] ss = null;
//
String week = null;
//
LocalTime opening, ending = null;
//
Multimap<DayOfWeek, OpeningHour> openingHours = null;
//
OpeningHour openingHour = null;
//
for (int i = 0; i < IterableUtils.size(es); i++) {
//
if ((e = IterableUtils.get(es, i)) == null) {
//
continue;
//
} // if
//
if (e.hasClass("week")) {
//
dayOfWeek = getDayOfWeek(week = text(e));
//
} else if (e.hasClass("time")) {
//
if ((ss = StringUtils.splitByWholeSeparator(text = text(e), " - ")) != null && ss.length == 2) {
//
opening = toLocalTime(ArrayUtils.get(ss, 0));
//
ending = toLocalTime(ArrayUtils.get(ss, 1));
//
if (dayOfWeek != null) {
//
(openingHour = new OpeningHour()).open = Boolean.TRUE;
//
openingHour.opening = opening;
//
openingHour.ending = ending;
//
put(openingHours = ObjectUtils.getIfNull(openingHours, LinkedHashMultimap::create), dayOfWeek,
openingHour);
//
} else if ((library = ObjectUtils.getIfNull(library, Library::new)) != null) {
//
library.publicHolidayOpeningHour = Triple.of(week, opening, ending);
//
} // if
//
} else if (Objects.equals(text, "Closed")) {
//
(openingHour = new OpeningHour()).open = Boolean.FALSE;
//
put(openingHours = ObjectUtils.getIfNull(openingHours, LinkedHashMultimap::create), dayOfWeek,
openingHour);
//
} else if ((ns = childNodes(e)) != null && ns.size() == 3) {
//
for (int j = 0; j < IterableUtils.size(ns); j++) {
//
if ((n = IterableUtils.get(ns, j)) == null) {
//
continue;
//
} // if
//
if ((ss = StringUtils.splitByWholeSeparator(text = n.nodeValue(), " - ")) != null
&& ss.length == 2) {
//
opening = toLocalTime(ArrayUtils.get(ss, 0));
//
ending = toLocalTime(ArrayUtils.get(ss, 1));
//
if (dayOfWeek != null) {
//
(openingHour = new OpeningHour()).open = Boolean.TRUE;
//
openingHour.opening = opening;
//
openingHour.ending = ending;
//
put(openingHours = ObjectUtils.getIfNull(openingHours, LinkedHashMultimap::create),
dayOfWeek, openingHour);
//
} else {
//
throw new RuntimeException(text);
//
} // if
//
} // if
//
} // for
//
} else {
//
throw new RuntimeException(text);
//
} // if
//
} // if
//
} // for
//
if ((library = ObjectUtils.getIfNull(library, Library::new)) != null) {
//
library.openingHours = openingHours;
//
} // if
//
return library;
//
}
private static LocalTime toLocalTime(final String input) {
//
String s = input != null ? new String(input) : null;
//
Integer hour = testAndApply(NumberUtils::isDigits, StringUtils.substring(s, 0, 2), NumberUtils::toInt, null);
//
final Integer minute = testAndApply(NumberUtils::isDigits, StringUtils.substring(s, 3, 5), NumberUtils::toInt,
null);
//
if (Objects.equals(s = StringUtils.trim(StringUtils.substring(s, 5)), "p.m.")) {
//
hour = add(hour, 12);
//
} else if (!contains(Arrays.asList("a.m.", "noon"), s)) {
//
throw new RuntimeException(s);
//
} // if
//
if (hour != null && minute != null) {
//
return LocalTime.of(hour.intValue(), minute.intValue());
//
} // if
//
throw new RuntimeException(StringUtils.joinWith(":", hour, minute));
//
}
private static Integer add(final Number number, final int value) {
return number != null ? Integer.valueOf(number.intValue() + value) : Integer.valueOf(value);
}
private static boolean contains(final String instance, final CharSequence s) {
return instance != null && instance.contains(s);
}
private static DayOfWeek getDayOfWeek(final String text) {
//
final List<DayOfWeek> list = toList(filter(Arrays.stream(DayOfWeek.values()),
x -> x != null && x.name() != null && equalsIgnoreCase(x.name(), text)));
//
if (IterableUtils.size(list) > 1) {
//
throw new RuntimeException();
//
} // if
//
return testAndApply(x -> IterableUtils.size(x) == 1, list, x -> IterableUtils.get(x, 0), null);
//
}
private static boolean equalsIgnoreCase(final String a, final String b) {
return a != null && a.equalsIgnoreCase(b);
}
private static Elements children(final Element instance) {
return instance != null ? instance.children() : null;
}
private static Element nextElementSibling(final Element instance) {
return instance != null ? instance.nextElementSibling() : null;
}
private static String replace(final String instance, final CharSequence target, final CharSequence replacement) {
return instance != null && replacement != null ? instance.replace(target, replacement) : instance;
}
private static List<Node> childNodes(final Element instance) {
return instance != null ? instance.childNodes() : null;
}
private static Map<String, String> getLibrariesUrls(final String url)
throws MalformedURLException, IOException, URISyntaxException {
//
final List<Element> es = nextElementSiblings(testAndApply(x -> IterableUtils.size(x) == 1,
select(Jsoup.parse(new URI(url).toURL(), 0), ".regi_title"), x -> IterableUtils.get(x, 0), null));
//
Map<String, String> map = null;
//
for (int i = 0; i < IterableUtils.size(es); i++) {
//
testAndAccept((k, v) -> !containsKey(k, text(v)), map = ObjectUtils.getIfNull(map, LinkedHashMap::new),
testAndApply(x -> IterableUtils.size(x) == 1, select(IterableUtils.get(es, i), "a"),
x -> IterableUtils.get(x, 0), null),
(k, v) -> put(k, text(v), absUrl(v, "href")));
//
} // for
//
return map;
//
}
private static Elements nextElementSiblings(final Element instance) {
return instance != null ? instance.nextElementSiblings() : null;
}
private static <K, V> void put(final Multimap<K, V> instance, final K key, final V value) {
if (instance != null) {
instance.put(key, value);
}
}
private static <K, V> void put(final Map<K, V> instance, final K key, final V value) {
if (instance != null) {
instance.put(key, value);
}
}
private static boolean containsKey(final Map<?, ?> instance, final Object key) {
return instance != null && instance.containsKey(key);
}
private static Table<String, String, String> getDistrictUrls()
throws MalformedURLException, IOException, URISyntaxException {
//
final List<Element> es1 = select(Jsoup.parse(new URI(getLibrariesUrl()).toURL(), 0), ".regi_hkg");
//
List<Element> es2 = null;
//
Element e1, e2 = null;
//
Table<String, String, String> table = null;
//
String row, column = null;
//
for (int i = 0; i < IterableUtils.size(es1); i++) {
//
if ((e1 = IterableUtils.get(es1, i)) == null
|| (table = ObjectUtils.getIfNull(table, HashBasedTable::create)) == null) {
//
continue;
//
} // if
//
row = text(select(e1, ".regi_title"));
//
es2 = select(e1, "a");
//
for (int j = 0; j < IterableUtils.size(es2); j++) {
//
if (!contains(table, row, column = text(e2 = IterableUtils.get(es2, j)))) {
//
put(table, row, column, absUrl(e2, "href"));
//
} // if
//
} // for
//
} // for
//
return table;
//
}
private static <R, C, V> void put(final Table<R, C, V> instance, final R rowKey, final C columnKey, final V value) {
if (instance != null) {
instance.put(rowKey, columnKey, value);
}
}
private static boolean contains(final Table<?, ?, ?> instance, final Object rowKey, final Object columnKey) {
return instance != null && instance.contains(rowKey, columnKey);
}
private static String getLibrariesUrl() throws MalformedURLException, IOException, URISyntaxException {
//
List<Element> es = toList(
filter(stream(select(Jsoup.parse(new URI("https://www.hkpl.gov.hk/en/").toURL(), 0), "li a")),
x -> Objects.equals(text(x), "Libraries")));
//
List<String> ss = null;
//
for (int i = 0; i < IterableUtils.size(es); i++) {
//
testAndAccept((a, b) -> !contains(a, b), ss = ObjectUtils.getIfNull(ss, ArrayList::new),
absUrl(IterableUtils.get(es, i), "href"), Hkpl::add);
//
} // for
//
if (IterableUtils.size(ss) > 1) {
//
throw new RuntimeException();
//
} // if
//
return testAndApply(x -> IterableUtils.size(x) == 1, ss, x -> IterableUtils.get(x, 0), null);
//
}
private static <T, R> R testAndApply(final Predicate<T> predicate, final T value, final Function<T, R> functionTrue,
final Function<T, R> functionFalse) {
return predicate != null && predicate.test(value) ? apply(functionTrue, value) : apply(functionFalse, value);
}
private static <T, R> R apply(final Function<T, R> instance, final T value) {
return instance != null ? instance.apply(value) : null;
}
private static <T, U> void testAndAccept(final BiPredicate<T, U> predicate, final T t, final U u,
final BiConsumer<T, U> consumer) {
if (predicate != null && predicate.test(t, u) && consumer != null) {
consumer.accept(t, u);
}
}
private static <E> void add(final Collection<E> instance, final E item) {
if (instance != null) {
instance.add(item);
}
}
private static boolean contains(final Collection<?> instance, final Object item) {
return instance != null && instance.contains(item);
}
private static String absUrl(final Node instance, final String attributeKey) {
return instance != null ? instance.absUrl(attributeKey) : null;
}
private static <T> List<T> toList(final Stream<T> instance) {
return instance != null ? instance.toList() : null;
}
private static String text(final Elements instance) {
return instance != null ? instance.text() : null;
}
private static String text(final Element instance) {
return instance != null ? instance.text() : null;
}
private static <T> Stream<T> filter(final Stream<T> instance, final Predicate<? super T> predicate) {
return instance != null ? instance.filter(predicate) : instance;
}
private static <T> Stream<T> stream(final Collection<T> instance) {
return instance != null ? instance.stream() : null;
}
private static Elements select(final Element instance, final String cssQuery) {
return instance != null ? instance.select(cssQuery) : null;
}
}
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
</properties>
<dependencies>
<!--https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.23.2</version>
</dependency>
<!--https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.6.0</version>
</dependency><!--https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.21.0</version>
</dependency>
<!--https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.7.2-jre</version>
</dependency>
<!--https://mvnrepository.com/artifact/tools.jackson.core/jackson-databind -->
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>3.2.4</version>
</dependency>
<!--https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.5.1</version>
</dependency>
</dependencies>
@asdf913

asdf913 commented Oct 23, 2026

Copy link
Copy Markdown
Author

@asdf913

asdf913 commented Oct 23, 2026 •

Copy link
Copy Markdown
Author

Area, District, Name, Address and Opening Hours

image The spreadsheet will highlight the weekday (i.e. Friday) columns which match the week day of current date image If the current time is between the opening hour and ending hour, both opening hour and ending hour will be highlighted. image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment