PMD: слияние новых правил (bestpractices/design/errorprone/multithreading) + правка нарушений без подавлений
PR checks / web (pull_request) Successful in 1m9s
PR checks / java (pull_request) Successful in 1m17s
Main: tests, deploy, autotests / web (push) Successful in 34s
Main: tests, deploy, autotests / images-web (push) Successful in 38s
Main: tests, deploy, autotests / java (push) Successful in 2m36s
Main: tests, deploy, autotests / images-app (push) Successful in 42s
Main: tests, deploy, autotests / deploy (push) Successful in 2m7s
Main: tests, deploy, autotests / autotests (push) Successful in 45s
Main: tests, deploy, autotests / rollback (push) Has been skipped
PR checks / web (pull_request) Successful in 1m9s
PR checks / java (pull_request) Successful in 1m17s
Main: tests, deploy, autotests / web (push) Successful in 34s
Main: tests, deploy, autotests / images-web (push) Successful in 38s
Main: tests, deploy, autotests / java (push) Successful in 2m36s
Main: tests, deploy, autotests / images-app (push) Successful in 42s
Main: tests, deploy, autotests / deploy (push) Successful in 2m7s
Main: tests, deploy, autotests / autotests (push) Successful in 45s
Main: tests, deploy, autotests / rollback (push) Has been skipped
This commit was merged in pull request #106.
This commit is contained in:
@@ -97,7 +97,7 @@ python3 docs/standards/docx/validate-fixtures.py wordpdf-core/src/test/resources
|
|||||||
- Константы UPPER_SNAKE с эталонными значениями (`PIE_DEPTH`, `DECOMPRESS_MB_PER_MAX_MB`); начертания `V_REGULAR/V_BOLD/V_ITALIC/V_BOLD_ITALIC`; модели — `record`; размеры в chart — в пунктах, растр × `DPI/72`.
|
- Константы UPPER_SNAKE с эталонными значениями (`PIE_DEPTH`, `DECOMPRESS_MB_PER_MAX_MB`); начертания `V_REGULAR/V_BOLD/V_ITALIC/V_BOLD_ITALIC`; модели — `record`; размеры в chart — в пунктах, растр × `DPI/72`.
|
||||||
- Логирование: `java.util.logging.Logger` в корневом пакете и `internal/`, SLF4J — в `internal/chart` и `wordpdf-app`.
|
- Логирование: `java.util.logging.Logger` в корневом пакете и `internal/`, SLF4J — в `internal/chart` и `wordpdf-app`.
|
||||||
- Тестовые методы: регрессионные — `объект_условие` через underscore (`ruPlain_cyrillicAndStyles`), юниты — camelCase (`pageFieldBecomesFldSimple`); оба стиля разрешает PMD-паттерн `junit5TestPattern` (`^[a-z][a-zA-Z0-9]*(_[a-zA-Z0-9]+)*$`).
|
- Тестовые методы: регрессионные — `объект_условие` через underscore (`ruPlain_cyrillicAndStyles`), юниты — camelCase (`pageFieldBecomesFldSimple`); оба стиля разрешает PMD-паттерн `junit5TestPattern` (`^[a-z][a-zA-Z0-9]*(_[a-zA-Z0-9]+)*$`).
|
||||||
- PMD (`pmd-ruleset.xml`, execution `pmd-check` на `verify` в обоих модулях, `includeTests=true`, валится нарушение любой приоритетности): полные исключения категории, кастомное XPath-правило `LiteralFirstInEquals` и настройки — в самом ruleset.
|
- PMD (`pmd-ruleset.xml`, execution `pmd-check` на `verify` в обоих модулях, `includeTests=true`, валится нарушение любой приоритетности): полные исключения категории и настройки правил — в самом ruleset. Нарушения чинятся кодом; подавление (`@SuppressWarnings("PMD…")`, `// NOPMD`) запрещено.
|
||||||
|
|
||||||
## Runtime & Tooling
|
## Runtime & Tooling
|
||||||
|
|
||||||
@@ -124,6 +124,6 @@ python3 docs/standards/docx/validate-fixtures.py wordpdf-core/src/test/resources
|
|||||||
- App-тесты: `@SpringBootTest` + `@AutoConfigureMockMvc` (Boot 4: `org.springframework.boot.webmvc.test.autoconfigure`); четыре набора свойств = четыре контекста (отдельные классы, не `@Nested`); `ConversionServiceTest`/`ApiExceptionHandlerTest` — без Spring. Core-юниты Spring **не поднимают**; app-тесты проверяют только HTTP-код/заголовки/текст ошибки. Детали — `docs/agent/testing.md`.
|
- App-тесты: `@SpringBootTest` + `@AutoConfigureMockMvc` (Boot 4: `org.springframework.boot.webmvc.test.autoconfigure`); четыре набора свойств = четыре контекста (отдельные классы, не `@Nested`); `ConversionServiceTest`/`ApiExceptionHandlerTest` — без Spring. Core-юниты Spring **не поднимают**; app-тесты проверяют только HTTP-код/заголовки/текст ошибки. Детали — `docs/agent/testing.md`.
|
||||||
- Жизненный цикл: только `@Test`; исключения — два `@BeforeAll` (прогрев шрифтов) и `@AfterEach drainWorker` в `ConversionTimeoutTest`. Ни `@Nested`, ни `@ParameterizedTest`, ни `@Disabled`, ни `assertAll`.
|
- Жизненный цикл: только `@Test`; исключения — два `@BeforeAll` (прогрев шрифтов) и `@AfterEach drainWorker` в `ConversionTimeoutTest`. Ни `@Nested`, ни `@ParameterizedTest`, ни `@Disabled`, ни `assertAll`.
|
||||||
- Идиомы загрузки фикстур: **core** — classloader без ведущего слэша, **app** — class-relative со слэшем (core test-jar). Синтетика: docx — `ZipOutputStream`, `.doc` — крафт `POIFSFileSystem`.
|
- Идиомы загрузки фикстур: **core** — classloader без ведущего слэша, **app** — class-relative со слэшем (core test-jar). Синтетика: docx — `ZipOutputStream`, `.doc` — крафт `POIFSFileSystem`.
|
||||||
- Сообщения ассертов — по-русски и с наблюдаемым значением; сравнение строк литерал-слева (`"%PDF".equals(...)`, PMD `LiteralFirstInEquals`); контракт идентичности — `assertSame`/`assertNotSame`. Общих test-util-классов нет: хелперы (`norm`, `pdfText`, `assertRatio`) намеренно продублированы.
|
- Сообщения ассертов — по-русски и с наблюдаемым значением; сравнение строк литерал-слева (`"%PDF".equals(...)`, PMD `LiteralsFirstInComparisons`); контракт идентичности — `assertSame`/`assertNotSame`. Общих test-util-классов нет: хелперы (`norm`, `pdfText`, `assertRatio`) намеренно продублированы.
|
||||||
- Прод-автотесты: pytest + requests; под маркером `needs_key` без ключа SKIP; конфигурация стенда **только env** (`WORDPDF_BASE_URL` обязателен).
|
- Прод-автотесты: pytest + requests; под маркером `needs_key` без ключа SKIP; конфигурация стенда **только env** (`WORDPDF_BASE_URL` обязателен).
|
||||||
- `mvn test` **не** запускает PMD и JaCoCo-гейты (оба на `verify`) — «зелёное» состояние проверяется `mvn clean verify`. `mvn -pl wordpdf-app` без `-am` падает: app зависит от core test-jar.
|
- `mvn test` **не** запускает PMD и JaCoCo-гейты (оба на `verify`) — «зелёное» состояние проверяется `mvn clean verify`. `mvn -pl wordpdf-app` без `-am` падает: app зависит от core test-jar.
|
||||||
|
|||||||
+37
-19
@@ -2,8 +2,11 @@
|
|||||||
<ruleset name="WordPDF code style" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
|
<ruleset name="WordPDF code style" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
|
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
|
||||||
<description>Код-стиль java-word-pdf: codestyle без opinionated-правил + unused-правила + NPE-safe equals</description>
|
<description>Код-стиль java-word-pdf: codestyle без opinionated-правил, unused-правила,
|
||||||
|
NPE-safe сравнения, гигиена ошибок/ресурсов/многопоточности. Нарушения чинятся
|
||||||
|
кодом — подавление @SuppressWarnings("PMD…") и // NOPMD запрещены.</description>
|
||||||
|
|
||||||
|
<!-- ==================== codestyle ==================== -->
|
||||||
<rule ref="category/java/codestyle.xml">
|
<rule ref="category/java/codestyle.xml">
|
||||||
<!-- opinionated/шумные, намеренно выключены -->
|
<!-- opinionated/шумные, намеренно выключены -->
|
||||||
<exclude name="AtLeastOneConstructor"/>
|
<exclude name="AtLeastOneConstructor"/>
|
||||||
@@ -23,6 +26,8 @@
|
|||||||
<!-- переопределены ниже -->
|
<!-- переопределены ниже -->
|
||||||
<exclude name="MethodNamingConventions"/>
|
<exclude name="MethodNamingConventions"/>
|
||||||
<exclude name="TooManyStaticImports"/>
|
<exclude name="TooManyStaticImports"/>
|
||||||
|
<exclude name="ControlStatementBraces"/>
|
||||||
|
<exclude name="UnnecessaryImport"/>
|
||||||
</rule>
|
</rule>
|
||||||
|
|
||||||
<!-- регрессионные тесты репо именуются объект_условие (AGENTS.md) -->
|
<!-- регрессионные тесты репо именуются объект_условие (AGENTS.md) -->
|
||||||
@@ -39,31 +44,35 @@
|
|||||||
</properties>
|
</properties>
|
||||||
</rule>
|
</rule>
|
||||||
|
|
||||||
<!-- PMD 7 удалил EqualsAvoidsNull; NPE-safe порядок операндов: литерал слева -->
|
<rule ref="category/java/codestyle.xml/UnnecessaryImport"/>
|
||||||
<rule name="LiteralFirstInEquals" language="java"
|
|
||||||
message="NPE-safe сравнение строк: строковый литерал должен стоять слева: "lit".equals(x)"
|
<!-- case без скобок — норма для этого стиля; true, если строже -->
|
||||||
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
|
<rule ref="category/java/codestyle.xml/ControlStatementBraces">
|
||||||
<priority>3</priority>
|
|
||||||
<properties>
|
<properties>
|
||||||
<property name="xpath">
|
<property name="checkCaseStmt" value="false"/>
|
||||||
<value><![CDATA[
|
|
||||||
//MethodCall[
|
|
||||||
(@MethodName = 'equals' or @MethodName = 'equalsIgnoreCase')
|
|
||||||
and ArgumentList/StringLiteral
|
|
||||||
and not(*[1][self::StringLiteral
|
|
||||||
or (self::VariableAccess and @CompileTimeConstant = true())])
|
|
||||||
]
|
|
||||||
]]></value>
|
|
||||||
</property>
|
|
||||||
</properties>
|
</properties>
|
||||||
</rule>
|
</rule>
|
||||||
|
|
||||||
|
<!-- ==================== bestpractices ==================== -->
|
||||||
<rule ref="category/java/bestpractices.xml/UnusedAssignment"/>
|
<rule ref="category/java/bestpractices.xml/UnusedAssignment"/>
|
||||||
<rule ref="category/java/bestpractices.xml/UnusedFormalParameter"/>
|
<rule ref="category/java/bestpractices.xml/UnusedFormalParameter"/>
|
||||||
<rule ref="category/java/bestpractices.xml/UnusedLocalVariable"/>
|
<rule ref="category/java/bestpractices.xml/UnusedLocalVariable"/>
|
||||||
<rule ref="category/java/bestpractices.xml/UnusedPrivateField"/>
|
<rule ref="category/java/bestpractices.xml/UnusedPrivateField"/>
|
||||||
<rule ref="category/java/bestpractices.xml/UnusedPrivateMethod"/>
|
<rule ref="category/java/bestpractices.xml/UnusedPrivateMethod"/>
|
||||||
|
<rule ref="category/java/bestpractices.xml/ForLoopCanBeForeach">
|
||||||
|
<priority>2</priority>
|
||||||
|
</rule>
|
||||||
|
<rule ref="category/java/bestpractices.xml/AvoidPrintStackTrace"/>
|
||||||
|
<rule ref="category/java/bestpractices.xml/SystemPrintln"/>
|
||||||
|
<!-- NPE-safe порядок операндов: литерал/константа слева. Заменило кастомное
|
||||||
|
XPath-правило LiteralFirstInEquals: штатное правило строго шире (константа
|
||||||
|
справа — тоже нарушение, плюс ==/!= по строкам). -->
|
||||||
|
<rule ref="category/java/bestpractices.xml/LiteralsFirstInComparisons"/>
|
||||||
|
|
||||||
|
<!-- ==================== design ==================== -->
|
||||||
|
<rule ref="category/java/design.xml/ExceptionAsFlowControl"/>
|
||||||
|
|
||||||
|
<!-- ==================== errorprone ==================== -->
|
||||||
<!-- null вместо пустой коллекции запрещён (priority 1 по умолчанию — валит verify) -->
|
<!-- null вместо пустой коллекции запрещён (priority 1 по умолчанию — валит verify) -->
|
||||||
<rule ref="category/java/errorprone.xml/ReturnEmptyCollectionRatherThanNull"/>
|
<rule ref="category/java/errorprone.xml/ReturnEmptyCollectionRatherThanNull"/>
|
||||||
<!-- литералы в условиях if — только именованными константами -->
|
<!-- литералы в условиях if — только именованными константами -->
|
||||||
@@ -71,7 +80,16 @@
|
|||||||
<rule ref="category/java/errorprone.xml/EmptyCatchBlock">
|
<rule ref="category/java/errorprone.xml/EmptyCatchBlock">
|
||||||
<priority>2</priority>
|
<priority>2</priority>
|
||||||
</rule>
|
</rule>
|
||||||
<rule ref="category/java/bestpractices.xml/ForLoopCanBeForeach">
|
<rule ref="category/java/errorprone.xml/EqualsNull"/>
|
||||||
<priority>2</priority>
|
<rule ref="category/java/errorprone.xml/CloseResource"/>
|
||||||
</rule>
|
<rule ref="category/java/errorprone.xml/BrokenNullCheck"/>
|
||||||
|
<rule ref="category/java/errorprone.xml/AvoidCatchingNPE"/>
|
||||||
|
<rule ref="category/java/errorprone.xml/AssignmentToNonFinalStatic"/>
|
||||||
|
<rule ref="category/java/errorprone.xml/DoNotCallGarbageCollectionExplicitly"/>
|
||||||
|
<rule ref="category/java/errorprone.xml/CompareObjectsWithEquals"/>
|
||||||
|
<rule ref="category/java/errorprone.xml/MisplacedNullCheck"/>
|
||||||
|
<rule ref="category/java/errorprone.xml/ImplicitSwitchFallThrough"/>
|
||||||
|
|
||||||
|
<!-- ==================== multithreading ==================== -->
|
||||||
|
<rule ref="category/java/multithreading.xml/UnsynchronizedStaticFormatter"/>
|
||||||
</ruleset>
|
</ruleset>
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import java.io.ByteArrayInputStream;
|
|||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import javax.xml.transform.Templates;
|
import javax.xml.transform.Templates;
|
||||||
|
import javax.xml.transform.TransformerConfigurationException;
|
||||||
import javax.xml.transform.stream.StreamSource;
|
import javax.xml.transform.stream.StreamSource;
|
||||||
import javax.imageio.ImageIO;
|
import javax.imageio.ImageIO;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -490,7 +491,7 @@ public final class WordPdfConverter {
|
|||||||
throw new ConversionException("Ресурс xslt/docx2fo.xslt не найден");
|
throw new ConversionException("Ресурс xslt/docx2fo.xslt не найден");
|
||||||
}
|
}
|
||||||
return XmlUtils.getTransformerFactory().newTemplates(new StreamSource(xslt));
|
return XmlUtils.getTransformerFactory().newTemplates(new StreamSource(xslt));
|
||||||
} catch (Exception e) {
|
} catch (IOException | TransformerConfigurationException e) {
|
||||||
throw new ConversionException("Не удалось скомпилировать xslt/docx2fo.xslt", e);
|
throw new ConversionException("Не удалось скомпилировать xslt/docx2fo.xslt", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ public final class DocxRewritePipeline {
|
|||||||
if (next != null) {
|
if (next != null) {
|
||||||
cur = next;
|
cur = next;
|
||||||
}
|
}
|
||||||
if (cur != xml) {
|
if (!cur.equals(xml)) {
|
||||||
changed = true;
|
changed = true;
|
||||||
rewritten = cur.getBytes(StandardCharsets.UTF_8);
|
rewritten = cur.getBytes(StandardCharsets.UTF_8);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -259,7 +259,7 @@ public final class OleObjectNormalizer {
|
|||||||
if (fixed != null) {
|
if (fixed != null) {
|
||||||
data = fixed.getBytes(StandardCharsets.UTF_8);
|
data = fixed.getBytes(StandardCharsets.UTF_8);
|
||||||
}
|
}
|
||||||
} else if (name.equals(CONTENT_TYPES_ENTRY)) {
|
} else if (CONTENT_TYPES_ENTRY.equals(name)) {
|
||||||
String fixed = stripOverrides(
|
String fixed = stripOverrides(
|
||||||
new String(data, StandardCharsets.UTF_8), oleParts);
|
new String(data, StandardCharsets.UTF_8), oleParts);
|
||||||
if (fixed != null) {
|
if (fixed != null) {
|
||||||
|
|||||||
@@ -70,12 +70,12 @@ final class CartesianPainter {
|
|||||||
"percentStacked".equalsIgnoreCase(lineGrouping))
|
"percentStacked".equalsIgnoreCase(lineGrouping))
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
// Разделение серий по осям значений: ссылочное равенство с secondaryValAxis
|
// Разделение серий по осям значений: та же ось по c:axId
|
||||||
// (назначается ChartSpec.parse по c:axId, §21.2.2.9).
|
// (назначается ChartSpec.parse, §21.2.2.9; {@link ChartSpec#sameAxis}).
|
||||||
List<Integer> primIdx = new ArrayList<>();
|
List<Integer> primIdx = new ArrayList<>();
|
||||||
List<Integer> secIdx = new ArrayList<>();
|
List<Integer> secIdx = new ArrayList<>();
|
||||||
for (int si = 0; si < spec.series.size(); si++) {
|
for (int si = 0; si < spec.series.size(); si++) {
|
||||||
if (secAxis != null && spec.series.get(si).valAxis == secAxis) {
|
if (ChartSpec.sameAxis(spec.series.get(si).valAxis, secAxis)) {
|
||||||
secIdx.add(si);
|
secIdx.add(si);
|
||||||
} else {
|
} else {
|
||||||
primIdx.add(si);
|
primIdx.add(si);
|
||||||
@@ -278,9 +278,9 @@ final class CartesianPainter {
|
|||||||
return gr != null ? gr : spec.grouping;
|
return gr != null ? gr : spec.grouping;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Серия на вторичной оси значений (ссылочное равенство с secondaryValAxis). */
|
/** Серия на вторичной оси значений (та же ось по c:axId, §21.2.2.9; {@link ChartSpec#sameAxis}). */
|
||||||
private static boolean onSecondary(ChartSpec.Series s, ChartSpec spec) {
|
private static boolean onSecondary(ChartSpec.Series s, ChartSpec spec) {
|
||||||
return spec.secondaryValAxis != null && s.valAxis == spec.secondaryValAxis;
|
return ChartSpec.sameAxis(s.valAxis, spec.secondaryValAxis);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<Integer> intersect(List<Integer> family, List<Integer> prim) {
|
private static List<Integer> intersect(List<Integer> family, List<Integer> prim) {
|
||||||
|
|||||||
@@ -396,7 +396,7 @@ final class ChartSpec {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (va == null || va == spec.valAxis) {
|
if (va == null || sameAxis(va, spec.valAxis)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (spec.secondaryValAxis == null) {
|
if (spec.secondaryValAxis == null) {
|
||||||
@@ -409,6 +409,14 @@ final class ChartSpec {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Та же ось по c:axId (§21.2.2.9): id уникален в диаграмме, оси с id ≥ 0 лежат
|
||||||
|
* в {@code axesById} по одному на id — для осей, назначенных из карты при разборе,
|
||||||
|
* эквивалентно ссылочному равенству. Прямое сравнение осей через == запрещено
|
||||||
|
* PMD CompareObjectsWithEquals; null и id < 0 — никогда «та же». */
|
||||||
|
static boolean sameAxis(AxisSpec a, AxisSpec b) {
|
||||||
|
return a != null && b != null && a.axId >= 0 && a.axId == b.axId;
|
||||||
|
}
|
||||||
|
|
||||||
private static void readChartFrame(CTChartSpace space, ChartSpec spec, DrawMlColor colors) {
|
private static void readChartFrame(CTChartSpace space, ChartSpec spec, DrawMlColor colors) {
|
||||||
CTShapeProperties sp = space.getSpPr();
|
CTShapeProperties sp = space.getSpPr();
|
||||||
if (sp == null) {
|
if (sp == null) {
|
||||||
|
|||||||
+14
-4
@@ -46,7 +46,9 @@ import java.io.ByteArrayInputStream;
|
|||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.IdentityHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
@@ -134,6 +136,7 @@ public final class DrawingPreRenderer {
|
|||||||
// ConcurrentModificationException.
|
// ConcurrentModificationException.
|
||||||
List<Part> parts = new ArrayList<>(pkg.getParts().getParts().values());
|
List<Part> parts = new ArrayList<>(pkg.getParts().getParts().values());
|
||||||
Set<Part> handled = new HashSet<>();
|
Set<Part> handled = new HashSet<>();
|
||||||
|
Set<List<?>> visitedContents = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||||
int[] idSeq = {1000};
|
int[] idSeq = {1000};
|
||||||
long[] pngTotal = {0};
|
long[] pngTotal = {0};
|
||||||
for (Part p : parts) {
|
for (Part p : parts) {
|
||||||
@@ -144,7 +147,7 @@ public final class DrawingPreRenderer {
|
|||||||
if (content.isEmpty()) {
|
if (content.isEmpty()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
walk(p, content, pkg, colors, idSeq, pngTotal, maxPngBytesTotal, options);
|
walk(p, content, pkg, colors, idSeq, pngTotal, maxPngBytesTotal, options, visitedContents);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,7 +174,14 @@ public final class DrawingPreRenderer {
|
|||||||
|
|
||||||
private static void walk(Part part, List<?> content, WordprocessingMLPackage pkg,
|
private static void walk(Part part, List<?> content, WordprocessingMLPackage pkg,
|
||||||
DrawMlColor colors, int[] idSeq, long[] pngTotal,
|
DrawMlColor colors, int[] idSeq, long[] pngTotal,
|
||||||
long maxPngBytesTotal, ConvertOptions options) {
|
long maxPngBytesTotal, ConvertOptions options,
|
||||||
|
Set<List<?>> visitedContents) {
|
||||||
|
// Посещённые списки — по идентичности (IdentityHashMap): рефлексивный
|
||||||
|
// getContent (ребёнок возвращает список родителя) не зацикливает обход.
|
||||||
|
// Сравнение списков через ==/!= запрещено PMD CompareObjectsWithEquals.
|
||||||
|
if (!visitedContents.add(content)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
for (Object o : content) {
|
for (Object o : content) {
|
||||||
Object v = o instanceof JAXBElement ? ((JAXBElement<?>) o).getValue() : o;
|
Object v = o instanceof JAXBElement ? ((JAXBElement<?>) o).getValue() : o;
|
||||||
if (v instanceof Drawing drawing) {
|
if (v instanceof Drawing drawing) {
|
||||||
@@ -179,8 +189,8 @@ public final class DrawingPreRenderer {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
List<?> nested = invokeList(v, "getContent");
|
List<?> nested = invokeList(v, "getContent");
|
||||||
if (!nested.isEmpty() && nested != content) {
|
if (!nested.isEmpty()) {
|
||||||
walk(part, nested, pkg, colors, idSeq, pngTotal, maxPngBytesTotal, options);
|
walk(part, nested, pkg, colors, idSeq, pngTotal, maxPngBytesTotal, options, visitedContents);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import java.nio.file.Files;
|
|||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.logging.Logger;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
@@ -34,6 +35,8 @@ public final class ChartTypesDocxGenerator {
|
|||||||
private static final String A = "http://schemas.openxmlformats.org/drawingml/2006/main";
|
private static final String A = "http://schemas.openxmlformats.org/drawingml/2006/main";
|
||||||
private static final String R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
private static final String R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
||||||
|
|
||||||
|
private static final Logger LOG = Logger.getLogger(ChartTypesDocxGenerator.class.getName());
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
Path out = Path.of(args[0]);
|
Path out = Path.of(args[0]);
|
||||||
List<String> titles = List.of(
|
List<String> titles = List.of(
|
||||||
@@ -109,7 +112,7 @@ public final class ChartTypesDocxGenerator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Files.write(out, out2.toByteArray());
|
Files.write(out, out2.toByteArray());
|
||||||
System.out.println("written " + out + " " + out2.size() + " bytes");
|
LOG.info("written " + out + " " + out2.size() + " bytes");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String space(String title, String groupWithAxes) {
|
private static String space(String title, String groupWithAxes) {
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ import java.math.BigInteger;
|
|||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ОДНОРАЗОВАЯ утилита: генерация готовых .docx для тестов (Apache POI).
|
* ОДНОРАЗОВАЯ утилита: генерация готовых .docx для тестов (Apache POI).
|
||||||
@@ -59,6 +60,8 @@ public final class SampleDocxGenerator {
|
|||||||
/** Путь основной части документа в zip. */
|
/** Путь основной части документа в zip. */
|
||||||
private static final String DOCUMENT_PART = "word/document.xml";
|
private static final String DOCUMENT_PART = "word/document.xml";
|
||||||
|
|
||||||
|
private static final Logger LOG = Logger.getLogger(SampleDocxGenerator.class.getName());
|
||||||
|
|
||||||
private SampleDocxGenerator() {
|
private SampleDocxGenerator() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,7 +80,7 @@ public final class SampleDocxGenerator {
|
|||||||
tooManyPages(dir.resolve("too-many-pages.docx"));
|
tooManyPages(dir.resolve("too-many-pages.docx"));
|
||||||
staleCache(dir.resolve("stale-cache.docx"));
|
staleCache(dir.resolve("stale-cache.docx"));
|
||||||
|
|
||||||
System.out.println("Готово: " + dir.toAbsolutePath());
|
LOG.info("Готово: " + dir.toAbsolutePath());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Русский текст, Calibri, заголовок + полужирный и курсивный run'ы. */
|
/** Русский текст, Calibri, заголовок + полужирный и курсивный run'ы. */
|
||||||
@@ -498,7 +501,7 @@ public final class SampleDocxGenerator {
|
|||||||
try (FileOutputStream fos = new FileOutputStream(out.toFile())) {
|
try (FileOutputStream fos = new FileOutputStream(out.toFile())) {
|
||||||
doc.write(fos);
|
doc.write(fos);
|
||||||
}
|
}
|
||||||
System.out.println(" создан: " + out.getFileName()
|
LOG.info(" создан: " + out.getFileName()
|
||||||
+ " (" + new File(out.toString()).length() + " байт)");
|
+ " (" + new File(out.toString()).length() + " байт)");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -110,12 +110,9 @@ class CfbReaderTest {
|
|||||||
for (int i = 0; i < specs.length; i++) {
|
for (int i = 0; i < specs.length; i++) {
|
||||||
Spec s = specs[i];
|
Spec s = specs[i];
|
||||||
boolean smallOne = s.data().length < 4096;
|
boolean smallOne = s.data().length < 4096;
|
||||||
int idx = -1;
|
// Spec — record с byte[]: equals сравнивает массив по ссылке, indexOf
|
||||||
for (int k = 0; k < (smallOne ? small : big).size(); k++) {
|
// находит ровно тот же экземпляр, что добавлялся в small/big.
|
||||||
if ((smallOne ? small : big).get(k) == s) {
|
int idx = (smallOne ? small : big).indexOf(s);
|
||||||
idx = k;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
dirEntry(file, 1, 1 + i, s.name(), 2,
|
dirEntry(file, 1, 1 + i, s.name(), 2,
|
||||||
smallOne ? miniHead[idx] : bigHead[idx], s.data().length);
|
smallOne ? miniHead[idx] : bigHead[idx], s.data().length);
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -377,7 +377,7 @@ class DocToDocxFormattingTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static byte[] cfb(boolean use1Table, boolean withTable) throws IOException {
|
private static byte[] cfb(boolean use1Table, boolean withTable) throws IOException {
|
||||||
POIFSFileSystem fs = new POIFSFileSystem();
|
try (POIFSFileSystem fs = new POIFSFileSystem()) {
|
||||||
byte[] wd = wordDocument();
|
byte[] wd = wordDocument();
|
||||||
if (!use1Table) {
|
if (!use1Table) {
|
||||||
wd[11] &= ~0x02; // fWhichTblStm (бит 9 u16) → 0Table
|
wd[11] &= ~0x02; // fWhichTblStm (бит 9 u16) → 0Table
|
||||||
@@ -390,9 +390,9 @@ class DocToDocxFormattingTest {
|
|||||||
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
|
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
|
||||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
fs.writeFilesystem(out);
|
fs.writeFilesystem(out);
|
||||||
fs.close();
|
|
||||||
return out.toByteArray();
|
return out.toByteArray();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static String documentXml(byte[] doc) throws IOException {
|
private static String documentXml(byte[] doc) throws IOException {
|
||||||
return partXml(doc, DOCUMENT_XML);
|
return partXml(doc, DOCUMENT_XML);
|
||||||
|
|||||||
Reference in New Issue
Block a user