From 4b3dc853d4887ea76602b106a3715ddfa8b42b14 Mon Sep 17 00:00:00 2001 From: Sylvain Jermini Date: Sat, 11 Jul 2020 14:56:31 +0200 Subject: [PATCH] remove unused classes/code, raw parameter type, misc. cleanup --- .../context/StylesheetFactoryImpl.java | 1 - .../openhtmltopdf/css/constants/CSSName.java | 9 +- .../openhtmltopdf/css/constants/Idents.java | 451 +----------------- .../css/constants/ValueConstants.java | 3 +- .../css/newmatch/CascadedStyle.java | 6 +- .../openhtmltopdf/css/newmatch/Condition.java | 2 +- .../openhtmltopdf/css/parser/CSSParser.java | 2 +- .../com/openhtmltopdf/css/parser/Lexer.java | 8 +- .../openhtmltopdf/css/parser/MakeTokens.java | 15 +- .../property/AbstractPropertyBuilder.java | 6 - .../css/parser/property/Conversions.java | 20 +- .../css/style/CalculatedStyle.java | 2 +- .../com/openhtmltopdf/layout/BoxBuilder.java | 12 +- .../openhtmltopdf/layout/BoxRangeHelper.java | 10 +- .../openhtmltopdf/layout/BoxRangeLists.java | 4 +- .../layout/LineBreakContext.java | 2 +- .../openhtmltopdf/layout/StyleTracker.java | 6 +- .../com/openhtmltopdf/newtable/TableBox.java | 2 +- .../protocols/data/DataURLConnection.java | 219 --------- .../openhtmltopdf/protocols/data/Handler.java | 44 -- .../com/openhtmltopdf/render/BlockBox.java | 2 +- .../java/com/openhtmltopdf/render/Box.java | 4 +- .../openhtmltopdf/render/InlineLayoutBox.java | 2 +- .../com/openhtmltopdf/render/PageBox.java | 16 +- .../ArrayDisplayListContainer.java | 2 +- .../displaylist/DisplayListCollector.java | 2 +- .../render/displaylist/TransformCreator.java | 2 +- .../simple/NoNamespaceHandler.java | 4 +- .../extend/form/AbstractButtonField.java | 4 +- .../simple/extend/form/FormField.java | 6 +- .../simple/extend/form/FormFieldState.java | 4 +- .../simple/extend/form/ImageField.java | 4 +- .../simple/extend/form/SelectField.java | 4 +- .../openhtmltopdf/simple/xhtml/XhtmlForm.java | 4 +- .../xhtml/controls/AbstractControl.java | 17 +- .../simple/xhtml/controls/CheckControl.java | 4 +- .../openhtmltopdf/swing/AWTFontResolver.java | 7 +- .../com/openhtmltopdf/swing/DOMInspector.java | 12 +- .../openhtmltopdf/swing/ImageLoadQueue.java | 6 +- .../com/openhtmltopdf/util/ArrayUtil.java | 4 +- .../com/openhtmltopdf/util/Configuration.java | 17 +- .../openhtmltopdf/util/DownscaleQuality.java | 6 +- .../com/openhtmltopdf/util/GeneralUtil.java | 5 - .../com/openhtmltopdf/util/ImageUtil.java | 74 +-- .../com/openhtmltopdf/util/JDKXRLogger.java | 22 +- .../com/openhtmltopdf/util/LoggerUtil.java | 40 +- .../openhtmltopdf/util/ScalingOptions.java | 4 +- .../com/openhtmltopdf/util/ThreadCtx.java | 7 +- .../util/XRSimpleLogFormatter.java | 2 +- .../layout/BreakerTestSupport.java | 2 +- .../src/main/java/ListFontFamilyNames.java | 5 +- .../src/main/java/VerifyGlyphExists.java | 12 +- .../TemplateAuthorGuideGenerator.java | 2 - .../JsoupNonVisualRegressionTest.java | 3 +- .../NonVisualRegressionTest.java | 3 +- .../api/BufferedImagePageProcessor.java | 4 +- .../objects/pdf/MergeBackgroundPdfDrawer.java | 13 +- .../pdfboxout/PdfBoxFontResolver.java | 5 +- .../openhtmltopdf/pdfboxout/PdfBoxForm.java | 11 +- .../openhtmltopdf/pdfboxout/PdfBoxImage.java | 7 +- .../pdfboxout/PdfBoxRenderer.java | 10 +- .../PdfBoxReplacedElementFactory.java | 3 - .../pdfboxout/PdfBoxUserAgent.java | 1 - .../svgsupport/OpenHtmlGvtFont.java | 3 - .../svgsupport/OpenHtmlGvtFontFamily.java | 6 - 65 files changed, 152 insertions(+), 1049 deletions(-) delete mode 100644 openhtmltopdf-core/src/main/java/com/openhtmltopdf/protocols/data/DataURLConnection.java delete mode 100644 openhtmltopdf-core/src/main/java/com/openhtmltopdf/protocols/data/Handler.java diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/StylesheetFactoryImpl.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/StylesheetFactoryImpl.java index 378e7947e..ff1023c9a 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/StylesheetFactoryImpl.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/StylesheetFactoryImpl.java @@ -24,7 +24,6 @@ import java.util.logging.Level; import com.openhtmltopdf.css.extend.StylesheetFactory; -import com.openhtmltopdf.css.parser.CSSErrorHandler; import com.openhtmltopdf.css.parser.CSSParser; import com.openhtmltopdf.css.sheet.Ruleset; import com.openhtmltopdf.css.sheet.Stylesheet; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/CSSName.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/CSSName.java index bcb088fbd..2fa7ea6a5 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/CSSName.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/CSSName.java @@ -26,7 +26,6 @@ import java.util.Objects; import java.util.logging.Level; -import com.openhtmltopdf.css.parser.CSSErrorHandler; import com.openhtmltopdf.css.parser.CSSParser; import com.openhtmltopdf.css.parser.PropertyValue; import com.openhtmltopdf.css.parser.property.BackgroundPropertyBuilder; @@ -62,22 +61,22 @@ public final class CSSName implements Comparable { /** * marker var, used for initialization */ - private static final Integer PRIMITIVE = new Integer(0); + private static final Integer PRIMITIVE = Integer.valueOf(0); /** * marker var, used for initialization */ - private static final Integer SHORTHAND = new Integer(1); + private static final Integer SHORTHAND = Integer.valueOf(1); /** * marker var, used for initialization */ - private static final Integer INHERITS = new Integer(2); + private static final Integer INHERITS = Integer.valueOf(2); /** * marker var, used for initialization */ - private static final Integer NOT_INHERITED = new Integer(3); + private static final Integer NOT_INHERITED = Integer.valueOf(3); /** * Used to assing unique int id values to new CSSNames created in this class diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/Idents.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/Idents.java index 166cce15c..d2d9fd592 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/Idents.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/Idents.java @@ -19,13 +19,7 @@ */ package com.openhtmltopdf.css.constants; -import com.openhtmltopdf.util.XRRuntimeException; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; +import java.util.*; import java.util.regex.Pattern; @@ -60,143 +54,17 @@ public final class Idents { */ private final static String RCSS_LENGTH = "((0$)|((" + RCSS_NUMBER + ")+" + "((em)|(ex)|(px)|(cm)|(mm)|(in)|(pt)|(pc)|(%))))"; - /** - * Pattern instance, for CSS lengths - */ - private final static Pattern CSS_NUMBER_PATTERN = Pattern.compile(RCSS_NUMBER); /** * Pattern instance, for CSS lengths */ private final static Pattern CSS_LENGTH_PATTERN = Pattern.compile(RCSS_LENGTH); - /** - * Pattern instance, for Hex-colors - */ - private final static Pattern COLOR_HEX_PATTERN = Pattern.compile("#((((\\d)|[a-fA-F]){6})|(((\\d)|[a-fA-F]){3}))"); - - /** - * Pattern instance for functions (not quite right [e.g no escapes], but good enough) - */ - private final static Pattern FUNCTION_PATTERN = Pattern.compile("^-?[_a-z][_a-z0-9-]+\\("); - - /** - * Description of the Field - */ - private final static Map COLOR_MAP; - /** - * Description of the Field - */ - private final static Map FONT_SIZES; - /** - * Description of the Field - */ - private final static Map FONT_WEIGHTS; - /** - * Description of the Field - */ - private final static Map BORDER_WIDTHS; - /** - * Description of the Field - */ - private final static Map BACKGROUND_POSITIONS; - /** - * Description of the Field - */ - private final static List BACKGROUND_REPEATS; - /** - * Description of the Field - */ - private final static List BORDER_STYLES; - /** - * Description of the Field - */ - private final static List LIST_TYPES; /** * Description of the Field */ - private final static List FONT_STYLES; - - /** - * Description of the Field - */ - private final static List BACKGROUND_POSITIONS_IDENTS; - - /** - * Description of the Method - * - * @param cssName PARAM - * @param ident PARAM - * @return Returns - */ - public static String convertIdent(CSSName cssName, String ident) { - if (ident.equals("inherit")) { - return ident; - } - - String val = ident; - - if (cssName == CSSName.FONT_SIZE) { - String size = FONT_SIZES.get(ident); - val = (size == null ? ident : size); - } else if (cssName == CSSName.FONT_WEIGHT) { - String size = FONT_WEIGHTS.get(ident); - val = (size == null ? ident : size); - } else if (cssName == CSSName.BACKGROUND_POSITION) { - String pos = BACKGROUND_POSITIONS.get(ident); - val = (pos == null ? ident : pos); - } else if ( - cssName == CSSName.BORDER_BOTTOM_WIDTH || - cssName == CSSName.BORDER_LEFT_WIDTH || - cssName == CSSName.BORDER_RIGHT_WIDTH || - cssName == CSSName.BORDER_WIDTH_SHORTHAND || - cssName == CSSName.BORDER_TOP_WIDTH) { - - String size = BORDER_WIDTHS.get(ident); - val = (size == null ? ident : size); - } else if ( - cssName == CSSName.BORDER_BOTTOM_COLOR || - cssName == CSSName.BORDER_LEFT_COLOR || - cssName == CSSName.BORDER_RIGHT_COLOR || - cssName == CSSName.BORDER_COLOR_SHORTHAND || - cssName == CSSName.BORDER_TOP_COLOR || - cssName == CSSName.BACKGROUND_COLOR || - cssName == CSSName.COLOR || - cssName == CSSName.OUTLINE_COLOR) { - - val = getColorHex(ident); - - //may fail because someone tried an invalid color - if (val == null) { - String fallback = CSSName.initialValue(cssName); - if (fallback.startsWith("=")) fallback = CSSName.initialValue(CSSName.getByPropertyName(fallback.substring(1))); - val = getColorHex(fallback); - } - - } - return val; - } - - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeABorderStyle(String val) { - return BORDER_STYLES.contains(val); - } + private final static Set BACKGROUND_POSITIONS_IDENTS = new HashSet<>(Arrays.asList("top", "center", "bottom", "right", "left")); - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeAColor(String val) { - return COLOR_MAP.get(val) != null || (val.startsWith("#") && (val.length() == 7 || val.length() == 4)) || val.startsWith("rgb"); - } - /** * Description of the Method * @@ -207,39 +75,6 @@ public static boolean looksLikeALength(String val) { return CSS_LENGTH_PATTERN.matcher(val).matches(); } - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeAURI(String val) { - return val.startsWith("url(") && val.endsWith(")"); - } - - public static boolean looksLikeAFunction(String value) { - return FUNCTION_PATTERN.matcher(value).find(); - } - - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeABGRepeat(String val) { - return BACKGROUND_REPEATS.indexOf(val) >= 0; - } - - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeABGAttachment(String val) { - return "scroll".equals(val) || "fixed".equals(val); - } /** * Description of the Method @@ -251,288 +86,6 @@ public static boolean looksLikeABGPosition(String val) { return BACKGROUND_POSITIONS_IDENTS.contains(val) || looksLikeALength(val); } - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeAListStyleType(String val) { - return LIST_TYPES.indexOf(val) >= 0; - } - - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeAListStyleImage(String val) { - return "none".equals(val) || looksLikeAURI(val); - } - - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeAListStylePosition(String val) { - return "inside".equals(val) || "outside".equals(val); - } - - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeAFontStyle(String val) { - return FONT_STYLES.indexOf(val) >= 0; - } - - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeAFontVariant(String val) { - return "normal".equals(val) || "small-caps".equals(val); - } - - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeAFontWeight(String val) { - return FONT_WEIGHTS.get(val) != null; - } - - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeAFontSize(String val) { - // TODO - return FONT_SIZES.get(val) != null || - looksLikeALength(val) || - "larger".equals(val) || "smaller".equals(val); - } - - /** - * Description of the Method - * - * @param val PARAM - * @return Returns - */ - public static boolean looksLikeALineHeight(String val) { - return "normal".equals(val) || looksLikeALength(val) || looksLikeANumber(val); - } - - public static boolean looksLikeANumber(String val) { - return CSS_NUMBER_PATTERN.matcher(val).matches(); - } - - /** - * Given a String, returns either the rgb declaration for the color, or the - * hex declaration; used to cleanup assignments like "red" or "green". - * - * @param value A String which contains a Color identifier, an rgb - * assignment or a Color hex value. - * @return The colorHex value - */ - public static String getColorHex(String value) { - if (value == null) { - throw new XRRuntimeException("value is null on getColorHex()"); - } - String retval = COLOR_MAP.get(value.toLowerCase()); - if (retval == null) { - if (value.trim().startsWith("rgb(")) { - retval = value; - } else { - Matcher m = COLOR_HEX_PATTERN.matcher(value); - if (m.matches()) { - retval = value; - } - } - } - return retval; - } - - static { - COLOR_MAP = new HashMap<>(); - /* From CSS 2.1- 4.3.6: Colors - aqua #00ffff - black #000000 - blue #0000ff - fuchsia #ff00ff - gray #808080 - green #008000 - lime #00ff00 - maroon #800000 - navy #000080 - olive #808000 - orange #ffA500 - purple #800080 - red #ff0000 - silver #c0c0c0 - teal #008080 - white #ffffff - yellow #ffff00 - */ - COLOR_MAP.put("aqua", "#00ffff"); - COLOR_MAP.put("black", "#000000"); - COLOR_MAP.put("blue", "#0000ff"); - COLOR_MAP.put("fuchsia", "#ff00ff"); - COLOR_MAP.put("gray", "#808080"); - COLOR_MAP.put("green", "#008000"); - COLOR_MAP.put("lime", "#00ff00"); - COLOR_MAP.put("maroon", "#800000"); - COLOR_MAP.put("navy", "#000080"); - COLOR_MAP.put("olive", "#808000"); - COLOR_MAP.put("orange", "#ffa500"); - COLOR_MAP.put("purple", "#800080"); - COLOR_MAP.put("red", "#ff0000"); - COLOR_MAP.put("silver", "#c0c0c0"); - COLOR_MAP.put("teal", "#008080"); - COLOR_MAP.put("transparent", "transparent"); - COLOR_MAP.put("white", "#ffffff"); - COLOR_MAP.put("yellow", "#ffff00"); - - //TODO: FONT_SIZES should be determined by the User Interface! - FONT_SIZES = new HashMap<>(); - FONT_SIZES.put("xx-small", "6.9pt"); - FONT_SIZES.put("x-small", "8.3pt"); - FONT_SIZES.put("small", "10pt"); - FONT_SIZES.put("medium", "12pt"); - FONT_SIZES.put("large", "14.4pt"); - FONT_SIZES.put("x-large", "17.3pt"); - FONT_SIZES.put("xx-large", "20.7pt"); - - // HACK - FONT_SIZES.put("smaller", "0.8em"); - FONT_SIZES.put("larger", "1.2em"); - - FONT_WEIGHTS = new HashMap<>(); - FONT_WEIGHTS.put("normal", "400"); - FONT_WEIGHTS.put("bold", "700"); - FONT_WEIGHTS.put("100", "100"); - FONT_WEIGHTS.put("200", "200"); - FONT_WEIGHTS.put("300", "300"); - FONT_WEIGHTS.put("400", "400"); - FONT_WEIGHTS.put("500", "500"); - FONT_WEIGHTS.put("600", "600"); - FONT_WEIGHTS.put("700", "700"); - FONT_WEIGHTS.put("800", "800"); - FONT_WEIGHTS.put("900", "900"); - FONT_WEIGHTS.put("bolder", "bolder"); - FONT_WEIGHTS.put("lighter", "lighter"); - // NOTE: 'bolder' and 'lighter' need to be handled programmatically - - BORDER_WIDTHS = new HashMap<>(); - BORDER_WIDTHS.put("thin", "1px"); - BORDER_WIDTHS.put("medium", "2px"); - BORDER_WIDTHS.put("thick", "3px"); - - BACKGROUND_POSITIONS_IDENTS = new ArrayList<>(); - BACKGROUND_POSITIONS_IDENTS.add("top"); - BACKGROUND_POSITIONS_IDENTS.add("center"); - BACKGROUND_POSITIONS_IDENTS.add("bottom"); - BACKGROUND_POSITIONS_IDENTS.add("right"); - BACKGROUND_POSITIONS_IDENTS.add("left"); - BACKGROUND_POSITIONS = new HashMap<>(); - - // NOTE: combinations of idents for background-positions, are specified in the CSS - // spec; some are disallowed, for example, there is no "top" all by itself. Check - // the CSS spec for background (shorthand) or background-position for a complete list. - // The percentages specified here are from that section of the spec. - BACKGROUND_POSITIONS.put("top left", "0% 0%"); - BACKGROUND_POSITIONS.put("left top", "0% 0%"); - - BACKGROUND_POSITIONS.put("top center", "50% 0%"); - BACKGROUND_POSITIONS.put("center top", "50% 0%"); - - BACKGROUND_POSITIONS.put("right top", "100% 0%"); - BACKGROUND_POSITIONS.put("top right", "100% 0%"); - - BACKGROUND_POSITIONS.put("left center", "0% 50%"); - BACKGROUND_POSITIONS.put("center left", "0% 50%"); - - BACKGROUND_POSITIONS.put("center", "50% 50%"); - BACKGROUND_POSITIONS.put("center center", "50% 50%"); - - BACKGROUND_POSITIONS.put("right center", "100% 50%"); - BACKGROUND_POSITIONS.put("center right", "100% 50%"); - - BACKGROUND_POSITIONS.put("bottom left", "0% 100%"); - BACKGROUND_POSITIONS.put("left bottom", "0% 100%"); - - BACKGROUND_POSITIONS.put("bottom center", "50% 100%"); - BACKGROUND_POSITIONS.put("center bottom", "50% 100%"); - - BACKGROUND_POSITIONS.put("bottom right", "100% 100%"); - BACKGROUND_POSITIONS.put("right bottom", "100% 100%"); - - BACKGROUND_REPEATS = new ArrayList<>(); - BACKGROUND_REPEATS.add("repeat"); - BACKGROUND_REPEATS.add("repeat-x"); - BACKGROUND_REPEATS.add("repeat-y"); - BACKGROUND_REPEATS.add("no-repeat"); - - BORDER_STYLES = new ArrayList<>(); - BORDER_STYLES.add("none"); - BORDER_STYLES.add("hidden"); - BORDER_STYLES.add("dotted"); - BORDER_STYLES.add("dashed"); - BORDER_STYLES.add("solid"); - BORDER_STYLES.add("double"); - BORDER_STYLES.add("groove"); - BORDER_STYLES.add("ridge"); - BORDER_STYLES.add("inset"); - BORDER_STYLES.add("outset"); - - LIST_TYPES = new ArrayList<>(); - LIST_TYPES.add("disc"); - LIST_TYPES.add("circle"); - LIST_TYPES.add("square"); - LIST_TYPES.add("decimal"); - LIST_TYPES.add("decimal-leading-zero"); - LIST_TYPES.add("lower-roman"); - LIST_TYPES.add("upper-roman"); - LIST_TYPES.add("lower-greek"); - LIST_TYPES.add("lower-alpha"); - LIST_TYPES.add("lower-latin"); - LIST_TYPES.add("upper-alpha"); - LIST_TYPES.add("upper-latin"); - LIST_TYPES.add("hebrew"); - LIST_TYPES.add("armenian"); - LIST_TYPES.add("georgian"); - LIST_TYPES.add("cjk-ideographic"); - LIST_TYPES.add("hiragana"); - LIST_TYPES.add("katakana"); - LIST_TYPES.add("hiragana-iroha"); - LIST_TYPES.add("katakana-iroha"); - LIST_TYPES.add("none"); - - FONT_STYLES = new ArrayList<>(); - FONT_STYLES.add("normal"); - FONT_STYLES.add("italic"); - FONT_STYLES.add("oblique"); - - }// end static - - public static boolean looksLikeAQuote(String content) { - return content.equals("open-quote") || content.equals("close-quote"); - } - - public static boolean looksLikeASkipQuote(String content) { - return content.equals("no-open-quote") || content.equals("no-close-quote"); - } }// end class /* diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/ValueConstants.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/ValueConstants.java index fe1a43631..e87962428 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/ValueConstants.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/constants/ValueConstants.java @@ -21,7 +21,6 @@ package com.openhtmltopdf.css.constants; import com.openhtmltopdf.css.parser.CSSPrimitiveValue; -import com.openhtmltopdf.css.parser.CSSValue; import com.openhtmltopdf.util.GeneralUtil; import com.openhtmltopdf.util.LogMessageId; import com.openhtmltopdf.util.XRLog; @@ -163,7 +162,7 @@ public static boolean isNumber(short cssPrimitiveType) { SortedMap map = new TreeMap<>(); TYPE_DESCRIPTIONS = new ArrayList<>(); try { - Field fields[] = CSSPrimitiveValue.class.getFields(); + Field[] fields = CSSPrimitiveValue.class.getFields(); for (int i = 0; i < fields.length; i++) { Field f = fields[i]; int mod = f.getModifiers(); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/CascadedStyle.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/CascadedStyle.java index 7092d16ea..13e951645 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/CascadedStyle.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/CascadedStyle.java @@ -123,7 +123,7 @@ public static PropertyDeclaration createLayoutPropertyDeclaration( } private CascadedStyle(CascadedStyle startingPoint, Iterator props) { - cascadedProperties = new TreeMap(startingPoint.cascadedProperties); + cascadedProperties = new TreeMap<>(startingPoint.cascadedProperties); addProperties(props); } @@ -134,7 +134,7 @@ private CascadedStyle(CascadedStyle startingPoint, Iterator * properties. */ private CascadedStyle() { - cascadedProperties = new TreeMap(); + cascadedProperties = new TreeMap<>(); } /** * Creates a CascadedStyle, setting the display property to @@ -162,7 +162,7 @@ private void addProperties(java.util.Iterator iter) { PropertyDeclaration prop = iter.next(); List bucket = buckets[prop.getImportanceAndOrigin()]; if (bucket == null) { - bucket = new ArrayList(); + bucket = new ArrayList<>(); buckets[prop.getImportanceAndOrigin()] = bucket; } bucket.add(prop); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/Condition.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/Condition.java index 26eee220b..47e3205a6 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/Condition.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/Condition.java @@ -527,7 +527,7 @@ private static String[] split(String s, char ch) { if (s.indexOf(ch) == -1) { return new String[] { s }; } else { - List result = new ArrayList(); + List result = new ArrayList<>(); int last = 0; int next = 0; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParser.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParser.java index e46084d59..b3e26da98 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParser.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParser.java @@ -1346,7 +1346,7 @@ private void prio() throws IOException { // ; private List expr(boolean literal) throws IOException { //System.out.println("expr()"); - List result = new ArrayList(10); + List result = new ArrayList<>(10); result.add(term(literal)); LOOP: while (true) { Token t = la(); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/Lexer.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/Lexer.java index 7f0cb990f..614e12ab7 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/Lexer.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/Lexer.java @@ -1457,7 +1457,7 @@ private static int zzUnpackTrans(String packed, int offset, int [] result) { private static final int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ - private static final String ZZ_ERROR_MSG[] = { + private static final String[] ZZ_ERROR_MSG = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" @@ -1466,7 +1466,7 @@ private static int zzUnpackTrans(String packed, int offset, int [] result) { /** * ZZ_ATTRIBUTE[aState] contains the attributes of state aState */ - private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + private static final int[] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\1\0\2\1\1\11\12\1\1\11\1\1\1\11\3\1"+ @@ -1512,7 +1512,7 @@ private static int zzUnpackAttribute(String packed, int offset, int [] result) { /** this buffer contains the current text to be matched and is the source of the yytext() string */ - private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + private char[] zzBuffer = new char[ZZ_BUFFERSIZE]; /** the textposition at the last accepting state */ private int zzMarkedPos; @@ -1625,7 +1625,7 @@ private boolean zzRefill() throws java.io.IOException { /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ - char newBuffer[] = new char[zzCurrentPos*2]; + char[] newBuffer = new char[zzCurrentPos*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/MakeTokens.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/MakeTokens.java index 08a9e35a6..b4a6440ee 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/MakeTokens.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/MakeTokens.java @@ -33,23 +33,12 @@ public class MakeTokens { public static final void main(String[] args) throws IOException { List tokens = new ArrayList<>(); - - BufferedReader reader = null; - try { - reader = new BufferedReader(new InputStreamReader( - new FileInputStream(INPUT))); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(INPUT)))){ String s; while ( (s = reader.readLine()) != null) { tokens.add(s); } - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - // ignore - } - } } StringBuilder buf = new StringBuilder(); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/AbstractPropertyBuilder.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/AbstractPropertyBuilder.java index ccd20397d..88fcc6d4b 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/AbstractPropertyBuilder.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/AbstractPropertyBuilder.java @@ -140,12 +140,6 @@ protected void checkAngleType(CSSName cssName, CSSPrimitiveValue value) { } } - protected void checkStringType(CSSName cssName, CSSPrimitiveValue value) { - if (value.getPrimitiveType() != CSSPrimitiveValue.CSS_STRING) { - throw new CSSParseException("Value for " + cssName + " must be a string", -1); - } - } - protected void checkIdentOrString(CSSName cssName, CSSPrimitiveValue value) { short type = value.getPrimitiveType(); if (type != CSSPrimitiveValue.CSS_STRING && type != CSSPrimitiveValue.CSS_IDENT) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/Conversions.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/Conversions.java index 2183af866..af9acef02 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/Conversions.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/Conversions.java @@ -176,15 +176,15 @@ public class Conversions { } static { - NUMERIC_FONT_WEIGHTS.put(new Float(100f), IdentValue.FONT_WEIGHT_100); - NUMERIC_FONT_WEIGHTS.put(new Float(200f), IdentValue.FONT_WEIGHT_200); - NUMERIC_FONT_WEIGHTS.put(new Float(300f), IdentValue.FONT_WEIGHT_300); - NUMERIC_FONT_WEIGHTS.put(new Float(400f), IdentValue.FONT_WEIGHT_400); - NUMERIC_FONT_WEIGHTS.put(new Float(500f), IdentValue.FONT_WEIGHT_500); - NUMERIC_FONT_WEIGHTS.put(new Float(600f), IdentValue.FONT_WEIGHT_600); - NUMERIC_FONT_WEIGHTS.put(new Float(700f), IdentValue.FONT_WEIGHT_700); - NUMERIC_FONT_WEIGHTS.put(new Float(800f), IdentValue.FONT_WEIGHT_800); - NUMERIC_FONT_WEIGHTS.put(new Float(900f), IdentValue.FONT_WEIGHT_900); + NUMERIC_FONT_WEIGHTS.put(Float.valueOf(100f), IdentValue.FONT_WEIGHT_100); + NUMERIC_FONT_WEIGHTS.put(Float.valueOf(200f), IdentValue.FONT_WEIGHT_200); + NUMERIC_FONT_WEIGHTS.put(Float.valueOf(300f), IdentValue.FONT_WEIGHT_300); + NUMERIC_FONT_WEIGHTS.put(Float.valueOf(400f), IdentValue.FONT_WEIGHT_400); + NUMERIC_FONT_WEIGHTS.put(Float.valueOf(500f), IdentValue.FONT_WEIGHT_500); + NUMERIC_FONT_WEIGHTS.put(Float.valueOf(600f), IdentValue.FONT_WEIGHT_600); + NUMERIC_FONT_WEIGHTS.put(Float.valueOf(700f), IdentValue.FONT_WEIGHT_700); + NUMERIC_FONT_WEIGHTS.put(Float.valueOf(800f), IdentValue.FONT_WEIGHT_800); + NUMERIC_FONT_WEIGHTS.put(Float.valueOf(900f), IdentValue.FONT_WEIGHT_900); } static { @@ -198,7 +198,7 @@ public static FSRGBColor getColor(String ident) { } public static IdentValue getNumericFontWeight(float weight) { - return NUMERIC_FONT_WEIGHTS.get(new Float(weight)); + return NUMERIC_FONT_WEIGHTS.get(Float.valueOf(weight)); } public static PropertyValue getBorderWidth(String ident) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/CalculatedStyle.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/CalculatedStyle.java index 52d8ed374..5d53012b7 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/CalculatedStyle.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/CalculatedStyle.java @@ -99,7 +99,7 @@ public class CalculatedStyle { /** * Cache child styles of this style that have the same cascaded properties */ - private final java.util.Map _childCache = new java.util.HashMap(); + private final java.util.Map _childCache = new java.util.HashMap<>(); /*private java.util.HashMap _childCache = new java.util.LinkedHashMap(5, 0.75f, true) { private static final int MAX_ENTRIES = 10; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxBuilder.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxBuilder.java index 31f5c39d0..1bd296ded 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxBuilder.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxBuilder.java @@ -523,11 +523,11 @@ private static void createAnonymousTableContent(LayoutContext c, BlockBox source * If not, the table is returned. */ private static BlockBox reorderTableContent(LayoutContext c, TableBox table) { - List topCaptions = new ArrayList(); + List topCaptions = new ArrayList<>(); Box header = null; - List bodies = new ArrayList(); + List bodies = new ArrayList<>(); Box footer = null; - List bottomCaptions = new ArrayList(); + List bottomCaptions = new ArrayList<>(); for (Box b : table.getChildren()) { IdentValue display = b.getStyle().getIdent(CSSName.DISPLAY); @@ -1150,7 +1150,7 @@ private static void createChildren( Node startAttribute = working.getAttributes().getNamedItem("start"); if (startAttribute != null) { try { - start = new Integer(Integer.parseInt(startAttribute.getNodeValue()) - 1); + start = Integer.valueOf(Integer.parseInt(startAttribute.getNodeValue()) - 1); } catch (NumberFormatException e) { // ignore } @@ -1159,7 +1159,7 @@ private static void createChildren( Node valueAttribute = working.getAttributes().getNamedItem("value"); if (valueAttribute != null) { try { - start = new Integer(Integer.parseInt(valueAttribute.getNodeValue()) - 1); + start = Integer.valueOf(Integer.parseInt(valueAttribute.getNodeValue()) - 1); } catch (NumberFormatException e) { // ignore } @@ -1427,7 +1427,7 @@ private static void insertAnonymousBlocks( if (inline.size() > 0) { createAnonymousBlock(c, parent, inline, savedParents); inline = new ArrayList<>(); - savedParents = new ArrayList(parents); + savedParents = new ArrayList<>(parents); } parent.addChild((Box) child); } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeHelper.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeHelper.java index 030853e01..7ee6cdef3 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeHelper.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeHelper.java @@ -27,20 +27,20 @@ import com.openhtmltopdf.util.XRRuntimeException; public class BoxRangeHelper { - private LinkedList _clipRegionStack = new LinkedList(); + private LinkedList _clipRegionStack = new LinkedList<>(); private OutputDevice _outputDevice; - private List _rangeList; + private List _rangeList; private int _rangeIndex = 0; private BoxRangeData _current = null; - public BoxRangeHelper(OutputDevice outputDevice, List rangeList) { + public BoxRangeHelper(OutputDevice outputDevice, List rangeList) { _outputDevice = outputDevice; _rangeList = rangeList; if (rangeList.size() > 0) { - _current = (BoxRangeData)rangeList.get(0); + _current = rangeList.get(0); } } @@ -60,7 +60,7 @@ public void pushClipRegion(RenderingContext c, int contentIndex) { if (_rangeIndex == _rangeList.size() - 1) { _current = null; } else { - _current = (BoxRangeData)_rangeList.get(++_rangeIndex); + _current = _rangeList.get(++_rangeIndex); } } } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeLists.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeLists.java index 2bc367b2a..87f140ef6 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeLists.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeLists.java @@ -23,8 +23,8 @@ import java.util.List; public class BoxRangeLists { - private final List _block = new ArrayList(); - private final List _inline = new ArrayList(); + private final List _block = new ArrayList<>(); + private final List _inline = new ArrayList<>(); public List getBlock() { return _block; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/LineBreakContext.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/LineBreakContext.java index d04434894..cf1d8ec05 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/LineBreakContext.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/LineBreakContext.java @@ -25,7 +25,7 @@ * to the layout code. */ public class LineBreakContext { - public static enum LineBreakResult { + public enum LineBreakResult { CHAR_BREAKING_NEED_NEW_LINE, WORD_BREAKING_NEED_NEW_LINE, diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/StyleTracker.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/StyleTracker.java index 4a0071e42..6bd3be4ba 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/StyleTracker.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/StyleTracker.java @@ -32,7 +32,7 @@ * element. */ public class StyleTracker { - private List _styles = new ArrayList(); + private List _styles = new ArrayList<>(); public void addStyle(CascadedStyle style) { _styles.add(style); @@ -54,8 +54,8 @@ public void clearStyles() { public CalculatedStyle deriveAll(CalculatedStyle start) { CalculatedStyle result = start; - for (Iterator i = getStyles().iterator(); i.hasNext(); ) { - result = result.deriveStyle((CascadedStyle)i.next()); + for (Iterator i = getStyles().iterator(); i.hasNext(); ) { + result = result.deriveStyle(i.next()); } return result; } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/newtable/TableBox.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/newtable/TableBox.java index f2f8cf0f0..abb4f9053 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/newtable/TableBox.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/newtable/TableBox.java @@ -1863,6 +1863,6 @@ public long calcWidth() { public void setCalcWidth(long i) { _calcWidth = i; } - }; + } } } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/protocols/data/DataURLConnection.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/protocols/data/DataURLConnection.java deleted file mode 100644 index ac649dbc0..000000000 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/protocols/data/DataURLConnection.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * {{{ header & license - * Copyright (c) 2008 Sean Bright - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * }}} - */ -package com.openhtmltopdf.protocols.data; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; -import java.util.HashMap; -import java.util.Map; - -public class DataURLConnection extends URLConnection { - - private Map _headers = new HashMap(); - private byte [] _data; - - DataURLConnection(URL u) { - super(u); - } - - public void connect() throws IOException { - parseURL(); - } - - public String getContentType() { - String type = (String) _headers.get("Content-Type"); - - if (type == null) { - return "Content-Type: text/plain; charset=US-ASCII"; - } - - return type; - } - - public int getContentLength() { - if (_data == null) - return 0; - - return _data.length; - } - - public InputStream getInputStream() throws IOException { - connect(); - - if (_data == null) - return new ByteArrayInputStream(new byte [] {}); - - return new ByteArrayInputStream(_data); - } - - protected void parseURL() throws UnsupportedCharsetException { - String sub = getURL().getPath(); - - int comma = sub.indexOf(','); - - if (comma < 0) { - throw new RuntimeException("Improperly formatted data URL"); - } - - String meta = sub.substring(0, comma); - String data = sub.substring(comma + 1); - - boolean isBase64 = false; - Map properties = new HashMap(); - - properties.put("charset", "US-ASCII"); - - if (meta.length() > 0) { - String [] parts = meta.split(";"); - - if (parts.length > 0) { - int index = 0; - - // See if a media type is specified - if (meta.charAt(0) != ';') { - // We have a media type - _headers.put("Content-Type", parts[index++]); - } - - for (; index < parts.length; index++) { - if (parts[index].indexOf("=") >= 0) { - String [] nameValuePair = parts[index].split("="); - - if (nameValuePair.length > 1) { - _headers.put(nameValuePair[0], nameValuePair[1]); - } - } else { - if (parts[index].compareTo("base64") == 0) { - isBase64 = true; - } - } - } - } - } - - String charset = (String) properties.get("charset"); - - // Make sure we have a supported charset - if (!Charset.isSupported(charset)) { - throw new UnsupportedCharsetException(charset); - } - - // Now we parse the data - if (isBase64) { - _data = Base64.decode(data); - } else { - _data = URLByteDecoder.decode(data); - } - } -} - -class URLByteDecoder { - - public static byte [] decode(String s) { - - byte [] buffer = new byte [s.length()]; - - int index = 0; - int bindex = 0; - char c; - - while (index < s.length()) { - c = s.charAt(index); - - switch (c) { - case '+': - buffer[bindex++] = ' '; - break; - case '%': - buffer[bindex++] = (byte) Integer - .parseInt(s.substring(index + 1, index + 3), 16); - index += 2; - break; - default: - buffer[bindex++] = (byte) c; - break; - } - - index++; - } - - byte [] result = new byte [bindex]; - - System.arraycopy(buffer, 0, result, 0, bindex); - - return result; - } - -} - -class Base64 { - - private static String _map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - - public static byte [] decode(String s) { - - if (s == null || s.length() < 4) - return new byte [] {}; - - s = s.replaceAll("[^A-Za-z0-9\\+\\/\\=]+", ""); - - if (s.length() < 4) - return new byte [] {}; - - int padding = 0; - - if (s.charAt(s.length() - 1) == '=') - padding++; - if (s.charAt(s.length() - 2) == '=') - padding++; - - byte [] input = s.getBytes(); - byte [] output = new byte [((s.length() / 4) * 3) - padding]; - - int outputIndex = 0; - - for (int i = 0; i < input.length; i += 4) { - - int e = - _map.indexOf(input[i]) << 18 | - _map.indexOf(input[i + 1]) << 12 | - _map.indexOf(input[i + 2]) << 6 | - _map.indexOf(input[i + 3]); - - output[outputIndex++] = (byte) ((e >> 16) & 0xFF); - - if (input[i + 2] != '=') { - output[outputIndex++] = (byte) ((e >> 8) & 0xFF); - - if (input[i + 3] != '=') { - output[outputIndex++] = (byte) (e & 0xFF); - } - } - } - - return output; - } - -} diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/protocols/data/Handler.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/protocols/data/Handler.java deleted file mode 100644 index c057742a3..000000000 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/protocols/data/Handler.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * {{{ header & license - * Copyright (c) 2008 Sean Bright - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License - * as published by the Free Software Foundation; either version 2.1 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * }}} - */ -package com.openhtmltopdf.protocols.data; - -import java.io.IOException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; - -public class Handler extends URLStreamHandler { - - protected void parseURL(URL u, String spec, int start, int limit) { - String sub = spec.substring(start, limit); - - // Make sure we have a comma - if (sub.indexOf(',') < 0) { - throw new RuntimeException("Improperly formatted data URL"); - } - - setURL(u, "data", "", -1, "", "", sub, "", ""); - } - - protected URLConnection openConnection(URL u) throws IOException { - return new DataURLConnection(u); - } - -} diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/BlockBox.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/BlockBox.java index 3298678b9..82db84601 100755 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/BlockBox.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/BlockBox.java @@ -1985,7 +1985,7 @@ public void styleText(LayoutContext c) { // FIXME Should be expanded into generic restyle facility public void styleText(LayoutContext c, CalculatedStyle style) { if (getChildrenContentType() == CONTENT_INLINE) { - LinkedList styles = new LinkedList(); + LinkedList styles = new LinkedList<>(); styles.add(style); for (Object a_inlineContent : _inlineContent) { Styleable child = (Styleable) a_inlineContent; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/Box.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/Box.java index 02d9a9b45..c2bbe885e 100755 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/Box.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/Box.java @@ -233,7 +233,7 @@ public void addChildForLayout(LayoutContext c, Box child) { public void addChild(Box child) { if (_boxes == null) { - _boxes = new ArrayList(); + _boxes = new ArrayList<>(); } if (child == null) { throw new NullPointerException("trying to add null child"); @@ -682,7 +682,7 @@ public void connectChildrenToCurrentLayer(LayoutContext c) { } public List getElementBoxes(Element elem) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (int i = 0; i < getChildCount(); i++) { Box child = getChild(i); if (child.getElement() == elem) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineLayoutBox.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineLayoutBox.java index 523631f36..c8859aa84 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineLayoutBox.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineLayoutBox.java @@ -609,7 +609,7 @@ public Dimension positionRelative(CssContext cssCtx) { } // NOTE: Will be List of DisplayListItem when we delete the old renderer. - public void addAllChildren(List list, Layer layer) { + public void addAllChildren(List list, Layer layer) { for (int i = 0; i < getInlineChildCount(); i++) { Object child = getInlineChild(i); if (child instanceof Box) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/PageBox.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/PageBox.java index 61aeed496..d74d716ad 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/PageBox.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/PageBox.java @@ -462,7 +462,7 @@ public void setOuterPageWidth(int containingBlockWidth) { public int getMarginBorderPadding(CssContext cssCtx, int which) { return getStyle().getMarginBorderPadding( - cssCtx, (int)getOuterPageWidth(), which); + cssCtx, getOuterPageWidth(), which); } public PageInfo getPageInfo() { @@ -486,11 +486,11 @@ public void layout(LayoutContext c) { // HACK Would much prefer to do this in ITextRenderer or ITextOutputDevice // but given the existing API, this is about the only place it can be done private void retrievePageMetadata(LayoutContext c) { - List props = getPageInfo().getXMPPropertyList(); + List props = getPageInfo().getXMPPropertyList(); if (props != null && props.size() > 0) { - for (Iterator i = props.iterator(); i.hasNext(); ) { - PropertyDeclaration decl = (PropertyDeclaration)i.next(); + for (Iterator i = props.iterator(); i.hasNext(); ) { + PropertyDeclaration decl = i.next(); if (decl.getCSSName() == CSSName.CONTENT) { PropertyValue value = (PropertyValue)decl.getValue(); List values = value.getValues(); @@ -610,7 +610,6 @@ public TableBox getTable() { private static abstract class MarginArea { private final MarginBoxName[] _marginBoxNames; - private TableBox _table; public abstract Dimension getLayoutDimension(CssContext c, PageBox page, RectPropertySet margin); public abstract Point getPaintingPosition( @@ -624,13 +623,6 @@ public MarginArea(MarginBoxName[] marginBoxNames) { _marginBoxNames = marginBoxNames; } - public TableBox getTable() { - return _table; - } - - public void setTable(TableBox table) { - _table = table; - } public MarginBoxName[] getMarginBoxNames() { return _marginBoxNames; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/ArrayDisplayListContainer.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/ArrayDisplayListContainer.java index 023f0d74f..0282d2e7f 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/ArrayDisplayListContainer.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/ArrayDisplayListContainer.java @@ -12,7 +12,7 @@ public class ArrayDisplayListContainer extends DisplayListContainer { private final int startPage; public ArrayDisplayListContainer(int startPage, int endPage) { - this.pageInstructions = new ArrayList(endPage - startPage + 1); + this.pageInstructions = new ArrayList<>(endPage - startPage + 1); this.startPage = startPage; for (int i = 0; i < endPage - startPage + 1; i++) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/DisplayListCollector.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/DisplayListCollector.java index ca87039b4..bb8955b15 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/DisplayListCollector.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/DisplayListCollector.java @@ -24,7 +24,7 @@ import com.openhtmltopdf.render.displaylist.PagedBoxCollector.PageResult; public class DisplayListCollector { - protected static enum CollectFlags { + protected enum CollectFlags { } private final List _pages; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/TransformCreator.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/TransformCreator.java index 1c18eb771..e9584826d 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/TransformCreator.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/displaylist/TransformCreator.java @@ -21,7 +21,7 @@ */ public class TransformCreator { - private static enum TransformYOrigin { + private enum TransformYOrigin { DOCUMENT_TOP, PAGE_TOP, PAGE_BOTTOM; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/NoNamespaceHandler.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/NoNamespaceHandler.java index 111d34e7c..033c8e67a 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/NoNamespaceHandler.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/NoNamespaceHandler.java @@ -130,7 +130,7 @@ public boolean isFormElement(Element e) { private Pattern _mediaPattern = Pattern.compile("media\\s?=\\s?"); public StylesheetInfo[] getStylesheets(org.w3c.dom.Document doc) { - List list = new ArrayList(); + List list = new ArrayList<>(); //get the processing-instructions (actually for XmlDocuments) //type and href are required to be set NodeList nl = doc.getChildNodes(); @@ -181,7 +181,7 @@ public StylesheetInfo[] getStylesheets(org.w3c.dom.Document doc) { list.add(info); } - return (StylesheetInfo[])list.toArray(new StylesheetInfo[list.size()]); + return list.toArray(new StylesheetInfo[list.size()]); } public StylesheetInfo getDefaultStylesheet(StylesheetFactory factory) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/AbstractButtonField.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/AbstractButtonField.java index 7deabfe5b..e6c620bc9 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/AbstractButtonField.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/AbstractButtonField.java @@ -74,10 +74,10 @@ protected void applyComponentStyle(JButton button) { FSDerivedValue widthValue = style.valueByName(CSSName.WIDTH); if (widthValue instanceof LengthValue) - intrinsicWidth = new Integer(getBox().getContentWidth()); + intrinsicWidth = Integer.valueOf(getBox().getContentWidth()); FSDerivedValue heightValue = style.valueByName(CSSName.HEIGHT); if (heightValue instanceof LengthValue) - intrinsicHeight = new Integer(getBox().getHeight()); + intrinsicHeight = Integer.valueOf(getBox().getHeight()); } } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/FormField.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/FormField.java index 2111a2e3b..3d9da0508 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/FormField.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/FormField.java @@ -109,9 +109,9 @@ private void initialize() { if (_component != null) { if (intrinsicWidth == null) - intrinsicWidth = new Integer(_component.getPreferredSize().width); + intrinsicWidth = Integer.valueOf(_component.getPreferredSize().width); if (intrinsicHeight == null) - intrinsicHeight = new Integer(_component.getPreferredSize().height); + intrinsicHeight = Integer.valueOf(_component.getPreferredSize().height); _component.setSize(getIntrinsicSize()); @@ -220,7 +220,7 @@ public Font getFont() { protected static Integer getLengthValue(CalculatedStyle style, CSSName cssName) { FSDerivedValue widthValue = style.valueByName(cssName); if (widthValue instanceof LengthValue) { - return new Integer((int)widthValue.asFloat()); + return Integer.valueOf((int)widthValue.asFloat()); } return null; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/FormFieldState.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/FormFieldState.java index 1cfcdf3b7..5887e50dc 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/FormFieldState.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/FormFieldState.java @@ -62,13 +62,13 @@ public static FormFieldState fromBoolean(boolean b) { return stateObject; } - public static FormFieldState fromList(List list) { + public static FormFieldState fromList(List list) { FormFieldState stateObject = new FormFieldState(); int [] indices = new int [list.size()]; for (int i = 0; i < list.size(); i++) { - indices[i] = ((Integer) list.get(i)).intValue(); + indices[i] = list.get(i).intValue(); } stateObject._selected = indices; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/ImageField.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/ImageField.java index 68ca1c02b..aa0fe6b56 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/ImageField.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/ImageField.java @@ -83,12 +83,12 @@ public Dimension getPreferredSize() { FSDerivedValue widthValue = style.valueByName(CSSName.WIDTH); if (widthValue instanceof LengthValue) { - intrinsicWidth = new Integer(getBox().getContentWidth()); + intrinsicWidth = Integer.valueOf(getBox().getContentWidth()); } FSDerivedValue heightValue = style.valueByName(CSSName.HEIGHT); if (heightValue instanceof LengthValue) { - intrinsicHeight = new Integer(getBox().getHeight()); + intrinsicHeight = Integer.valueOf(getBox().getHeight()); } button.addActionListener(event -> { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/SelectField.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/SelectField.java index cd826b501..3b5a2231a 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/SelectField.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/form/SelectField.java @@ -93,7 +93,7 @@ public JComponent create() { } protected FormFieldState loadOriginalState() { - ArrayList list = new ArrayList(); + List list = new ArrayList(); NodeList options = getElement().getElementsByTagName("option"); @@ -101,7 +101,7 @@ protected FormFieldState loadOriginalState() { Element option = (Element) options.item(i); if (option.hasAttribute("selected") && option.getAttribute("selected").equalsIgnoreCase("selected")) { - list.add(new Integer(i)); + list.add(Integer.valueOf(i)); } } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlForm.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlForm.java index 8913bfb1e..7d35cf57d 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlForm.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlForm.java @@ -125,8 +125,8 @@ public void reset() { public void submit() { // TODO other encodings than urlencode? StringBuilder data = new StringBuilder(); - for (Iterator iter = getControls(); iter.hasNext();) { - FormControl control = (FormControl) iter.next(); + for (Iterator iter = getControls(); iter.hasNext();) { + FormControl control = iter.next(); if (control.isSuccessful()) { if (control.isMultiple()) { String[] values = control.getMultipleValues(); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/AbstractControl.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/AbstractControl.java index 432278592..51715a4b5 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/AbstractControl.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/AbstractControl.java @@ -20,7 +20,6 @@ package com.openhtmltopdf.simple.xhtml.controls; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.w3c.dom.Element; @@ -34,8 +33,8 @@ public abstract class AbstractControl implements FormControl { - private XhtmlForm _form; - private Element _element; + private final XhtmlForm _form; + private final Element _element; private String _name; private String _initialValue; @@ -70,21 +69,15 @@ public void resetted(XhtmlForm form) { } protected void fireChanged() { - for (Iterator iter = _listeners.iterator(); iter.hasNext();) { - ((FormControlListener) iter.next()).changed(this); - } + _listeners.forEach(l -> l.changed(this)); } protected void fireSuccessful() { - for (Iterator iter = _listeners.iterator(); iter.hasNext();) { - ((FormControlListener) iter.next()).successful(this); - } + _listeners.forEach(l -> l.successful(this)); } protected void fireEnabled() { - for (Iterator iter = _listeners.iterator(); iter.hasNext();) { - ((FormControlListener) iter.next()).enabled(this); - } + _listeners.forEach(l -> l.enabled(this)); } public void addFormControlListener(FormControlListener listener) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/CheckControl.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/CheckControl.java index 76ed11f4e..ec32e59e3 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/CheckControl.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/CheckControl.java @@ -47,9 +47,9 @@ public void setSuccessful(boolean successful) { if (form == null) { return; } - for (Iterator iter = form.getAllControls(getName()).iterator(); iter + for (Iterator iter = form.getAllControls(getName()).iterator(); iter .hasNext();) { - FormControl control = (FormControl) iter.next(); + FormControl control = iter.next(); if (control instanceof CheckControl) { CheckControl check = (CheckControl) control; if (check.isRadio() && check != this) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/AWTFontResolver.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/AWTFontResolver.java index 0c8f2d6bb..873a94133 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/AWTFontResolver.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/AWTFontResolver.java @@ -30,6 +30,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; /** @@ -42,13 +43,13 @@ public class AWTFontResolver implements FontResolver { /** * Map of concrete instances of fonts including size, weight, etc. */ - private final HashMap instanceHash = new HashMap(); + private final Map instanceHash = new HashMap<>(); /** * Map of base fonts, from which we can derive a concrete instance at the correct size, weight, etc. * Note: The value is initially null until we need the given base font. */ - private final HashMap availableFontsHash = new HashMap(); + private final Map availableFontsHash = new HashMap<>(); /** * Constructor @@ -85,7 +86,7 @@ public void flushCache() { * Resolves a list of font families. */ public FSFont resolveFont(SharedContext ctx, String[] families, float size, IdentValue weight, IdentValue style, IdentValue variant) { - List fonts = new ArrayList(3); + List fonts = new ArrayList<>(3); // for each font family if (families != null) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/DOMInspector.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/DOMInspector.java index 18d4b7d48..545721b51 100755 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/DOMInspector.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/DOMInspector.java @@ -297,7 +297,7 @@ private TableModel tableModel(Node node) { Toolkit.getDefaultToolkit().beep(); return _defaultTableModel; } - Map props = _sr.getCascadedPropertiesMap((Element) node); + Map props = _sr.getCascadedPropertiesMap((Element) node); return new PropertiesTableModel(props); } @@ -367,19 +367,19 @@ static class PropertiesTableModel extends AbstractTableModel { * Description of the Field */ //String _colNames[] = {"Property Name", "Text", "Value", "Important-Inherit"}; - String _colNames[] = {"Property Name", "Text", "Value"}; + String[] _colNames = {"Property Name", "Text", "Value"}; /** * Description of the Field */ - Map _properties; + Map _properties; /** * Constructor for the PropertiesTableModel object * * @param cssProperties PARAM */ - PropertiesTableModel(Map cssProperties) { + PropertiesTableModel(Map cssProperties) { _properties = cssProperties; } @@ -433,7 +433,7 @@ public Object getValueAt(int row, int col) { break; case 2: if (ValueConstants.isNumber(cpv.getPrimitiveType())) { - val = new Float(cpv.getFloatValue(cpv.getPrimitiveType())); + val = Float.valueOf(cpv.getFloatValue(cpv.getPrimitiveType())); } else { val = "";//actual.cssValue().getCssText(); } @@ -537,7 +537,7 @@ class DOMTreeModel implements TreeModel { /** * Description of the Field */ - List listeners = new ArrayList(); + List listeners = new ArrayList<>(); /** * Constructor for the DOMTreeModel object diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/ImageLoadQueue.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/ImageLoadQueue.java index e8475b5e0..defc25018 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/ImageLoadQueue.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/swing/ImageLoadQueue.java @@ -37,13 +37,13 @@ class ImageLoadQueue { private static final ImageLoadItem KILL_SWITCH = new ImageLoadItem(null, null, null, -1, -1); // list of items to be loaded - private final java.util.LinkedList _loadQueue; + private final java.util.LinkedList _loadQueue; /** * Intantiates a new queue. */ public ImageLoadQueue() { - this._loadQueue = new LinkedList(); + this._loadQueue = new LinkedList<>(); } /** @@ -87,7 +87,7 @@ public synchronized ImageLoadItem getTask() throws InterruptedException { XRLog.log(Level.FINE, LogMessageId.LogMessageId1Param.GENERAL_THREAD_REQUESTED_ITEM_BUT_QUEUE_IS_SHUTTING_DOWN, Thread.currentThread().getName()); return KILL_SWITCH; } else { - ImageLoadItem item = (ImageLoadItem) _loadQueue.removeLast(); + ImageLoadItem item = _loadQueue.removeLast(); XRLog.log(Level.FINE, LogMessageId.LogMessageId3Param.GENERAL_THREAD_PULLED_ITEM_FROM_QUEUE, Thread.currentThread().getName(), item._uri, _loadQueue.size() - 1); return item; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ArrayUtil.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ArrayUtil.java index 4a6598399..5bd856ed2 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ArrayUtil.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ArrayUtil.java @@ -24,11 +24,11 @@ public class ArrayUtil { public static String[] cloneOrEmpty(String[] source){ - return source == null ? Constants.EMPTY_STR_ARR : (String[]) source.clone(); + return source == null ? Constants.EMPTY_STR_ARR : source.clone(); } public static int[] cloneOrEmpty(int[] source) { - return source == null ? Constants.EMPTY_INT_ARR : (int[]) source.clone(); + return source == null ? Constants.EMPTY_INT_ARR : source.clone(); } /** diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/Configuration.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/Configuration.java index 26f5745b9..fd9273fab 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/Configuration.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/Configuration.java @@ -88,7 +88,7 @@ public class Configuration { * List of LogRecords for messages from Configuration startup; used to hold these * temporarily as we can't use XRLog while starting up, as it depends on Configuration. */ - private List startupLogRecords; + private List startupLogRecords; /** * Logger we use internally related to configuration. @@ -108,7 +108,7 @@ public class Configuration { * for example, if the default configuration file was not readable. */ private Configuration() { - startupLogRecords = new ArrayList(); + startupLogRecords = new ArrayList<>(); try { try { @@ -170,9 +170,9 @@ public static void setConfigLogger(Logger logger) { Configuration config = instance(); config.configLogger = logger; if (config.startupLogRecords != null) { - Iterator iter = config.startupLogRecords.iterator(); + Iterator iter = config.startupLogRecords.iterator(); while (iter.hasNext()) { - LogRecord lr = (LogRecord) iter.next(); + LogRecord lr = iter.next(); logger.log(lr.getLevel(), lr.getMessage()); } config.startupLogRecords = null; @@ -281,13 +281,8 @@ private void loadOverrideProperties(String uri) { Properties temp = new Properties(); if (f.exists()) { info("Found config override file " + f.getAbsolutePath()); - try { - InputStream readStream = new BufferedInputStream(new FileInputStream(f)); - try { - temp.load(readStream); - } finally { - readStream.close(); - } + try (InputStream readStream = new BufferedInputStream(new FileInputStream(f))) { + temp.load(readStream); } catch (IOException iex) { warning("Error while loading override properties file; skipping.", iex); return; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/DownscaleQuality.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/DownscaleQuality.java index 144322c63..8b87d0c25 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/DownscaleQuality.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/DownscaleQuality.java @@ -32,7 +32,7 @@ // made a separate class only to reduce size of ImageUtil public class DownscaleQuality { /** Internal map string type to DQ instance */ - private static Map constList; + private static Map constList; /** * Highest-quality downscaling; probably slowest as well. @@ -67,7 +67,7 @@ private static DownscaleQuality addConstant(String type) { } private static void init() { - if ( constList == null ) constList = new HashMap(); + if ( constList == null ) constList = new HashMap<>(); } private DownscaleQuality(String type) { @@ -86,7 +86,7 @@ public String asString() { * @return The constant quality instance for the type, or the default if not found. */ public static DownscaleQuality forString(String type, DownscaleQuality dflt) { - DownscaleQuality q = (DownscaleQuality) constList.get(type); + DownscaleQuality q = constList.get(type); return q == null ? dflt : q; } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/GeneralUtil.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/GeneralUtil.java index ed085e5dc..b714734ec 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/GeneralUtil.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/GeneralUtil.java @@ -20,11 +20,6 @@ */ package com.openhtmltopdf.util; -import java.io.*; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - /** * Description of the Class * diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ImageUtil.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ImageUtil.java index 0cad3a32b..99ebb7bb9 100755 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ImageUtil.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ImageUtil.java @@ -23,10 +23,8 @@ import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; -import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import javax.imageio.ImageIO; @@ -39,38 +37,16 @@ */ public class ImageUtil { - private static final Map qual; + private static final Map qual; static { - qual = new HashMap(); + qual = new HashMap<>(); qual.put(DownscaleQuality.FAST, new OldScaler()); qual.put(DownscaleQuality.HIGH_QUALITY, new HighQualityScaler()); qual.put(DownscaleQuality.LOW_QUALITY, new FastScaler()); qual.put(DownscaleQuality.AREA, new AreaAverageScaler()); } - /** - * Sets the background of the image to the specified color - * - * @param image the image - * @param bgColor the color - */ - public static void clearImage(BufferedImage image, Color bgColor) { - Graphics2D g2d = (Graphics2D) image.getGraphics(); - g2d.setColor(bgColor); - g2d.fillRect(0, 0, image.getWidth(), image.getHeight()); - g2d.dispose(); - } - - /** - * Sets the background of the image to white. - * - * @param image the image - */ - public static void clearImage(BufferedImage image) { - clearImage(image, Color.WHITE); - } - public static BufferedImage makeCompatible(BufferedImage bimg) { BufferedImage cimg = null; if (GraphicsEnvironment.isHeadless()) { @@ -95,8 +71,7 @@ public static BufferedImage makeCompatible(BufferedImage bimg) { * for best performance. In a headless environment, simply creates a new BufferedImage. For non-headless * environments, this just sets up and calls * {@link java.awt.GraphicsConfiguration#createCompatibleImage(int,int,int)}. The image will not have anything - * drawn to it, not even a white background; you must do this yourself. The {@link #clearImage(BufferedImage)} - * method will do this for you if you like. + * drawn to it, not even a white background; you must do this yourself. * * @param width Target width for the image * @param height Target height for the image @@ -210,31 +185,6 @@ public static BufferedImage getScaledInstance(BufferedImage orgImage, int target return getScaledInstance(opt, orgImage); } - /** - * Scales one image to multiple dimensions, using the same ScalingOptions for each. The method follows the same - * process for scaling as {@link #getScaledInstance(ScalingOptions,java.awt.image.BufferedImage)}. - * - * @param opt Options to apply to control scaling process. - * @param img The original image to scale - * @param dimensions List of dimensions to scale to; one output image will be produced for each dimension. Will - * not check for duplicate dimensions. - * @return List of buffered images in the given dimensions. - */ - public static java.util.List scaleMultiple(ScalingOptions opt, BufferedImage img, java.util.List dimensions) { - java.util.List scaledImages = new ArrayList(dimensions.size()); - - Iterator iter = dimensions.iterator(); - while (iter.hasNext()) { - Dimension dim = (Dimension) iter.next(); - opt.setTargetDimensions(dim); - - BufferedImage scaled = getScaledInstance(opt, img); - - scaledImages.add(scaled); - } - return scaledImages; - } - /** * Utility method to convert an AWT Image to a BufferedImage. Size is preserved, BufferedImage is compatible * with current display device. @@ -331,22 +281,8 @@ interface Scaler { * to be fully loaded (e.g. no need to wait for loading on requesting height or width. * * @param img the original image to be scaled - * @param imageType type of image from {@link java.awt.image.BufferedImage} (values starting with TYPE) - * @param hint one of the rendering hints that corresponds to - * {@code RenderingHints.KEY_INTERPOLATION} (e.g. - * {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR}, - * {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR}, - * {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC}) - * @param higherQuality if true, this method will use a multi-step - * scaling technique that provides higher quality than the usual - * one-step technique (only useful in downscaling cases, where - * {@code targetWidth} or {@code targetHeight} is - * smaller than the original dimensions, and generally only when - * the {@code BILINEAR} hint is specified) - * @param targetWidth the desired width of the scaled instance, - * in pixels - * @param targetHeight the desired height of the scaled instance, - * in pixels + * @param opt options + * * @return a scaled version of the original {@code BufferedImage} */ BufferedImage getScaledInstance(BufferedImage img, ScalingOptions opt); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/JDKXRLogger.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/JDKXRLogger.java index 93b46bc25..6a5d47bc7 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/JDKXRLogger.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/JDKXRLogger.java @@ -21,7 +21,6 @@ */ package com.openhtmltopdf.util; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -100,8 +99,6 @@ private static void init() { Configuration.setConfigLogger(Logger.getLogger(XRLog.CONFIG)); } catch (SecurityException e) { // may happen in a sandbox environment - } catch (FileNotFoundException e) { - throw new XRRuntimeException("Could not initialize logs. " + e.getLocalizedMessage(), e); } catch (IOException e) { throw new XRRuntimeException("Could not initialize logs. " + e.getLocalizedMessage(), e); } @@ -130,7 +127,7 @@ private static void initializeJDKLogManager(final Properties fsLoggingProperties // load our properties into our log manager Enumeration keys = fsLoggingProperties.keys(); - Map handlers = new HashMap<>(); + Map handlers = new HashMap<>(); Map handlerFormatterMap = new HashMap<>(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); @@ -160,8 +157,8 @@ private static void configureLoggerHandlerForwarding(Properties fsLoggingPropert loggers.forEach(l -> l.setUseParentHandlers(flag)); } - private static void assignFormatter(Map handlers, String handlerClassName, String formatterClassName) { - Handler handler = (Handler) handlers.get(handlerClassName); + private static void assignFormatter(Map handlers, String handlerClassName, String formatterClassName) { + Handler handler = handlers.get(handlerClassName); if (handler != null) { try { Class fclass = Class.forName(formatterClassName); @@ -205,13 +202,12 @@ private static List retrieveLoggers() { * * @return Map of handler class names to handler instances. */ - private static Map configureLogHandlers(List loggers, final String handlerClassList) { + private static Map configureLogHandlers(List loggers, final String handlerClassList) { final String[] names = handlerClassList.split(" "); - final Map handlers = new HashMap(names.length); - for (int i = 0; i < names.length; i++) { - final String name = names[i]; + final Map handlers = new HashMap(names.length); + for (String name : names) { try { - Class handlerClass = Class.forName(name); + Class handlerClass = Class.forName(name); Handler handler = (Handler) handlerClass.newInstance(); handlers.put(name, handler); String hl = Configuration.valueFor("xr.util-logging." + name + ".level", "INFO"); @@ -229,8 +225,8 @@ private static Map configureLogHandlers(List loggers, final String handlerClassL } // now assign each handler to each FS logger - for (Iterator iterator = loggers.iterator(); iterator.hasNext();) { - Logger logger = (Logger) iterator.next(); + for (Iterator iterator = loggers.iterator(); iterator.hasNext();) { + Logger logger = iterator.next(); for (Iterator ith = handlers.values().iterator(); ith.hasNext();) { Handler handler = (Handler) ith.next(); logger.addHandler(handler); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/LoggerUtil.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/LoggerUtil.java index 1fa5db6ef..5848ec41f 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/LoggerUtil.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/LoggerUtil.java @@ -35,41 +35,25 @@ public class LoggerUtil { * @param cls PARAM * @return The debugLogger value */ - public static Logger getDebugLogger( Class cls ) { + public static Logger getDebugLogger( Class cls ) { Logger l = Logger.getLogger( cls.getName() ); l.setLevel( Level.ALL ); return l; } public static Level parseLogLevel(String val, Level defaultLogLevel) { - if ("ALL".equals(val)) { - return Level.ALL; + switch (val) { + case "ALL": return Level.ALL; + case "CONFIG": return Level.CONFIG; + case "FINE": return Level.FINE; + case "FINER": return Level.FINER; + case "FINEST": return Level.FINEST; + case "INFO": return Level.INFO; + case "OFF": return Level.OFF; + case "SEVERE": return Level.SEVERE; + case "WARNING": return Level.WARNING; + default: return defaultLogLevel; } - if ("CONFIG".equals(val)) { - return Level.CONFIG; - } - if ("FINE".equals(val)) { - return Level.FINE; - } - if ("FINER".equals(val)) { - return Level.FINER; - } - if ("FINEST".equals(val)) { - return Level.FINEST; - } - if ("INFO".equals(val)) { - return Level.INFO; - } - if ("OFF".equals(val)) { - return Level.OFF; - } - if ("SEVERE".equals(val)) { - return Level.SEVERE; - } - if ("WARNING".equals(val)) { - return Level.WARNING; - } - return defaultLogLevel; } } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ScalingOptions.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ScalingOptions.java index 61e771171..5a30a446a 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ScalingOptions.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ScalingOptions.java @@ -109,8 +109,8 @@ public void applyRenderingHints(Graphics2D g2) { * * @return Map of rendering hints. */ - protected Map getRenderingHints() { - HashMap map = new HashMap(); + protected Map getRenderingHints() { + HashMap map = new HashMap<>(); map.put(RenderingHints.KEY_INTERPOLATION, getRenderingHint()); return map; } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ThreadCtx.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ThreadCtx.java index 053458a7f..934eed588 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ThreadCtx.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/ThreadCtx.java @@ -4,7 +4,6 @@ import java.io.Closeable; import java.util.function.Consumer; -import java.util.logging.Level; /** * Because OpenHTMLtoPDF is designed to run in a single thread at all times for one invocation, @@ -13,8 +12,8 @@ */ public class ThreadCtx { - private static final ThreadLocal data = ThreadLocal.withInitial(() -> new ThreadData()); - private static final ThreadLocal> diagnosticConsumer = new ThreadLocal(); + private static final ThreadLocal data = ThreadLocal.withInitial(ThreadData::new); + private static final ThreadLocal> diagnosticConsumer = new ThreadLocal<>(); @@ -35,7 +34,7 @@ public static void cleanup() { public static Closeable applyDiagnosticConsumer(Consumer consumer) { diagnosticConsumer.set(consumer); - return () -> diagnosticConsumer.remove(); + return diagnosticConsumer::remove; } public static class ThreadData { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRSimpleLogFormatter.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRSimpleLogFormatter.java index fb1cb849b..6712aa7c0 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRSimpleLogFormatter.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRSimpleLogFormatter.java @@ -68,7 +68,7 @@ public String format( LogRecord record ) { thName = th.getClass().getName(); thMessage = th.getMessage(); } - String args[] = { + String[] args = { String.valueOf( record.getMillis() ), record.getLoggerName(), record.getLevel().toString(), diff --git a/openhtmltopdf-core/src/test/java/com/openhtmltopdf/layout/BreakerTestSupport.java b/openhtmltopdf-core/src/test/java/com/openhtmltopdf/layout/BreakerTestSupport.java index cfe3222d0..01c2a4d19 100644 --- a/openhtmltopdf-core/src/test/java/com/openhtmltopdf/layout/BreakerTestSupport.java +++ b/openhtmltopdf-core/src/test/java/com/openhtmltopdf/layout/BreakerTestSupport.java @@ -113,7 +113,7 @@ static LineBreakContext createContext(String str) { return ctx; } - static final ToIntFunction MEASURER = (str) -> str.length(); + static final ToIntFunction MEASURER = String::length; static final ToIntFunction MEASURER3 = (str) -> str.length() * 3; static final ToIntFunction MEASURER_WITH_ZERO_WIDTH_SOFT_HYPHEN = (str) -> { long softHyphenCount = str.chars().filter(ch -> ch == Breaker.SOFT_HYPHEN).count(); diff --git a/openhtmltopdf-examples/src/main/java/ListFontFamilyNames.java b/openhtmltopdf-examples/src/main/java/ListFontFamilyNames.java index 884b84a47..8efa0d230 100644 --- a/openhtmltopdf-examples/src/main/java/ListFontFamilyNames.java +++ b/openhtmltopdf-examples/src/main/java/ListFontFamilyNames.java @@ -31,10 +31,7 @@ public boolean accept(File file, String s) { Font awtf = null; try { awtf = Font.createFont(Font.TRUETYPE_FONT, f); - } catch (FontFormatException e) { - System.err.println("Trying to load font via AWT: " + e.getMessage()); - System.exit(1); - } catch (IOException e) { + } catch (FontFormatException | IOException e) { System.err.println("Trying to load font via AWT: " + e.getMessage()); System.exit(1); } diff --git a/openhtmltopdf-examples/src/main/java/VerifyGlyphExists.java b/openhtmltopdf-examples/src/main/java/VerifyGlyphExists.java index f6aeedf2b..c2819cbff 100644 --- a/openhtmltopdf-examples/src/main/java/VerifyGlyphExists.java +++ b/openhtmltopdf-examples/src/main/java/VerifyGlyphExists.java @@ -70,22 +70,14 @@ public static void main(String[] args) { } private static List readLines(File file) { - List l = new ArrayList(); - LineNumberReader r = null; - try { - r = new LineNumberReader(new BufferedReader(new FileReader(file))); + List l = new ArrayList<>(); + try (LineNumberReader r = new LineNumberReader(new BufferedReader(new FileReader(file)))){ String path; while ((path = r.readLine()) != null) { l.add(path); } } catch (IOException e) { error("Can't read list of font paths from " + file.getPath()); - } finally { - try { - if (r != null) r.close(); - } catch (IOException e) { - // swallow - } } return l; } diff --git a/openhtmltopdf-examples/src/main/java/com/openhtmltopdf/documentation/generator/TemplateAuthorGuideGenerator.java b/openhtmltopdf-examples/src/main/java/com/openhtmltopdf/documentation/generator/TemplateAuthorGuideGenerator.java index 2158ec016..4b26d2f74 100644 --- a/openhtmltopdf-examples/src/main/java/com/openhtmltopdf/documentation/generator/TemplateAuthorGuideGenerator.java +++ b/openhtmltopdf-examples/src/main/java/com/openhtmltopdf/documentation/generator/TemplateAuthorGuideGenerator.java @@ -1,11 +1,9 @@ package com.openhtmltopdf.documentation.generator; -import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Arrays; -import org.apache.commons.io.FileUtils; import org.apache.pdfbox.io.IOUtils; import org.apache.pdfbox.util.Charsets; diff --git a/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/nonvisualregressiontests/JsoupNonVisualRegressionTest.java b/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/nonvisualregressiontests/JsoupNonVisualRegressionTest.java index 2e66755c6..9da4e5765 100644 --- a/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/nonvisualregressiontests/JsoupNonVisualRegressionTest.java +++ b/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/nonvisualregressiontests/JsoupNonVisualRegressionTest.java @@ -7,7 +7,6 @@ import org.apache.commons.io.FileUtils; import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.jsoup.Jsoup; import org.jsoup.helper.W3CDom; import org.junit.Ignore; @@ -49,7 +48,7 @@ private static void render(String fileName, BuilderConfig config) throws IOExcep } } - private static PDDocument load(String filename) throws InvalidPasswordException, IOException { + private static PDDocument load(String filename) throws IOException { return PDDocument.load(new File(OUT_PATH, filename + ".pdf")); } diff --git a/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/nonvisualregressiontests/NonVisualRegressionTest.java b/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/nonvisualregressiontests/NonVisualRegressionTest.java index 1aa96e2f6..3727b1964 100644 --- a/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/nonvisualregressiontests/NonVisualRegressionTest.java +++ b/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/nonvisualregressiontests/NonVisualRegressionTest.java @@ -19,7 +19,6 @@ import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.common.PDRectangle; -import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo; import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink; @@ -87,7 +86,7 @@ public void configure(PdfRendererBuilder builder) { }); } - private static PDDocument load(String filename) throws InvalidPasswordException, IOException { + private static PDDocument load(String filename) throws IOException { return PDDocument.load(new File(OUT_PATH, filename + ".pdf")); } diff --git a/openhtmltopdf-java2d/src/main/java/com/openhtmltopdf/java2d/api/BufferedImagePageProcessor.java b/openhtmltopdf-java2d/src/main/java/com/openhtmltopdf/java2d/api/BufferedImagePageProcessor.java index 13a2efcb2..9bbdc5f44 100644 --- a/openhtmltopdf-java2d/src/main/java/com/openhtmltopdf/java2d/api/BufferedImagePageProcessor.java +++ b/openhtmltopdf-java2d/src/main/java/com/openhtmltopdf/java2d/api/BufferedImagePageProcessor.java @@ -12,7 +12,7 @@ public class BufferedImagePageProcessor implements FSPageProcessor { private final double _scale; private final int _imageType; - private List _pages = new ArrayList(); + private List _pages = new ArrayList<>(); private class BufferedImagePage implements FSPage { BufferedImage _image; @@ -68,7 +68,7 @@ public void finishPage(FSPage pg) { } public List getPageImages() { - List images = new ArrayList(); + List images = new ArrayList<>(); for (BufferedImagePage page : _pages) { images.add(page._image); } diff --git a/openhtmltopdf-objects/src/main/java/com/openhtmltopdf/objects/pdf/MergeBackgroundPdfDrawer.java b/openhtmltopdf-objects/src/main/java/com/openhtmltopdf/objects/pdf/MergeBackgroundPdfDrawer.java index 024bb995f..9cd126956 100644 --- a/openhtmltopdf-objects/src/main/java/com/openhtmltopdf/objects/pdf/MergeBackgroundPdfDrawer.java +++ b/openhtmltopdf-objects/src/main/java/com/openhtmltopdf/objects/pdf/MergeBackgroundPdfDrawer.java @@ -6,7 +6,6 @@ import java.io.OutputStream; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; -import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; @@ -55,22 +54,18 @@ public Map drawObject(Element e, double x, double y, double width if (mapWeakReference != null) map = mapWeakReference.get(); if (map == null) { - map = new HashMap(); - formMap.put(new PDFBoxDeviceReference(pdfBoxOutputDevice), - new SoftReference>(map)); + map = new HashMap<>(); + formMap.put(new PDFBoxDeviceReference(pdfBoxOutputDevice), new SoftReference<>(map)); } try { PDFormXObject pdFormXObject = map.get(url); LayerUtility layerUtility = new LayerUtility(pdfBoxOutputDevice.getWriter()); if (pdFormXObject == null) { - InputStream inputStream = new URL(url).openStream(); - try { + try (InputStream inputStream = new URL(url).openStream()){ PDFParser pdfParser = new PDFParser(new RandomAccessBuffer(inputStream)); pdfParser.parse(); pdFormXObject = layerUtility.importPageAsForm(pdfParser.getPDDocument(), pdfpage - 1); pdfParser.getPDDocument().close(); - } finally { - inputStream.close(); } map.put(url, pdFormXObject); } @@ -94,8 +89,6 @@ public Map drawObject(Element e, double x, double y, double width saveAndPlaceStream.write("q\n".getBytes(Charsets.US_ASCII)); saveAndPlaceStream.close(); - } catch (MalformedURLException e1) { - e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } diff --git a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxFontResolver.java b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxFontResolver.java index 8e131c5ca..01870939a 100644 --- a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxFontResolver.java +++ b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxFontResolver.java @@ -242,12 +242,9 @@ public void process(TrueTypeFont ttf) throws IOException { public void addFontCollection(FSSupplier supplier, final String fontFamilyNameOverride, final Integer fontWeightOverride, final IdentValue fontStyleOverride, final boolean subset) throws IOException { - InputStream inputStream = supplier.supply(); - try { + try (InputStream inputStream = supplier.supply()){ TrueTypeCollection collection = new TrueTypeCollection(inputStream); addFontCollection(collection, fontFamilyNameOverride, fontWeightOverride, fontStyleOverride, subset); - } finally { - inputStream.close(); } } diff --git a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxForm.java b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxForm.java index 2de3ee8e6..f3b49f52e 100644 --- a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxForm.java +++ b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxForm.java @@ -531,20 +531,11 @@ public static PDAppearanceStream createCheckboxAppearance(CheckboxStyle style, P public static PDAppearanceStream createCheckboxAppearance(String appear, PDDocument doc, PDResources resources) { PDAppearanceStream s = new PDAppearanceStream(doc); s.setBBox(new PDRectangle(100f, 100f)); - OutputStream os = null; - try { - os = s.getContentStream().createOutputStream(); + try (OutputStream os = s.getContentStream().createOutputStream()){ os.write(appear.getBytes(StandardCharsets.US_ASCII)); } catch (IOException e) { throw new PdfContentStreamAdapter.PdfException("createCheckboxAppearance", e); - } finally { - try { - if (os != null) - os.close(); - } catch (IOException e) { - } } - s.setResources(resources); return s; } diff --git a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxImage.java b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxImage.java index 91f09b805..88f0c41ad 100644 --- a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxImage.java +++ b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxImage.java @@ -30,12 +30,9 @@ public PdfBoxImage(byte[] image, String uri) throws IOException { _bytes = image; _uri = uri; - ImageInputStream in = null; ImageReader reader = null; - try { - in = ImageIO - .createImageInputStream(new ByteArrayInputStream(_bytes)); + try (ImageInputStream in = ImageIO.createImageInputStream(new ByteArrayInputStream(_bytes))){ Iterator readers = ImageIO.getImageReaders(in); if (readers.hasNext()) { @@ -55,8 +52,6 @@ public PdfBoxImage(byte[] image, String uri) throws IOException { throw new IOException("Unrecognized Image format"); } } finally { - if (in != null) - in.close(); if (reader != null) reader.dispose(); } diff --git a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxRenderer.java b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxRenderer.java index fb5cfa983..6813030ab 100644 --- a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxRenderer.java +++ b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxRenderer.java @@ -841,11 +841,7 @@ private void addPdfASchema(PDDocument document, int part, String conformance) { oi.setRegistryName("http://www.color.org"); catalog.addOutputIntent(oi); } - } catch (BadFieldValueException e) { - throw new RuntimeException(e); - } catch (IOException e) { - throw new RuntimeException(e); - } catch (TransformerException e) { + } catch (BadFieldValueException | IOException | TransformerException e) { throw new RuntimeException(e); } } @@ -966,12 +962,10 @@ private String stringfyMetadata(Element element) { transformer.transform(new DOMSource(target), new StreamResult(output)); return output.toString(); - } catch (TransformerConfigurationException e) { + } catch (TransformerException e) { // Things must be in pretty bad shape to get here so // rethrow as runtime exception throw new RuntimeException(e); - } catch (TransformerException e) { - throw new RuntimeException(e); } } diff --git a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxReplacedElementFactory.java b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxReplacedElementFactory.java index 344eb1246..3083c66da 100644 --- a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxReplacedElementFactory.java +++ b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxReplacedElementFactory.java @@ -22,15 +22,12 @@ import com.openhtmltopdf.extend.*; import com.openhtmltopdf.layout.LayoutContext; import com.openhtmltopdf.render.BlockBox; -import com.openhtmltopdf.resource.ImageResource; import com.openhtmltopdf.resource.XMLResource; import com.openhtmltopdf.util.ImageUtil; import org.w3c.dom.Element; import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.StringReader; public class PdfBoxReplacedElementFactory implements ReplacedElementFactory { private final SVGDrawer _svgImpl; diff --git a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxUserAgent.java b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxUserAgent.java index d20f31afe..45ae822b3 100644 --- a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxUserAgent.java +++ b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxUserAgent.java @@ -29,7 +29,6 @@ import com.openhtmltopdf.layout.SharedContext; import com.openhtmltopdf.resource.ImageResource; -import com.openhtmltopdf.swing.FSCacheKey; import com.openhtmltopdf.swing.NaiveUserAgent; import com.openhtmltopdf.util.ImageUtil; import com.openhtmltopdf.util.LogMessageId; diff --git a/openhtmltopdf-svg-support/src/main/java/com/openhtmltopdf/svgsupport/OpenHtmlGvtFont.java b/openhtmltopdf-svg-support/src/main/java/com/openhtmltopdf/svgsupport/OpenHtmlGvtFont.java index f7b205b11..ea2c1158e 100644 --- a/openhtmltopdf-svg-support/src/main/java/com/openhtmltopdf/svgsupport/OpenHtmlGvtFont.java +++ b/openhtmltopdf-svg-support/src/main/java/com/openhtmltopdf/svgsupport/OpenHtmlGvtFont.java @@ -22,7 +22,6 @@ public class OpenHtmlGvtFont implements GVTFont { private final Font baseFont; private final GVTFontFamily fontFamily; - private final float size; private static int toFontWeight(Float weight) { if (weight == null) { @@ -56,13 +55,11 @@ public OpenHtmlGvtFont(byte[] fontBytes, GVTFontFamily family, float size, Float this.baseFont = font; this.fontFamily = family; - this.size = size; } private OpenHtmlGvtFont(Font font, GVTFontFamily family, float size) { this.baseFont = font; this.fontFamily = family; - this.size = size; } @Override diff --git a/openhtmltopdf-svg-support/src/main/java/com/openhtmltopdf/svgsupport/OpenHtmlGvtFontFamily.java b/openhtmltopdf-svg-support/src/main/java/com/openhtmltopdf/svgsupport/OpenHtmlGvtFontFamily.java index e101c7ecb..018a8e009 100644 --- a/openhtmltopdf-svg-support/src/main/java/com/openhtmltopdf/svgsupport/OpenHtmlGvtFontFamily.java +++ b/openhtmltopdf-svg-support/src/main/java/com/openhtmltopdf/svgsupport/OpenHtmlGvtFontFamily.java @@ -2,10 +2,6 @@ import java.awt.FontFormatException; import java.awt.font.TextAttribute; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; import java.text.AttributedCharacterIterator; import java.util.HashMap; import java.util.Map; @@ -14,8 +10,6 @@ import org.apache.batik.gvt.font.GVTFontFace; import org.apache.batik.gvt.font.GVTFontFamily; -import com.openhtmltopdf.util.XRLog; - public class OpenHtmlGvtFontFamily implements GVTFontFamily { private static class FontDescriptor {