Snippets
Revised by
Yclept Nemo
4e151fe
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 | // Copyright
// 2016 Yclept Nemo <pscjtwjdjtAhnbjm/dpn>
// License
// Apache 2.0 or GPL (compatible with Boilerpipe and Recoll)
// Internal:
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Locale;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
// External:
import org.apache.commons.cli.*;
import com.kohlschutter.boilerpipe.BoilerpipeProcessingException;
import com.kohlschutter.boilerpipe.sax.BoilerpipeSAXInput;
import com.kohlschutter.boilerpipe.sax.HTMLHighlighter;
import com.kohlschutter.boilerpipe.sax.ImageExtractor;
import com.kohlschutter.boilerpipe.document.TextDocument;
import com.kohlschutter.boilerpipe.document.Image;
import com.kohlschutter.boilerpipe.extractors.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.jsoup.Jsoup;
import org.jsoup.parser.Tag;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Document;
import org.mozilla.universalchardet.UniversalDetector;
// CheckedInputStream:
// author:
// rinde
// source:
// http://stackoverflow.com/a/35139613/2626865
// notes:
// Solves "Invalidate Stream without Closing"
final class CheckedInputStream extends InputStream {
final InputStream delegate;
boolean validated;
public CheckedInputStream(InputStream stream) {
delegate = stream;
validated = true;
}
public void invalidate() {
validated = false;
}
void checkValidated() {
if (!validated) {
throw new IllegalStateException("Stream is invalidated.");
}
}
@Override
public int read() throws IOException {
checkValidated();
return delegate.read();
}
@Override
public int read(byte b[]) throws IOException {
checkValidated();
return delegate.read(b, 0, b.length);
}
@Override
public int read(byte b[], int off, int len) throws IOException {
checkValidated();
return delegate.read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
checkValidated();
return delegate.skip(n);
}
@Override
public int available() throws IOException {
checkValidated();
return delegate.available();
}
@Override
public void close() throws IOException {
checkValidated();
delegate.close();
}
@Override
public synchronized void mark(int readlimit) {
checkValidated();
delegate.mark(readlimit);
}
@Override
public synchronized void reset() throws IOException {
checkValidated();
delegate.reset();
}
@Override
public boolean markSupported() {
checkValidated();
return delegate.markSupported();
}
}
class UnrecognizedArgumentException extends ParseException {
private Option option;
private String argument;
public UnrecognizedArgumentException(String message) {
super(message);
}
public UnrecognizedArgumentException(Option option, String argument) {
this(String.format
( "Unrecognized argument \"%s\" for option \"%s\""
, argument
, option.getLongOpt() == null
? option.getOpt()
: option.getLongOpt()
)
);
this.option = option;
this.argument = argument;
}
public Option getOption() {
return option;
}
public String getArgument() {
return argument;
}
}
class ExclusiveOptionsException extends ParseException {
private Option option_a;
private Option option_b;
public ExclusiveOptionsException(String message) {
super(message);
}
public ExclusiveOptionsException(Option option_a, Option option_b) {
this(String.format
( "Latter option \"%s\" conflicts with former option \"%s\""
, option_a.getLongOpt() == null
? option_a.getOpt()
: option_a.getLongOpt()
, option_b.getLongOpt() == null
? option_b.getOpt()
: option_b.getLongOpt()
)
);
this.option_a = option_a;
this.option_b = option_b;
}
public Option getOptionFormer() {
return option_a;
}
public Option getOptionLatter() {
return option_b;
}
}
class BoilerpipeInterface {
private final TextDocument document;
private final ExtractorBase extractor;
// Constructor
public BoilerpipeInterface(ExtractorBase extractor, String string) throws BoilerpipeProcessingException {
this(extractor, new StringReader(string));
}
public BoilerpipeInterface(ExtractorBase extractor, Reader reader) throws BoilerpipeProcessingException {
this(extractor, new InputSource(reader));
}
public BoilerpipeInterface(ExtractorBase extractor, InputSource source) throws BoilerpipeProcessingException {
try {
this.document = new BoilerpipeSAXInput(source).getTextDocument();
}
catch (SAXException e) {
throw new BoilerpipeProcessingException(e);
}
this.extractor = extractor;
this.extractor.process(this.document);
}
// text()
public String text() {
return document.getContent();
}
// html()
public String html(String string) throws BoilerpipeProcessingException {
return html(new StringReader(string));
}
public String html(Reader reader) throws BoilerpipeProcessingException {
return html(new InputSource(reader));
}
public String html(InputSource source) throws BoilerpipeProcessingException {
return HTMLHighlighter.newExtractingInstance().process(document, source);
}
// highlight()
public String highlight(String string) throws BoilerpipeProcessingException {
return highlight(new StringReader(string));
}
public String highlight(Reader reader) throws BoilerpipeProcessingException {
return highlight(new InputSource(reader));
}
public String highlight(InputSource source) throws BoilerpipeProcessingException {
return HTMLHighlighter.newHighlightingInstance().process(document, source);
}
// images()
public List<Image> images(String string) throws BoilerpipeProcessingException {
return images(new StringReader(string));
}
public List<Image> images(Reader reader) throws BoilerpipeProcessingException {
return images(new InputSource(reader));
}
public List<Image> images(InputSource source) throws BoilerpipeProcessingException {
return ImageExtractor.INSTANCE.process(this.document, source);
}
}
class BoilerpipeArguments {
// from org.jsoup.helper.DataUtil, as we are re-implementing jsoup's
// encoding detection. See below for more details.
private static final Pattern charset_pattern = Pattern.compile("(?i)\\bcharset=\\s*(?:\"|')?([^\\s,;\"']+)");
private static final Map<byte[], String> map_bom;
static {
Map<byte[], String> map_bom_t = new HashMap<byte[], String>();
map_bom_t.put(new byte[] {(byte)0xEF, (byte)0xBB, (byte)0xBF}, "UTF-8");
map_bom_t.put(new byte[] {(byte)0xFE, (byte)0xFF}, "UTF-16BE");
map_bom_t.put(new byte[] {(byte)0xFF, (byte)0xFE}, "UTF-16LE");
map_bom_t.put(new byte[] {(byte)0x00, (byte)0x00, (byte)0xFE, (byte)0xFF}, "UTF-32BE");
map_bom_t.put(new byte[] {(byte)0xFF, (byte)0xFE, (byte)0x00, (byte)0x00}, "UTF-32LE");
// UTF-7: 7-bit schemes: the last two bits of the fourth byte are not
// used, so all possible combinations are listed. As the UTF-7 BOM is
// insufficiently unique (standard ASCII/UTF-8 characters) and UTF-7 is
// intended to be base64 encoded, heuristic algorithms (ie, character
// frequency) should supplement or replace detection via the BOM.
// Therefore, UTF-7 BOM detection is disabled.
//map_bom_t.put(new byte[] {(byte)0x2B, (byte)0x2F, (byte)0x76, (byte)0x38}, "UTF-7");
//map_bom_t.put(new byte[] {(byte)0x2B, (byte)0x2F, (byte)0x76, (byte)0x39}, "UTF-7");
//map_bom_t.put(new byte[] {(byte)0x2B, (byte)0x2F, (byte)0x76, (byte)0x2B}, "UTF-7");
//map_bom_t.put(new byte[] {(byte)0x2B, (byte)0x2F, (byte)0x76, (byte)0x38}, "UTF-7");
map_bom_t.put(new byte[] {(byte)0xF7, (byte)0x64, (byte)0x4c}, "UTF-1");
map_bom_t.put(new byte[] {(byte)0xDD, (byte)0x73, (byte)0x66, (byte)0x73}, "UTF-EBCDIC");
// SCSU: SCSU uses U+FEFF (the UTF-16/32 BOM) as the "Signature Byte
// Sequence", however U+FEFF has multiple encodings in SCSU. The
// preferred encoding of U+FEFF for the "Signature Byte Sequence" is
// listed and used below, as per UTR#6.
map_bom_t.put(new byte[] {(byte)0x0E, (byte)0xFE, (byte)0xFF}, "SCSU");
map_bom_t.put(new byte[] {(byte)0xFB, (byte)0xEE, (byte)0x28}, "BOCU-1");
map_bom_t.put(new byte[] {(byte)0x84, (byte)0x31, (byte)0x95, (byte)0x33}, "GB-18030");
map_bom = Collections.unmodifiableMap(map_bom_t);
}
private static final Options options = new Options();
static {
Option option_help = Option.builder("h")
.longOpt("help")
.desc("display help")
.required(false)
.build();
Option option_output = Option.builder("o")
.longOpt("output")
.desc("output path")
.required(false)
.hasArg()
.argName("output-path")
.build();
Option option_extractor = Option.builder("e")
.longOpt("extractor")
.desc("extractor, default 'ArticleExtractor'")
.required(false)
.hasArg()
.argName("extractor")
.build();
Option option_wrap = Option.builder("w")
.longOpt("wrap")
.desc("wrap output with html derived from the original document (incompatible with: \"highlight\")")
.required(false)
.build();
Option option_markup = Option.builder("m")
.longOpt("markup")
.desc("extract content with enclosing markup (incompatible with: \"highlight\", \"images\")")
.required(false)
.build();
Option option_highlight = Option.builder("l")
.longOpt("highlight")
.desc("highlight content blocks of the original document (incompatible with: \"markup\", \"images\" + \"wrap\")")
.required(false)
.build();
Option option_images = Option.builder("i")
.longOpt("images")
.desc("extract content-enclosed images as links (incompatible with: \"markup\", \"highlight\")")
.required(false)
.build();
OptionGroup option_group_boilerpipe = new OptionGroup();
option_group_boilerpipe.addOption(option_markup);
option_group_boilerpipe.addOption(option_highlight);
option_group_boilerpipe.addOption(option_images);
options.addOption(option_help);
options.addOption(option_output);
options.addOption(option_extractor);
options.addOption(option_wrap);
options.addOptionGroup(option_group_boilerpipe);
}
private final CommandLine commandline;
private Boolean markup = null;
private Boolean highlight = null;
private Boolean images = null;
private Boolean help = null;
private Boolean wrap = null;
private BufferedWriter output = null;
private RandomAccessFile input = null;
private ExtractorBase extractor = null;
private Charset output_charset = Charset.forName("UTF-8");
private Charset input_charset = null;
// Constructors
public BoilerpipeArguments(CommandLine commandline) throws ParseException {
this.commandline = commandline;
check();
}
public BoilerpipeArguments(String[] arguments) throws ParseException {
this(new DefaultParser().parse(options, arguments));
}
// Getters (static)
public static Options options() {
assert (options!= null);
return options;
}
// Getters
public boolean markup() {
if (this.markup == null) {
set_markup();
}
return this.markup.booleanValue();
}
public boolean highlight() {
if (this.highlight == null) {
set_highlight();
}
return this.highlight.booleanValue();
}
public boolean images() {
if (this.images == null) {
set_images();
}
return this.images.booleanValue();
}
public boolean help() {
if (this.help == null) {
set_help();
}
return this.help.booleanValue();
}
public boolean wrap() {
if (this.wrap == null) {
set_wrap();
}
return this.wrap.booleanValue();
}
public BufferedWriter output() throws IOException {
if (this.output == null) {
set_output();
}
return this.output;
}
public RandomAccessFile input() throws ParseException, IOException {
if (this.input == null) {
set_input();
}
return this.input;
}
public ExtractorBase extractor() throws ParseException, IOException {
if (this.extractor == null) {
set_extractor();
}
return this.extractor;
}
public Charset output_charset() {
assert (this.output_charset != null);
return this.output_charset;
}
public Charset input_charset()
throws ParseException,
IOException,
IllegalCharsetNameException,
UnsupportedCharsetException {
if (this.input_charset == null) {
set_input_charset();
}
return this.input_charset;
}
public CheckedInputStream input_stream() throws ParseException, IOException {
return new CheckedInputStream(new FileInputStream(this.input().getFD()));
}
// Setters
private void set_markup() {
if (this.commandline.hasOption("m")) {
this.markup = Boolean.TRUE;
} else {
this.markup = Boolean.FALSE;
}
}
private void set_highlight() {
if (this.commandline.hasOption("l")) {
this.highlight = Boolean.TRUE;
} else {
this.highlight = Boolean.FALSE;
}
}
private void set_images() {
if (this.commandline.hasOption("i")) {
this.images = Boolean.TRUE;
} else {
this.images = Boolean.FALSE;
}
}
private void set_help() {
if (this.commandline.hasOption("h")) {
this.help = Boolean.TRUE;
} else {
this.help = Boolean.FALSE;
}
}
private void set_wrap() {
if (this.commandline.hasOption("w")) {
this.wrap = Boolean.TRUE;
} else {
this.wrap = Boolean.FALSE;
}
}
private void set_output() throws IOException {
String output_path = "";
boolean output_path_use = false;
if (this.commandline.hasOption("o")) {
output_path = this.commandline.getOptionValue("o");
}
if (output_path.length() > 0 && !output_path.equals("-")) {
output_path_use = true;
}
if (output_path_use) {
this.output = new BufferedWriter
( new OutputStreamWriter
( new FileOutputStream(output_path)
, output_charset()
)
);
} else {
this.output = new BufferedWriter
( new OutputStreamWriter
( System.out
)
);
}
}
private void set_input() throws ParseException, IOException {
List<String> parameters = this.commandline.getArgList();
if (parameters.size() != 1) {
throw new MissingArgumentException("Missing parameter: input-path");
}
this.input = new RandomAccessFile(parameters.get(0), "r");
}
private void set_extractor() throws ParseException, IOException {
ExtractorBase extractor = ArticleExtractor.INSTANCE;
String exception_message = "Invalid Boilerpipe Extractor \"%s\": %s";
if (this.commandline.hasOption("e")) {
String extractor_string = this.commandline.getOptionValue("e");
if (!is_valid_identifier(extractor_string)) {
throw new UnrecognizedArgumentException(String.format(exception_message, extractor_string, "invalid identifier"));
}
String extractor_package = "com.kohlschutter.boilerpipe.extractors.";
// Not all derived classes provide getInstance()
//try {
// Class<?> extractor_class = Class.forName(extractor_package + extractor_string);
// Method extractor_method = extractor_class.getDeclaredMethod("getInstance", ExtractorBase.class);
// extractor = extractor_method.invoke(null);
//}
//catch (ClassNotFoundException|IllegalAccessException|NoSuchMethodException|InvocationTargetException e) {
// System.exit(10);
//}
try {
Class<?> extractor_class = Class.forName(extractor_package + extractor_string);
Field extractor_field = extractor_class.getDeclaredField("INSTANCE");
Object extractor_object = extractor_field.get(ExtractorBase.class);
extractor = ExtractorBase.class.cast(extractor_object);
}
catch (ClassNotFoundException|NoSuchFieldException|IllegalAccessException e) {
throw new UnrecognizedArgumentException(String.format(exception_message, extractor_string, "no such extractor"));
}
}
this.extractor = extractor;
}
private void set_input_charset()
throws ParseException,
IOException,
IllegalCharsetNameException,
UnsupportedCharsetException {
CheckedInputStream stream1 = input_stream();
CheckedInputStream stream2 = input_stream();
CheckedInputStream stream3 = input_stream();
String encoding = null;
if (encoding == null) {
encoding = encoding_from_bom(stream1);
}
this.input().seek(0);
if (encoding == null) {
encoding = encoding_from_html(stream2);
}
this.input().seek(0);
if (encoding == null) {
encoding = encoding_detect(stream3);
}
this.input().seek(0);
if (encoding == null) {
encoding = Charset.defaultCharset().name();
}
this.input().seek(0);
assert !stream1.validated;
assert !stream2.validated;
assert !stream3.validated;
assert (encoding != null);
this.input_charset = charset_from_string(encoding);
}
// Miscellaneous functions
public void close() throws IOException {
if (this.input != null) {
this.input.close();
}
if (this.output != null) {
this.output.close();
}
}
public void check() throws ExclusiveOptionsException {
if (commandline.hasOption("w") && commandline.hasOption("l")) {
throw new ExclusiveOptionsException(options.getOption("w"), options.getOption("l"));
}
}
// Miscellaneous functions (static)
public static String help(String application, String error) {
StringWriter sw = new StringWriter();
StringBuffer sb = sw.getBuffer();
PrintWriter pw = new PrintWriter(sw, true);
HelpFormatter formatter = new HelpFormatter();
formatter.printUsage(pw, 80, application, options);
sb.deleteCharAt(sb.length() - 1);
sb.append(" input-path");
sb.append("\n\n");
sb.append("Boilerpipe command-line wrapper");
sb.append("\n\n");
sb.append(String.join("\n"
, "positional arguments:"
, " input-path"));
sb.append("\n\n");
sb.append("optional arguments:\n");
formatter.printOptions(pw, 80, options, 4, 4);
if (error != null && error.length() > 0) {
sb.append("\n" + error + "\n");
}
return sw.toString();
}
// Support Methods (static)
static boolean is_valid_identifier(String s) {
if (s == null || s.length() == 0) {
return false;
}
if (!Character.isJavaIdentifierStart(s.charAt(0))) {
return false;
}
for (int i=1; i<s.length(); i++) {
if (!Character.isJavaIdentifierPart(s.charAt(i))) {
return false;
}
}
return true;
}
static String encoding_from_bom(CheckedInputStream stream) throws IOException {
byte[] bom;
int bom_read;
int bom_length = 0;
int bom_offset = 0;
for (byte[] key : map_bom.keySet()) {
if (key.length > bom_length) {
bom_length = key.length;
}
}
bom = new byte[bom_length];
while ((bom_read = stream.read(bom, bom_offset, bom_length)) > 0) {
bom_length -= bom_read;
bom_offset += bom_read;
}
stream.invalidate();
for (Map.Entry<byte[], String> entry : map_bom.entrySet()) {
if (equals(bom, entry.getKey(), 0)) {
return entry.getValue();
}
}
return null;
}
static String encoding_detect(CheckedInputStream stream) throws IOException {
UniversalDetector detector = new UniversalDetector(null);
byte[] buffer = new byte[4096];
int bytes_read;
while ((bytes_read = stream.read(buffer)) > 0 && !detector.isDone()) {
detector.handleData(buffer, 0, bytes_read);
}
detector.dataEnd();
String encoding = detector.getDetectedCharset();
detector.reset();
stream.invalidate();
return encoding;
}
// Since org.jsoup.nodes.Document.OutputSettings:charset defaults to
// UTF-8 if no charset is specified in the document, reimplement
// jsoup's charset detection (org.jsoup.helper.DataUtil:parseByteData)
static String encoding_from_html(CheckedInputStream stream) throws IOException {
Document document = Jsoup.parse(stream, null, "");
Element meta = document.select("meta[http-equiv=content-type], meta[charset]").first();
String encoding = null;
if (meta != null) {
if (encoding == null && meta.hasAttr("http-equiv")) {
encoding = encoding_from_content_type(meta.attr("content"));
}
if (encoding != null && !encoding_is_legal(encoding)) {
encoding = null;
}
if (encoding == null && meta.hasAttr("charset")) {
encoding = meta.attr("charset");
}
if (encoding != null && !encoding_is_legal(encoding)) {
encoding = null;
}
}
stream.invalidate();
return encoding;
}
static String encoding_from_content_type(String s) {
Matcher charset_matcher = charset_pattern.matcher(s);
String charset = null;
if (charset_matcher.matches()) {
charset = charset_matcher.group(1);
assert !charset.isEmpty();
}
return charset;
}
static boolean encoding_is_legal(String s) {
boolean legal = true;
try {
Charset.isSupported(s);
}
catch (IllegalCharsetNameException e) {
legal = false;
}
return legal;
}
static Charset charset_from_string(String s)
throws IllegalCharsetNameException,
UnsupportedCharsetException {
Charset charset = null;
try {
try {
charset = Charset.forName(s);
}
catch (IllegalCharsetNameException|UnsupportedCharsetException e) {
charset = Charset.forName(s.toUpperCase(Locale.ENGLISH));
}
}
catch (IllegalCharsetNameException e) {
throw new IllegalCharsetNameException("Illegal charset name: " + e.getMessage());
}
catch (UnsupportedCharsetException e) {
throw new UnsupportedCharsetException("Unsupported charset: " + e.getMessage());
}
return charset;
}
static boolean equals(byte[] a, byte[] b, int n) {
if (a == null) {
return (b == null);
}
int n_a = n <= 0 ? a.length : Math.min(n, a.length);
int n_b = n <= 0 ? b.length : Math.min(n, b.length);
ByteBuffer bb_a = ByteBuffer.wrap(a, 0, n_a);
ByteBuffer bb_b = ByteBuffer.wrap(b, 0, n_b);
return bb_a.equals(bb_b);
}
}
class BoilerpipeHandler {
private static final String html_metadata;
static {
String[] metadata_tags =
{ "head > title"
, "head > base"
, "head > meta[name=application-name]"
, "head > meta[name=author]"
, "head > meta[name=description]"
, "head > meta[name=keywords]"
, "head > link[rel=alternate]"
, "head > link[rel=author]"
, "head > link[rel=icon]"
, "head > link[rel=license]"
, "head > link[rel=next]"
, "head > link[rel=pref]"
, "head > link[rel=search]"
, "head > link[rel=canonical]"
};
html_metadata = String.join(", ", metadata_tags);
}
private static boolean body_markup = false;
static String error_string(String component, String error) {
return String.join(": ", "Error", component, error);
}
static void error_print(String component, String error) {
System.err.println(error_string(component, error));
}
static void help(String error) {
System.err.print
( BoilerpipeArguments.help
( "BoilerpipeHandler"
, error != null && error.length() > 0
? error_string("Command-line", error)
: null
)
);
}
static void process_arguments(BoilerpipeArguments arguments) {
if (arguments.help()) {
help(null);
System.exit(0);
}
}
static String process_boilerpipe_images(List<Image> images) {
Element container = new Element(Tag.valueOf("body"), "");
for (Image image : images) {
Element child = new Element(Tag.valueOf("img"), "");
if (image.getSrc() != null) {
child.attr("src", image.getSrc());
}
if (image.getWidth() != null) {
child.attr("width", image.getWidth());
}
if (image.getHeight() != null) {
child.attr("height", image.getHeight());
}
if (image.getAlt() != null) {
child.attr("alt", image.getAlt());
}
container.appendChild(child);
}
return container.html();
}
static String process_boilerpipe(BoilerpipeArguments arguments)
throws ParseException,
IOException,
BoilerpipeProcessingException {
Charset charset = arguments.input_charset();
CheckedInputStream stream = arguments.input_stream();
BufferedReader reader_a = new BufferedReader
( new InputStreamReader
( stream
, charset
)
);
BufferedReader reader_b = new BufferedReader
( new InputStreamReader
( stream
, charset
)
);
BoilerpipeInterface boilerpipe_interface = new BoilerpipeInterface
( arguments.extractor()
, reader_a
);
arguments.input().seek(0);
String output;
if (arguments.markup()) {
output = boilerpipe_interface.html(reader_b);
body_markup = true;
}
else if (arguments.highlight()) {
output = boilerpipe_interface.highlight(reader_b);
body_markup = true;
}
else if (arguments.images()) {
List<Image> images = boilerpipe_interface.images(reader_b);
output = process_boilerpipe_images(images);
body_markup = true;
}
else {
output = boilerpipe_interface.text();
body_markup = false;
}
stream.invalidate();
arguments.input().seek(0);
return output;
}
static Document process_wrap_shell(BoilerpipeArguments arguments)
throws ParseException,
IOException,
BoilerpipeProcessingException {
Charset charset = arguments.input_charset();
CheckedInputStream stream = arguments.input_stream();
Document document_source = Jsoup.parse(stream, charset.name(), "");
stream.invalidate();
arguments.input().seek(0);
Document document_target = Document.createShell("");
document_target.charset(arguments.output_charset());
Element head_source = document_source.getElementsByTag("head").first();
if (head_source != null) {
Element head_target = document_target.getElementsByTag("head").first();
assert (head_target != null);
for(Element elem : head_source.select(html_metadata)) {
if (elem.hasAttr("http-equiv") || elem.hasAttr("charset")) {
continue;
}
head_target.appendChild(elem);
}
}
return document_target;
}
static String process_wrap(BoilerpipeArguments arguments)
throws ParseException,
IOException,
BoilerpipeProcessingException {
Document document = process_wrap_shell(arguments);
String contents = process_boilerpipe(arguments);
Element body = document.getElementsByTag("body").first();
assert (body != null);
if (body_markup) {
body.html(contents);
} else {
body.text(contents);
}
return document.toString();
}
static String ensure_eol_terminated(String s) {
if (!s.endsWith(System.lineSeparator())) {
s = s + System.lineSeparator();
}
return s;
}
public static void main(String[] argv) {
try {
BoilerpipeArguments arguments = new BoilerpipeArguments(argv);
process_arguments(arguments);
String output = process_boilerpipe(arguments);
if (arguments.wrap()) {
output = process_wrap(arguments);
}
output = ensure_eol_terminated(output);
arguments.output().write(output);
arguments.close();
}
catch (ParseException e) {
help(e.getMessage());
System.exit(1);
}
catch (IOException e) {
error_print("IO", e.getMessage());
System.exit(2);
}
catch (IllegalCharsetNameException|UnsupportedCharsetException e) {
error_print("Charset", e.getMessage());
System.exit(3);
}
catch (BoilerpipeProcessingException e) {
error_print("Boilerpipe", e.getMessage());
System.exit(4);
}
}
}
|
You can clone a snippet to your computer for local editing. Learn more.