Убрать все @SuppressWarnings (PMD проходит поправленным кодом) #84
@@ -114,11 +114,6 @@ public final class WordPdfConverter {
|
|||||||
* документ длиннее {@code options.maxPages()} страниц
|
* документ длиннее {@code options.maxPages()} страниц
|
||||||
* @throws ConversionException прочие ошибки (битый .docx, ошибка рендера)
|
* @throws ConversionException прочие ошибки (битый .docx, ошибка рендера)
|
||||||
*/
|
*/
|
||||||
// PMD.UnusedAssignment глушится намеренно: зануление docxBytes ниже —
|
|
||||||
// не «мёртвое присваивание», а детерминированное освобождение массива до
|
|
||||||
// моста/рендера (точные liveness-карты HotSpot строит только для
|
|
||||||
// скомпилированных кадров).
|
|
||||||
@SuppressWarnings("PMD.UnusedAssignment")
|
|
||||||
public static byte[] convert(byte[] docxBytes, String title, ConvertOptions options) throws ConversionException {
|
public static byte[] convert(byte[] docxBytes, String title, ConvertOptions options) throws ConversionException {
|
||||||
ConvertOptions opts = options == null ? ConvertOptions.defaults() : options;
|
ConvertOptions opts = options == null ? ConvertOptions.defaults() : options;
|
||||||
// Полная проверка входа — одна на оба формата: размер до
|
// Полная проверка входа — одна на оба формата: размер до
|
||||||
@@ -126,19 +121,17 @@ public final class WordPdfConverter {
|
|||||||
// лимита), затем для .docx — zip/контейнер/страницы, для .doc —
|
// лимита), затем для .docx — zip/контейнер/страницы, для .doc —
|
||||||
// страницы по чистому бинарному документу (до конвертации).
|
// страницы по чистому бинарному документу (до конвертации).
|
||||||
WordPdfValidator.validate(docxBytes, opts);
|
WordPdfValidator.validate(docxBytes, opts);
|
||||||
boolean fromDoc = WordPdfValidator.isBinaryDoc(docxBytes);
|
|
||||||
// Бинарный .doc (Word 97–2003): мост internal.doc. Сгенерированный
|
// Бинарный .doc (Word 97–2003): мост internal.doc. Сгенерированный
|
||||||
// .docx — собственный артефакт, его штатной валидацией входа не
|
// .docx — собственный артефакт, его штатной валидацией входа не
|
||||||
// проверяем (вход уже проверен по байтам .doc).
|
// проверяем (вход уже проверен по байтам .doc). Переиспользование слота
|
||||||
byte[] docx = fromDoc ? DocToDocx.convert(docxBytes) : docxBytes;
|
// docxBytes: результат моста становится в тот же слот, и сырые байты
|
||||||
// Сырой вход (.doc до конвертации в docx тоже был в куче) больше не
|
// .doc сбрасываются в кадре на этом же месте — детерминированно, до
|
||||||
// читается — обнуляем явно: точные liveness-карты HotSpot строит
|
// рендера (точные liveness-карты HotSpot строит только для
|
||||||
// только для скомпилированных кадров, без этого ссылка доживала бы до
|
// скомпилированных кадров; отдельное присваивание null не нужно).
|
||||||
// конца метода, пережив и мост, и FOP-рендер.
|
docxBytes = WordPdfValidator.isBinaryDoc(docxBytes) ? DocToDocx.convert(docxBytes) : docxBytes;
|
||||||
docxBytes = null;
|
ByteArrayOutputStream bos = new ByteArrayOutputStream(Math.max(1 << 16, docxBytes.length));
|
||||||
ByteArrayOutputStream bos = new ByteArrayOutputStream(Math.max(1 << 16, docx.length));
|
|
||||||
try {
|
try {
|
||||||
convertToStream(docx, title, opts, bos);
|
convertToStream(docxBytes, title, opts, bos);
|
||||||
} catch (ConversionException e) {
|
} catch (ConversionException e) {
|
||||||
// ValidationException (отказ валидации входа) — подтип, уходит
|
// ValidationException (отказ валидации входа) — подтип, уходит
|
||||||
// вызывающему без обёртки
|
// вызывающему без обёртки
|
||||||
@@ -154,10 +147,6 @@ public final class WordPdfConverter {
|
|||||||
* совместимости commons-compress в classpath потребителя (DependencyGuard):
|
* совместимости commons-compress в classpath потребителя (DependencyGuard):
|
||||||
* без неё старая версия библиотеки дала бы мутный NoSuchMethodError внутри docx4j.
|
* без неё старая версия библиотеки дала бы мутный NoSuchMethodError внутри docx4j.
|
||||||
*/
|
*/
|
||||||
// PMD.UnusedAssignment глушится намеренно: зануление rawDocxBytes/docxBytes
|
|
||||||
// — детерминированное освобождение байтов входа до load()/рендера, а не
|
|
||||||
// «мёртвое присваивание» (см. javadoc convert).
|
|
||||||
@SuppressWarnings("PMD.UnusedAssignment")
|
|
||||||
private static void convertToStream(byte[] rawDocxBytes, String title, ConvertOptions options,
|
private static void convertToStream(byte[] rawDocxBytes, String title, ConvertOptions options,
|
||||||
OutputStream os) throws Exception {
|
OutputStream os) throws Exception {
|
||||||
// 0. Совместимость commons-compress: docx4j требует ковариантный
|
// 0. Совместимость commons-compress: docx4j требует ковариантный
|
||||||
@@ -176,20 +165,12 @@ public final class WordPdfConverter {
|
|||||||
|
|
||||||
// 2. Загрузка документа: один zip-проход переписывания XML-частей
|
// 2. Загрузка документа: один zip-проход переписывания XML-частей
|
||||||
// (DocxRewritePipeline) + условная OLE-вычистка (OleObjectNormalizer)
|
// (DocxRewritePipeline) + условная OLE-вычистка (OleObjectNormalizer)
|
||||||
// — дальше лежит transitional-байт, готовый для JAXB/docx4j.
|
// и load transitional-байтов в пакет — внутри loadPackage(). Её кадр
|
||||||
byte[] docxBytes = rawDocxBytes;
|
// умирает сразу после load(), ZipPartStore держит распакованные
|
||||||
for (DocxNormalizer normalizer : normalizers(options)) {
|
// записи в своём реестре — поэтому ни промежуточные, ни финальный
|
||||||
docxBytes = normalizer.normalize(docxBytes);
|
// нормализованный zip-массивы не доживают до FOP-рендера (пик:
|
||||||
}
|
// JAXB-модель + FOP + PDF-буфер), притом без зануления ссылок.
|
||||||
// Исходные байты до нормализации больше не читаются — освобождаем явно
|
WordprocessingMLPackage pkg = loadPackage(rawDocxBytes, options);
|
||||||
// (без них при .doc-входе в куче жили бы и .doc, и нормализованный .docx).
|
|
||||||
rawDocxBytes = null;
|
|
||||||
WordprocessingMLPackage pkg = WordprocessingMLPackage.load(
|
|
||||||
new ByteArrayInputStream(docxBytes));
|
|
||||||
// ZipPartStore при load() копирует распакованные байты каждой записи в
|
|
||||||
// свой реестр, нормализованный zip дальше не читается — освобождаем до
|
|
||||||
// FOP-рендера (пик: JAXB-модель + FOP + PDF-буфер).
|
|
||||||
docxBytes = null;
|
|
||||||
try {
|
try {
|
||||||
// 3. Привязка маппера: docx4j сопоставляет шрифты документа
|
// 3. Привязка маппера: docx4j сопоставляет шрифты документа
|
||||||
// с физическими TTF (учитывая и шрифты, встроенные в docx)
|
// с физическими TTF (учитывая и шрифты, встроенные в docx)
|
||||||
@@ -239,6 +220,22 @@ public final class WordPdfConverter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Нормализация входных байтов (цепочка {@link #normalizers}: правила 1–8
|
||||||
|
* одним zip-проходом {@code DocxRewritePipeline} + условная OLE-вычистка)
|
||||||
|
* и {@code WordprocessingMLPackage.load} полученного transitional-байта.
|
||||||
|
* Нормализация переиспользует слот {@code bytes}: каждая замена массива
|
||||||
|
* сбрасывает предыдущий (без неё при .doc-входе в куче жили бы и .doc,
|
||||||
|
* и нормализованный .docx); кадр метода умирает сразу после load(),
|
||||||
|
* освобождая финальный массив.
|
||||||
|
*/
|
||||||
|
private static WordprocessingMLPackage loadPackage(byte[] bytes, ConvertOptions options) throws Exception {
|
||||||
|
for (DocxNormalizer normalizer : normalizers(options)) {
|
||||||
|
bytes = normalizer.normalize(bytes);
|
||||||
|
}
|
||||||
|
return WordprocessingMLPackage.load(new ByteArrayInputStream(bytes));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Конвейер байтовой нормализации docx. Порядок фиксирован: сначала один
|
* Конвейер байтовой нормализации docx. Порядок фиксирован: сначала один
|
||||||
* zip-проход переписывания XML-частей (внутри части порядок рерайтов
|
* zip-проход переписывания XML-частей (внутри части порядок рерайтов
|
||||||
|
|||||||
@@ -108,8 +108,11 @@ public final class BundledFonts {
|
|||||||
new Entry("NotoSansArmenian-Regular.ttf", "noto sans armenian", V_REGULAR)
|
new Entry("NotoSansArmenian-Regular.ttf", "noto sans armenian", V_REGULAR)
|
||||||
);
|
);
|
||||||
|
|
||||||
/** Ключ семейства (lowercase) -> начертание -> зарегистрированный PhysicalFont. */
|
/** Ключ семейства (lowercase) -> начертание -> зарегистрированный PhysicalFont.
|
||||||
private static final Map<String, Map<String, PhysicalFont>> VARIANTS = new HashMap<>();
|
* Package-private: тесты одного пакета забирают снимок и чистят карту
|
||||||
|
* напрямую ({@code BundledFontMapperTest}); тест чужого пакета лезет в неё
|
||||||
|
* через reflection ({@code FopFallbackFontsTest}). */
|
||||||
|
static final Map<String, Map<String, PhysicalFont>> VARIANTS = new HashMap<>();
|
||||||
|
|
||||||
/** Каталог, куда выгружены TTF (после init()). */
|
/** Каталог, куда выгружены TTF (после init()). */
|
||||||
private static Path extractDir;
|
private static Path extractDir;
|
||||||
|
|||||||
@@ -27,22 +27,19 @@ class BundledFontMapperTest {
|
|||||||
|
|
||||||
/** Выполнить body в состоянии «шрифты бандла не зарегистрированы», затем восстановить. */
|
/** Выполнить body в состоянии «шрифты бандла не зарегистрированы», затем восстановить. */
|
||||||
private static void withoutBundledInit(TestBody body) throws Exception {
|
private static void withoutBundledInit(TestBody body) throws Exception {
|
||||||
Field variantsField = BundledFonts.class.getDeclaredField("VARIANTS");
|
|
||||||
variantsField.setAccessible(true);
|
|
||||||
Field initedField = BundledFonts.class.getDeclaredField("inited");
|
Field initedField = BundledFonts.class.getDeclaredField("inited");
|
||||||
initedField.setAccessible(true);
|
initedField.setAccessible(true);
|
||||||
@SuppressWarnings("unchecked")
|
// VARIANTS package-private (тот же пакет) — снимок/очистка напрямую,
|
||||||
Map<String, Map<String, PhysicalFont>> variants =
|
// типизированно, без reflection-каста.
|
||||||
(Map<String, Map<String, PhysicalFont>>) variantsField.get(null);
|
Map<String, Map<String, PhysicalFont>> savedVariants = new HashMap<>(BundledFonts.VARIANTS);
|
||||||
Map<String, Map<String, PhysicalFont>> savedVariants = new HashMap<>(variants);
|
|
||||||
boolean savedInited = initedField.getBoolean(null);
|
boolean savedInited = initedField.getBoolean(null);
|
||||||
variants.clear();
|
BundledFonts.VARIANTS.clear();
|
||||||
initedField.setBoolean(null, false);
|
initedField.setBoolean(null, false);
|
||||||
try {
|
try {
|
||||||
body.run();
|
body.run();
|
||||||
} finally {
|
} finally {
|
||||||
variants.clear();
|
BundledFonts.VARIANTS.clear();
|
||||||
variants.putAll(savedVariants);
|
BundledFonts.VARIANTS.putAll(savedVariants);
|
||||||
initedField.setBoolean(null, savedInited);
|
initedField.setBoolean(null, savedInited);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import org.docx4j.convert.out.FOSettings;
|
|||||||
import org.docx4j.convert.out.fopconf.Fop;
|
import org.docx4j.convert.out.fopconf.Fop;
|
||||||
import org.docx4j.convert.out.fopconf.Fonts;
|
import org.docx4j.convert.out.fopconf.Fonts;
|
||||||
import org.docx4j.convert.out.fopconf.ObjectFactory;
|
import org.docx4j.convert.out.fopconf.ObjectFactory;
|
||||||
import org.docx4j.fonts.PhysicalFont;
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import ru.pjandro.wordpdf.fonts.BundledFonts;
|
import ru.pjandro.wordpdf.fonts.BundledFonts;
|
||||||
|
|
||||||
@@ -111,11 +110,11 @@ class FopFallbackFontsTest {
|
|||||||
void declareWithoutInitDeclaresNothing() throws Exception {
|
void declareWithoutInitDeclaresNothing() throws Exception {
|
||||||
Field variantsField = BundledFonts.class.getDeclaredField("VARIANTS");
|
Field variantsField = BundledFonts.class.getDeclaredField("VARIANTS");
|
||||||
variantsField.setAccessible(true);
|
variantsField.setAccessible(true);
|
||||||
@SuppressWarnings("unchecked")
|
// Поле final — ссылка не подменяется (Field.set на final запрещён с
|
||||||
Map<String, Map<String, PhysicalFont>> variants =
|
// JDK 15), карта чистится и наполняется обратно. Кастов нет: доступ
|
||||||
(Map<String, Map<String, PhysicalFont>>) variantsField.get(null);
|
// через reifiable Map<?,?>, обратный putAll — рефлектив вызовом Map.putAll.
|
||||||
Map<String, Map<String, PhysicalFont>> saved =
|
Map<?, ?> variants = (Map<?, ?>) variantsField.get(null);
|
||||||
new java.util.HashMap<>(variants);
|
Map<Object, Object> savedVariants = new java.util.HashMap<>(variants);
|
||||||
variants.clear();
|
variants.clear();
|
||||||
Fonts pdfFonts = new ObjectFactory().createFonts();
|
Fonts pdfFonts = new ObjectFactory().createFonts();
|
||||||
try {
|
try {
|
||||||
@@ -124,7 +123,7 @@ class FopFallbackFontsTest {
|
|||||||
"без init() декларировать нечего");
|
"без init() декларировать нечего");
|
||||||
} finally {
|
} finally {
|
||||||
variants.clear();
|
variants.clear();
|
||||||
variants.putAll(saved);
|
Map.class.getMethod("putAll", Map.class).invoke(variants, savedVariants);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -281,16 +281,16 @@ class DrawMlColorTest {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static CTColor srgbWith(String kind, Object value) {
|
private static <T> CTColor srgbWith(String kind, Class<T> cls, T value) {
|
||||||
CTColor c = srgb("00FF00");
|
CTColor c = srgb("00FF00");
|
||||||
srgbWith(c, kind, value);
|
srgbWith(c, kind, cls, value);
|
||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
/** Класс значения — явным параметром (как в {@link #transform}),
|
||||||
private static void srgbWith(CTColor c, String kind, Object value) {
|
* JAXBElement параметризован без unchecked-каста {@code value.getClass()}. */
|
||||||
c.getSrgbClr().getEGColorTransform().add(
|
private static <T> void srgbWith(CTColor c, String kind, Class<T> cls, T value) {
|
||||||
new JAXBElement<>(new QName(DML_NS, kind), (Class<Object>) value.getClass(), value));
|
c.getSrgbClr().getEGColorTransform().add(transform(kind, cls, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** §20.1.2.3.30: каналы scrgbClr — проценты линейной гаммы, 50% -> BC (пример спеки). */
|
/** §20.1.2.3.30: каналы scrgbClr — проценты линейной гаммы, 50% -> BC (пример спеки). */
|
||||||
@@ -349,7 +349,7 @@ class DrawMlColorTest {
|
|||||||
@Test
|
@Test
|
||||||
void alphaModScalesOpacity() {
|
void alphaModScalesOpacity() {
|
||||||
DrawMlColor colors = new DrawMlColor(null);
|
DrawMlColor colors = new DrawMlColor(null);
|
||||||
Color resolved = colors.resolve(srgbWith("alphaMod", fixedPct(50000)));
|
Color resolved = colors.resolve(srgbWith("alphaMod", CTPositiveFixedPercentage.class, fixedPct(50000)));
|
||||||
assertEquals(128, resolved.getAlpha());
|
assertEquals(128, resolved.getAlpha());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -371,25 +371,25 @@ class DrawMlColorTest {
|
|||||||
DrawMlColor colors = new DrawMlColor(null);
|
DrawMlColor colors = new DrawMlColor(null);
|
||||||
CTAngle hue = new CTAngle();
|
CTAngle hue = new CTAngle();
|
||||||
hue.setVal(14400000);
|
hue.setVal(14400000);
|
||||||
assertEquals(Color.BLUE, colors.resolve(srgbWith("hue", hue)));
|
assertEquals(Color.BLUE, colors.resolve(srgbWith("hue", CTAngle.class, hue)));
|
||||||
// спека для sat 50% даёт 40C040 (floor), у нас округление — 191
|
// спека для sat 50% даёт 40C040 (floor), у нас округление — 191
|
||||||
assertEquals(new Color(64, 191, 64), colors.resolve(srgbWith("sat", fixed(50000))));
|
assertEquals(new Color(64, 191, 64), colors.resolve(srgbWith("sat", CTFixedPercentage.class, fixed(50000))));
|
||||||
assertEquals(new Color(0, 102, 0), colors.resolve(srgbWith("lum", fixed(20000))));
|
assertEquals(new Color(0, 102, 0), colors.resolve(srgbWith("lum", CTFixedPercentage.class, fixed(20000))));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** §20.1.2.3.23-25/.10-12/.4-6: red/green/blue и их Mod/Off. */
|
/** §20.1.2.3.23-25/.10-12/.4-6: red/green/blue и их Mod/Off. */
|
||||||
@Test
|
@Test
|
||||||
void channelSettersModsOffsets() {
|
void channelSettersModsOffsets() {
|
||||||
DrawMlColor colors = new DrawMlColor(null);
|
DrawMlColor colors = new DrawMlColor(null);
|
||||||
assertEquals(new Color(0, 255, 255), colors.resolve(srgbWith("blue", fixed(100000))));
|
assertEquals(new Color(0, 255, 255), colors.resolve(srgbWith("blue", CTFixedPercentage.class, fixed(100000))));
|
||||||
CTColor blueMod = srgb("0000FF");
|
CTColor blueMod = srgb("0000FF");
|
||||||
srgbWith(blueMod, "blueMod", fixed(50000));
|
srgbWith(blueMod, "blueMod", CTFixedPercentage.class, fixed(50000));
|
||||||
assertEquals(new Color(0, 0, 128), colors.resolve(blueMod));
|
assertEquals(new Color(0, 0, 128), colors.resolve(blueMod));
|
||||||
CTColor redOff = srgb("FF0000");
|
CTColor redOff = srgb("FF0000");
|
||||||
srgbWith(redOff, "redOff", fixed(-20000));
|
srgbWith(redOff, "redOff", CTFixedPercentage.class, fixed(-20000));
|
||||||
assertEquals(new Color(204, 0, 0), colors.resolve(redOff));
|
assertEquals(new Color(204, 0, 0), colors.resolve(redOff));
|
||||||
CTColor greenMod = srgb("008000");
|
CTColor greenMod = srgb("008000");
|
||||||
srgbWith(greenMod, "greenMod", fixed(200000));
|
srgbWith(greenMod, "greenMod", CTFixedPercentage.class, fixed(200000));
|
||||||
assertEquals(new Color(0, 255, 0), colors.resolve(greenMod));
|
assertEquals(new Color(0, 255, 0), colors.resolve(greenMod));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user