Java tutorial
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.carlomicieli.footballdb.starter.parsers; import io.github.carlomicieli.footballdb.starter.documents.DocumentDownloader; import io.github.carlomicieli.footballdb.starter.documents.DocumentNotFoundException; import io.github.carlomicieli.footballdb.starter.documents.PathBuilder; import org.apache.commons.lang3.Validate; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.OptionalInt; import java.util.function.Function; import java.util.Optional; /** * It represents a parser for NFL.com pages. * * @author Carlo Micieli */ public abstract class Parser<T> { private final DocumentDownloader documentsDownloader; protected Parser(DocumentDownloader docs) { Validate.notNull(docs, "A DocumentDownloader is required"); this.documentsDownloader = docs; } /** * It parses the document at the provided path. * <p> * The actual meaning for the <code>path</code> is determined by * the concrete implementation of <code>DocumentDownloaded</code>. * </p> * <p> * This method is not enforce validation for the path. It solely assume * the provided value is not empty. A more tight validation could be performed * by concrete implementation of <code>DocumentDownloaded</code>. * </p> * * @param path * @return */ public Optional<T> parse(String path) { return parse(path, pathBuilder()); } public Optional<T> parse(String path, PathBuilder pathBuilder) { Validate.notBlank(path, "A path value is required."); String url = pathBuilder.build(path); Document doc = documentsDownloader.from(url).orElseThrow(DocumentNotFoundException::new); return Optional.ofNullable(parseDocument(doc)); } protected abstract T parseDocument(Document doc); protected abstract PathBuilder pathBuilder(); protected static Optional<String> childValueAsString(Element e, int index) { return valueFromChild(e, index); } protected static Optional<Integer> childValueAsInt(Element e, int index) { return valueFromChild(e, index).map(Integer::parseInt); } protected static Optional<String> valueFromChild(Element e, int index) { Elements children = e.children(); if (index > children.size()) return Optional.empty(); return Optional.ofNullable(children.get(index).text()); } }