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

This commit was merged in pull request #106.
This commit is contained in:
Pjandro
2026-11-13 01:24:25 +03:00
parent d8eda0a2e4
commit 0b2dda8caa
12 changed files with 97 additions and 57 deletions
@@ -31,6 +31,7 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.imageio.ImageIO;
import java.io.InputStream;
@@ -490,7 +491,7 @@ public final class WordPdfConverter {
throw new ConversionException("Ресурс xslt/docx2fo.xslt не найден");
}
return XmlUtils.getTransformerFactory().newTemplates(new StreamSource(xslt));
} catch (Exception e) {
} catch (IOException | TransformerConfigurationException e) {
throw new ConversionException("Не удалось скомпилировать xslt/docx2fo.xslt", e);
}
}
@@ -137,7 +137,7 @@ public final class DocxRewritePipeline {
if (next != null) {
cur = next;
}
if (cur != xml) {
if (!cur.equals(xml)) {
changed = true;
rewritten = cur.getBytes(StandardCharsets.UTF_8);
}
@@ -259,7 +259,7 @@ public final class OleObjectNormalizer {
if (fixed != null) {
data = fixed.getBytes(StandardCharsets.UTF_8);
}
} else if (name.equals(CONTENT_TYPES_ENTRY)) {
} else if (CONTENT_TYPES_ENTRY.equals(name)) {
String fixed = stripOverrides(
new String(data, StandardCharsets.UTF_8), oleParts);
if (fixed != null) {
@@ -70,12 +70,12 @@ final class CartesianPainter {
"percentStacked".equalsIgnoreCase(lineGrouping))
: null;
// Разделение серий по осям значений: ссылочное равенство с secondaryValAxis
// (назначается ChartSpec.parse по c:axId, §21.2.2.9).
// Разделение серий по осям значений: та же ось по c:axId
// (назначается ChartSpec.parse, §21.2.2.9; {@link ChartSpec#sameAxis}).
List<Integer> primIdx = new ArrayList<>();
List<Integer> secIdx = new ArrayList<>();
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);
} else {
primIdx.add(si);
@@ -278,9 +278,9 @@ final class CartesianPainter {
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) {
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) {
@@ -396,7 +396,7 @@ final class ChartSpec {
break;
}
}
if (va == null || va == spec.valAxis) {
if (va == null || sameAxis(va, spec.valAxis)) {
continue;
}
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 &lt; 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) {
CTShapeProperties sp = space.getSpPr();
if (sp == null) {
@@ -46,7 +46,9 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
@@ -134,6 +136,7 @@ public final class DrawingPreRenderer {
// ConcurrentModificationException.
List<Part> parts = new ArrayList<>(pkg.getParts().getParts().values());
Set<Part> handled = new HashSet<>();
Set<List<?>> visitedContents = Collections.newSetFromMap(new IdentityHashMap<>());
int[] idSeq = {1000};
long[] pngTotal = {0};
for (Part p : parts) {
@@ -144,7 +147,7 @@ public final class DrawingPreRenderer {
if (content.isEmpty()) {
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,
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) {
Object v = o instanceof JAXBElement ? ((JAXBElement<?>) o).getValue() : o;
if (v instanceof Drawing drawing) {
@@ -179,8 +189,8 @@ public final class DrawingPreRenderer {
continue;
}
List<?> nested = invokeList(v, "getContent");
if (!nested.isEmpty() && nested != content) {
walk(part, nested, pkg, colors, idSeq, pngTotal, maxPngBytesTotal, options);
if (!nested.isEmpty()) {
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.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
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 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 {
Path out = Path.of(args[0]);
List<String> titles = List.of(
@@ -109,7 +112,7 @@ public final class ChartTypesDocxGenerator {
}
}
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) {
@@ -35,6 +35,7 @@ import java.math.BigInteger;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.logging.Logger;
/**
* ОДНОРАЗОВАЯ утилита: генерация готовых .docx для тестов (Apache POI).
@@ -59,6 +60,8 @@ public final class SampleDocxGenerator {
/** Путь основной части документа в zip. */
private static final String DOCUMENT_PART = "word/document.xml";
private static final Logger LOG = Logger.getLogger(SampleDocxGenerator.class.getName());
private SampleDocxGenerator() {
}
@@ -77,7 +80,7 @@ public final class SampleDocxGenerator {
tooManyPages(dir.resolve("too-many-pages.docx"));
staleCache(dir.resolve("stale-cache.docx"));
System.out.println("Готово: " + dir.toAbsolutePath());
LOG.info("Готово: " + dir.toAbsolutePath());
}
/** Русский текст, Calibri, заголовок + полужирный и курсивный run'ы. */
@@ -498,7 +501,7 @@ public final class SampleDocxGenerator {
try (FileOutputStream fos = new FileOutputStream(out.toFile())) {
doc.write(fos);
}
System.out.println(" создан: " + out.getFileName()
LOG.info(" создан: " + out.getFileName()
+ " (" + new File(out.toString()).length() + " байт)");
}
}
@@ -110,12 +110,9 @@ class CfbReaderTest {
for (int i = 0; i < specs.length; i++) {
Spec s = specs[i];
boolean smallOne = s.data().length < 4096;
int idx = -1;
for (int k = 0; k < (smallOne ? small : big).size(); k++) {
if ((smallOne ? small : big).get(k) == s) {
idx = k;
}
}
// Spec — record с byte[]: equals сравнивает массив по ссылке, indexOf
// находит ровно тот же экземпляр, что добавлялся в small/big.
int idx = (smallOne ? small : big).indexOf(s);
dirEntry(file, 1, 1 + i, s.name(), 2,
smallOne ? miniHead[idx] : bigHead[idx], s.data().length);
}
@@ -377,21 +377,21 @@ class DocToDocxFormattingTest {
}
private static byte[] cfb(boolean use1Table, boolean withTable) throws IOException {
POIFSFileSystem fs = new POIFSFileSystem();
byte[] wd = wordDocument();
if (!use1Table) {
wd[11] &= ~0x02; // fWhichTblStm (бит 9 u16) → 0Table
try (POIFSFileSystem fs = new POIFSFileSystem()) {
byte[] wd = wordDocument();
if (!use1Table) {
wd[11] &= ~0x02; // fWhichTblStm (бит 9 u16) → 0Table
}
fs.getRoot().createDocument("WordDocument", new ByteArrayInputStream(wd));
if (withTable) {
fs.getRoot().createDocument(use1Table ? "1Table" : "0Table",
new ByteArrayInputStream(tableStream()));
}
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
ByteArrayOutputStream out = new ByteArrayOutputStream();
fs.writeFilesystem(out);
return out.toByteArray();
}
fs.getRoot().createDocument("WordDocument", new ByteArrayInputStream(wd));
if (withTable) {
fs.getRoot().createDocument(use1Table ? "1Table" : "0Table",
new ByteArrayInputStream(tableStream()));
}
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
ByteArrayOutputStream out = new ByteArrayOutputStream();
fs.writeFilesystem(out);
fs.close();
return out.toByteArray();
}
private static String documentXml(byte[] doc) throws IOException {