fix(core): DependencyGuard — понятная ошибка при старой commons-compress у потребителя
PR checks / web (pull_request) Successful in 49s
PR checks / java (pull_request) Successful in 1m2s
Main: tests, deploy, autotests / web (push) Successful in 44s
Main: tests, deploy, autotests / java (push) Successful in 57s
Main: tests, deploy, autotests / images-web (push) Successful in 30s
Main: tests, deploy, autotests / images-app (push) Successful in 5m12s
Main: tests, deploy, autotests / deploy (push) Successful in 1m34s
Main: tests, deploy, autotests / autotests (push) Successful in 49s
Main: tests, deploy, autotests / rollback (push) Has been skipped
PR checks / web (pull_request) Successful in 49s
PR checks / java (pull_request) Successful in 1m2s
Main: tests, deploy, autotests / web (push) Successful in 44s
Main: tests, deploy, autotests / java (push) Successful in 57s
Main: tests, deploy, autotests / images-web (push) Successful in 30s
Main: tests, deploy, autotests / images-app (push) Successful in 5m12s
Main: tests, deploy, autotests / deploy (push) Successful in 1m34s
Main: tests, deploy, autotests / autotests (push) Successful in 49s
Main: tests, deploy, autotests / rollback (push) Has been skipped
docx4j 17.3.2 требует ковариантный ZipArchiveInputStream.getNextEntry() (>= 1.25.0); BOM/nearest-wins потребителя мог навязать старую версию — конвертация падала NoSuchMethodError внутри docx4j. Теперь шаг 0 convertToStream бросает ConversionException с инструкцией; commons-compress объявлена явной зависимостью ядра (1.28.0, версия docx4j); README — закрепление версии в Maven/Gradle. Регрессия — DependencyGuardTest, негативная ветка проверена подменой jar (1.21 → ConversionException).
This commit was merged in pull request #56.
This commit is contained in:
@@ -11,6 +11,7 @@ import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
|
||||
import ru.pjandro.wordpdf.fonts.BundledFontMapper;
|
||||
import ru.pjandro.wordpdf.fonts.BundledFonts;
|
||||
import ru.pjandro.wordpdf.internal.chart.DrawingPreRenderer;
|
||||
import ru.pjandro.wordpdf.internal.DependencyGuard;
|
||||
import ru.pjandro.wordpdf.internal.DocxNormalizer;
|
||||
import ru.pjandro.wordpdf.internal.DocxOnOffNormalizer;
|
||||
import ru.pjandro.wordpdf.internal.FieldNormalizer;
|
||||
@@ -116,10 +117,16 @@ public final class WordPdfConverter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ядро конвертации: docx -> XSL-FO -> FOP -> PDF в поток.
|
||||
* Ядро конвертации: docx -> XSL-FO -> FOP -> PDF в поток. Шаг 0 — проверка
|
||||
* совместимости commons-compress в classpath потребителя (DependencyGuard):
|
||||
* без неё старая версия библиотеки дала бы мутный NoSuchMethodError внутри docx4j.
|
||||
*/
|
||||
private static void convertToStream(byte[] rawDocxBytes, String title, ConvertOptions options,
|
||||
OutputStream os) throws Exception {
|
||||
// 0. Совместимость commons-compress: docx4j требует ковариантный
|
||||
// ZipArchiveInputStream.getNextEntry() (>= 1.25.0); ниже — понятный
|
||||
// ConversionException с инструкцией вместо NoSuchMethodError.
|
||||
DependencyGuard.check();
|
||||
// 1. Маппер шрифтов. Порядок важен: конструктор запускает
|
||||
// обнаружение системных шрифтов, затем бандл-шрифты из jar
|
||||
// регистрируются поверх них (имеют приоритет).
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
|
||||
import ru.pjandro.wordpdf.ConversionException;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* Проверка совместимости commons-compress в classpath потребителя.
|
||||
*
|
||||
* <p>docx4j читает zip-контейнер docx через
|
||||
* {@code org.docx4j.openpackaging.io3.stores.ZipPartStore}, который вызывает
|
||||
* ковариантный {@code ZipArchiveInputStream.getNextEntry(): ZipArchiveEntry}
|
||||
* — он появился только в commons-compress 1.25.0. Если у потребителя старая
|
||||
* версия (BOM, например Spring Boot 3.x, или nearest-wins в Maven навязали
|
||||
* понижение), конвертация падала мутным {@code NoSuchMethodError} внутри
|
||||
* docx4j. Guard бросает {@link ConversionException} с текстом-инструкцией
|
||||
* до входа в docx4j.</p>
|
||||
*
|
||||
* <p>Порог определяется API-пробой (возврат {@code getMethod("getNextEntry")}),
|
||||
* а не разбором строки версии: {@code getImplementationVersion()} бывает
|
||||
* {@code null} в shaded/uber-jar сборках, а проба ловит ровно тот бинарный
|
||||
* контракт, который реально ломается.</p>
|
||||
*/
|
||||
public final class DependencyGuard {
|
||||
|
||||
private DependencyGuard() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Бросает {@link ConversionException}, если commons-compress в classpath
|
||||
* несовместим с docx4j 17.3.2 (нет ковариантного {@code getNextEntry},
|
||||
* т.е. версия ниже 1.25.0, либо библиотека отсутствует).
|
||||
*/
|
||||
public static void check() {
|
||||
String reason = incompatibleReason();
|
||||
if (reason != null) {
|
||||
throw new ConversionException(reason);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Причина отказа или {@code null}, если classpath совместим.
|
||||
* Package-private хук для юнит-теста (негативную ветку surefire покрыть
|
||||
* нельзя — одна версия jar на тестовом classpath, см. DependencyGuardTest).
|
||||
*/
|
||||
static String incompatibleReason() {
|
||||
String found;
|
||||
try {
|
||||
Method m = ZipArchiveInputStream.class.getMethod("getNextEntry");
|
||||
if (ZipArchiveEntry.class.equals(m.getReturnType())) {
|
||||
return null; // >= 1.25.0: ковариантный getNextEntry на месте
|
||||
}
|
||||
String v = ZipArchiveInputStream.class.getPackage().getImplementationVersion();
|
||||
found = v == null ? "версия не определена" : v;
|
||||
} catch (NoSuchMethodException e) {
|
||||
found = "версия не определена"; // нет даже getNextEntry — доисторическая сборка
|
||||
} catch (NoClassDefFoundError e) {
|
||||
return "В classpath отсутствует org.apache.commons:commons-compress — "
|
||||
+ "docx4j требует версию 1.28.0 (минимум 1.25.0).";
|
||||
}
|
||||
return "Несовместимая версия commons-compress в classpath (найдена: " + found
|
||||
+ "): docx4j требует >= 1.25.0, рекомендована 1.28.0. Старую версию обычно"
|
||||
+ " навязывает BOM или nearest-wins. Закрепите org.apache.commons:commons-compress"
|
||||
+ " версии 1.28.0: Maven — запись в dependencyManagement, Gradle — constraints"
|
||||
+ " или resolutionStrategy.force (см. README, раздел «Библиотека»).";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
/**
|
||||
* Guard на тестовом classpath (commons-compress 1.28.0) — no-op.
|
||||
* Негативная ветка (старая версия jar) surefire-покрытию недоступна — одна
|
||||
* версия jar на classpath; проверена эмпирически подменой jar в classpath
|
||||
* прогона (1.21 → ConversionException, 1.25.0/1.28.0 → OK).
|
||||
*/
|
||||
class DependencyGuardTest {
|
||||
|
||||
@Test
|
||||
void checkPassesOnCurrentClasspath() {
|
||||
assertDoesNotThrow(DependencyGuard::check);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reasonNullOnCurrentClasspath() {
|
||||
assertNull(DependencyGuard.incompatibleReason());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user