PMD codestyle на verify + исправление всех предупреждений #13

Merged
pjandro merged 2 commits from chore/pmd-codestyle into main 2026-10-20 01:56:22 +03:00
24 changed files with 87 additions and 107 deletions
Showing only changes of commit 5f0cabd8e2 - Show all commits
@@ -24,7 +24,7 @@ import ru.pjandro.wordpdf.ValidationException;
@RestControllerAdvice
final class ApiExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);
private static final Logger LOG = LoggerFactory.getLogger(ApiExceptionHandler.class);
/** Тело ответа ошибки; Jackson сериализует record как есть. */
record ApiError(String error) {
@@ -99,7 +99,7 @@ final class ApiExceptionHandler {
/** Прочее — внутренняя ошибка; подробность только в лог, не в ответ. */
@ExceptionHandler(Exception.class)
ResponseEntity<ApiError> unexpected(Exception e) {
log.error("Необработанное исключение в API", e);
LOG.error("Необработанное исключение в API", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(new ApiError("Внутренняя ошибка конвертации"));
}
@@ -75,7 +75,7 @@ class ApiKeyFilterTest {
.andExpect(status().isOk())
.andReturn();
byte[] pdf = result.getResponse().getContentAsByteArray();
assertTrue(new String(pdf, 0, 4, StandardCharsets.US_ASCII).equals("%PDF"),
assertTrue("%PDF".equals(new String(pdf, 0, 4, StandardCharsets.US_ASCII)),
"ответ не PDF");
}
@@ -115,7 +115,7 @@ class ConvertControllerTest {
org.hamcrest.Matchers.containsString("filename*=UTF-8''ru-plain.pdf")))
.andReturn();
byte[] pdf = result.getResponse().getContentAsByteArray();
assertTrue(new String(pdf, 0, 4, StandardCharsets.US_ASCII).equals("%PDF"),
assertTrue("%PDF".equals(new String(pdf, 0, 4, StandardCharsets.US_ASCII)),
"тело не начинается с %PDF");
String text = norm(pdfText(pdf));
assertTrue(text.contains("Привет, мир!"), "нет «Привет, мир!»: " + text);
@@ -308,7 +308,7 @@ class ConvertControllerTest {
.andExpect(status().isOk())
.andReturn();
byte[] pdf = r.getResponse().getContentAsByteArray();
assertTrue(new String(pdf, 0, 4, StandardCharsets.US_ASCII).equals("%PDF"),
assertTrue("%PDF".equals(new String(pdf, 0, 4, StandardCharsets.US_ASCII)),
"ответ не PDF");
} catch (Exception e) {
throw new IllegalStateException(e);
@@ -12,7 +12,6 @@ import org.springframework.test.web.servlet.MockMvc;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -130,7 +130,7 @@ public final class WordPdfValidator {
ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) {
String n = entry.getName();
if (n.equals("docProps/app.xml") || n.equals("word/document.xml")
if ("docProps/app.xml".equals(n) || "word/document.xml".equals(n)
|| isHeaderFooterPart(n)) {
parts.put(n, zip.readAllBytes());
if (isHeaderFooterPart(n)) {
@@ -218,7 +218,7 @@ public final class WordPdfValidator {
XMLStreamReader xr = newSecureReader().createXMLStreamReader(in);
while (xr.hasNext()) {
if (xr.next() == XMLStreamReader.START_ELEMENT
&& xr.getLocalName().equals("Pages")) {
&& "Pages".equals(xr.getLocalName())) {
String text = xr.getElementText().trim();
return Math.max(0, Integer.parseInt(text));
}
@@ -344,7 +344,7 @@ public final class WordPdfValidator {
XMLStreamReader xr = newSecureReader().createXMLStreamReader(in);
while (xr.hasNext()) {
if (xr.next() == XMLStreamReader.START_ELEMENT
&& xr.getLocalName().equals("br") && isPageBreak(xr)) {
&& "br".equals(xr.getLocalName()) && isPageBreak(xr)) {
count++;
}
}
@@ -384,7 +384,7 @@ public final class WordPdfValidator {
private static boolean truthy(XMLStreamReader xr) {
String v = attrLocal(xr, "val");
return v == null || v.equals("true") || v.equals("1") || v.equals("on");
return v == null || "true".equals(v) || "1".equals(v) || "on".equals(v);
}
private static boolean inside(Deque<String> path, String ancestor) {
@@ -54,7 +54,7 @@ public final class BundledFonts {
/** Описание одного файла: имя в jar, ключ семейства, начертание.
* Package-private: доступ для теста. */
static record Entry(String file, String family, String variant) {
record Entry(String file, String family, String variant) {
}
/**
@@ -222,7 +222,7 @@ public final class BundledFonts {
* FO может запросить любой из них (фолбэк docx4j по покрытию глифов),
* а FOP знает только задекларированные.
*/
public static java.util.List<String> families() {
public static List<String> families() {
return ENTRIES.stream().map(Entry::family).distinct().toList();
}
@@ -79,7 +79,7 @@ public final class DocxOnOffNormalizer {
m.reset();
StringBuilder sb = new StringBuilder(xml.length());
while (m.find()) {
String value = m.group(2).equalsIgnoreCase("on") ? "true" : "false";
String value = "on".equalsIgnoreCase(m.group(2)) ? "true" : "false";
m.appendReplacement(sb, Matcher.quoteReplacement(
"w:val=" + m.group(1) + value + m.group(1)));
}
@@ -98,7 +98,7 @@ public final class StrictOoxmlNormalizer {
// в numbering.xml w:start — элемент стартового значения
// счётчика, его не переименовываем
String fixed = rewrite(new String(data, StandardCharsets.UTF_8),
!name.equals("word/numbering.xml"));
!"word/numbering.xml".equals(name));
if (fixed != null) {
changed = true;
data = fixed.getBytes(StandardCharsets.UTF_8);
@@ -225,7 +225,7 @@ public final class StrictOoxmlNormalizer {
m.reset();
StringBuilder sb = new StringBuilder(xml.length());
while (m.find()) {
String value = m.group(2).equals("start") ? "left" : "right";
String value = "start".equals(m.group(2)) ? "left" : "right";
m.appendReplacement(sb,
Matcher.quoteReplacement(m.group(1) + value + "\""));
}
@@ -43,8 +43,8 @@ final class CartesianPainter {
// 1. Поля под подписи осей
double catGutter = 0;
for (String c : cats) {
catGutter = Math.max(catGutter, DrawMlText.textHeight(catStyle, g.getFontRenderContext()));
if (!cats.isEmpty()) {
catGutter = DrawMlText.textHeight(catStyle, g.getFontRenderContext());
}
catGutter += 6;
@@ -86,8 +86,7 @@ final class CartesianPainter {
if (valAxis.gridlines && !valAxis.deleted) {
g.setColor(valAxis.gridColor);
g.setStroke(new BasicStroke(0.6f));
int i = 0;
for (double v = lo; v <= hi + unit / 2; v += unit, i++) {
for (double v = lo; v <= hi + unit / 2; v += unit) {
double t = (v - lo) / (hi - lo);
if (horizontal) {
double x = plot.getX() + t * plot.getWidth();
@@ -259,7 +258,6 @@ final class CartesianPainter {
private static void drawAreas(Graphics2D g, ChartSpec spec, Rectangle2D plot,
List<Color> palette, double lo, double hi, int nCat,
boolean horizontal) {
double baseline = horizontal ? plot.getX() : plot.getY() + plot.getHeight();
for (int si = 0; si < spec.series.size(); si++) {
ChartSpec.Series s = spec.series.get(si);
Color c = s.fill != null ? s.fill : s.fillAt(si, palette);
@@ -277,18 +275,16 @@ final class CartesianPainter {
continue;
}
Path2D p = new Path2D.Double();
p.moveTo(toX(along.get(0), cross.get(0), baseline, horizontal),
toY(along.get(0), cross.get(0), baseline, horizontal));
p.moveTo(toX(along.get(0), cross.get(0), horizontal),
toY(along.get(0), cross.get(0), horizontal));
for (int i = 0; i < along.size(); i++) {
p.lineTo(toX(along.get(i), cross.get(i), baseline, horizontal),
toY(along.get(i), cross.get(i), baseline, horizontal));
p.lineTo(toX(along.get(i), cross.get(i), horizontal),
toY(along.get(i), cross.get(i), horizontal));
}
p.lineTo(toX(along.get(along.size() - 1), cross.get(cross.size() - 1),
baseline, horizontal),
toY(along.get(along.size() - 1), cross.get(cross.size() - 1),
baseline, horizontal));
p.lineTo(toX(along.get(0), cross.get(0), baseline, horizontal),
toY(along.get(0), cross.get(0), baseline, horizontal));
p.lineTo(toX(along.get(along.size() - 1), cross.get(cross.size() - 1), horizontal),
toY(along.get(along.size() - 1), cross.get(cross.size() - 1), horizontal));
p.lineTo(toX(along.get(0), cross.get(0), horizontal),
toY(along.get(0), cross.get(0), horizontal));
p.closePath();
g.setColor(DrawMlColor.withAlpha(c, 0.55));
g.fill(p);
@@ -299,11 +295,11 @@ final class CartesianPainter {
}
/** (вдоль категории, вдоль значения) -> экранные координаты. */
private static double toX(double along, double cross, double baseline, boolean horizontal) {
private static double toX(double along, double cross, boolean horizontal) {
return horizontal ? cross : along;
}
private static double toY(double along, double cross, double baseline, boolean horizontal) {
private static double toY(double along, double cross, boolean horizontal) {
return horizontal ? along : cross;
}
@@ -179,8 +179,6 @@ final class ChartRenderer {
}
}
case SURFACE3D -> {
List<Double> vals = spec.series.isEmpty()
? List.of() : spec.series.get(0).values;
double min = Double.MAX_VALUE;
double max = -Double.MAX_VALUE;
for (ChartSpec.Series s : spec.series) {
@@ -330,7 +328,7 @@ final class ChartRenderer {
// (так делает Word) — иначе surface3D теряет нижнюю полосу и легенда
// съезжает с «0-1 … 4-5» на «1-2 … 4-5».
double lo = axis != null && axis.min != null ? axis.min
: (dataMin >= 0 ? 0 : Math.floor(dataMin / unit) * unit);
: dataMin >= 0 ? 0 : Math.floor(dataMin / unit) * unit;
double hi;
if (axis != null && axis.max != null) {
hi = axis.max;
@@ -346,7 +344,7 @@ final class ChartRenderer {
/** Формат числа для подписей оси ("General" -> без лишних нулей). */
static String formatValue(double v, String fmt) {
if (fmt != null && !fmt.equalsIgnoreCase("General")) {
if (fmt != null && !"General".equalsIgnoreCase(fmt)) {
if (fmt.contains("0.00")) {
return String.format(java.util.Locale.ROOT, "%.2f", v);
}
@@ -122,10 +122,6 @@ final class ChartSpec {
Color chartBorder = new Color(0xBF, 0xBF, 0xBF);
double chartBorderWidth = 0.75;
/** package-private: тестам нужен пустой spec без CTChartSpace. */
ChartSpec() {
}
/** Цвета акцента темы — базовая палитра рядов (как в Word). */
static List<Color> palette(DrawMlColor colors) {
List<Color> p = new ArrayList<>();
@@ -228,25 +224,24 @@ final class ChartSpec {
if (group instanceof CTPie3DChart g) {
spec.type = Type.PIE3D;
for (CTPieSer s : g.getSer()) {
spec.series.add(readPieSer(s, colors, palette));
spec.series.add(readPieSer(s, colors));
}
} else if (group instanceof CTPieChart g) {
spec.type = Type.PIE;
for (CTPieSer s : g.getSer()) {
spec.series.add(readPieSer(s, colors, palette));
spec.series.add(readPieSer(s, colors));
}
} else if (group instanceof CTDoughnutChart g) {
spec.type = Type.DOUGHNUT;
for (CTPieSer s : g.getSer()) {
spec.series.add(readPieSer(s, colors, palette));
spec.series.add(readPieSer(s, colors));
}
} else if (group instanceof CTLineChart g) {
spec.type = Type.LINE;
for (CTLineSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors, palette);
readLineProps(s.getSpPr(), ser, colors, palette,
spec.series.size());
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors);
readLineProps(s.getSpPr(), ser, colors);
CTMarker m = s.getMarker();
if (m != null) {
ser.marker = m.getSymbol() == null
@@ -260,11 +255,11 @@ final class ChartSpec {
} else if (group instanceof CTBarChart g) {
boolean horizontal = g.getBarDir() != null
&& g.getBarDir().getVal() != null
&& g.getBarDir().getVal().value().equalsIgnoreCase("bar");
&& "bar".equalsIgnoreCase(g.getBarDir().getVal().value());
spec.type = horizontal ? Type.BAR_HORIZONTAL : Type.BAR;
for (CTBarSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors, palette);
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors);
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
}
@@ -274,11 +269,11 @@ final class ChartSpec {
spec.type = Type.AREA;
for (org.docx4j.dml.chart.CTAreaSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors, palette);
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors);
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
}
readLineProps(s.getSpPr(), ser, colors, palette, spec.series.size());
readLineProps(s.getSpPr(), ser, colors);
spec.series.add(ser);
}
} else if (group instanceof CTSurface3DChart g) {
@@ -286,7 +281,7 @@ final class ChartSpec {
spec.wireframe = isTrue(g.getWireframe());
for (CTSurfaceSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), List.of(), ser, colors, palette);
readCommon(s.getTx(), s.getCat(), s.getVal(), List.of(), ser, colors);
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
}
@@ -305,9 +300,9 @@ final class ChartSpec {
}
}
private static Series readPieSer(CTPieSer s, DrawMlColor colors, List<Color> palette) {
private static Series readPieSer(CTPieSer s, DrawMlColor colors) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors, palette);
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors);
if (s.getSpPr() != null) {
if (s.getSpPr().getSolidFill() != null) {
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
@@ -328,8 +323,7 @@ final class ChartSpec {
/** Общее для всех типов: имя, категории, значения, переопределения точек. */
private static void readCommon(CTSerTx tx, CTAxDataSource cat, CTNumDataSource val,
List<CTDPt> dPts, Series ser, DrawMlColor colors,
List<Color> palette) {
List<CTDPt> dPts, Series ser, DrawMlColor colors) {
ser.name = seriesName(tx);
ser.categories.addAll(categoryNames(cat));
if (val != null) {
@@ -362,8 +356,7 @@ final class ChartSpec {
}
/** a:ln ряда (цвет и толщина линии графика). */
private static void readLineProps(CTShapeProperties sp, Series ser, DrawMlColor colors,
List<Color> palette, int seriesIndex) {
private static void readLineProps(CTShapeProperties sp, Series ser, DrawMlColor colors) {
if (sp == null) {
return;
}
@@ -112,9 +112,9 @@ final class DrawMlColor {
}
String n = name.toLowerCase(Locale.ROOT);
// Word: bg1/tx1 — псевдонимы lt1/dk1
if (n.equals("bg1")) {
if ("bg1".equals(n)) {
n = "lt1";
} else if (n.equals("tx1")) {
} else if ("tx1".equals(n)) {
n = "dk1";
}
Color c = scheme.get(n);
@@ -171,7 +171,7 @@ final class DrawMlColor {
}
case "hueMod" -> {
hsl = RgbHsl.toHsl(toRgb(hsl));
hsl[0] = (hsl[0] * p) % 360.0;
hsl[0] = hsl[0] * p % 360.0;
hslDirty = true;
}
case "hueOff" -> {
@@ -260,9 +260,9 @@ final class DrawMlColor {
if (c.getScrgbClr() != null) {
CTScRgbColor s = c.getScrgbClr();
return new Color(
clamp255((int) Math.round(s.getR() * 255)),
clamp255((int) Math.round(s.getG() * 255)),
clamp255((int) Math.round(s.getB() * 255)));
clamp255(Math.round(s.getR() * 255)),
clamp255(Math.round(s.getG() * 255)),
clamp255(Math.round(s.getB() * 255)));
}
if (c.getHslClr() != null) {
CTHslColor h = c.getHslClr();
@@ -12,7 +12,6 @@ import ru.pjandro.wordpdf.fonts.BundledFonts;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
@@ -214,7 +213,7 @@ final class DrawMlText {
continue;
}
StringBuilder cur = new StringBuilder();
double curWidth = 0;
double curWidth;
for (String word : hard.split(" ")) {
if (word.isEmpty()) {
continue;
@@ -224,7 +223,6 @@ final class DrawMlText {
if (w <= limit || cur.length() == 0) {
cur.setLength(0);
cur.append(candidate);
curWidth = w;
continue;
}
out.add(cur.toString());
@@ -251,13 +249,13 @@ final class DrawMlText {
/** Ширина строки в тех же единицах, что и размер шрифта. */
static double textWidth(String text, Style style, FontRenderContext frc) {
return new java.awt.font.TextLayout(text, fontFor(style), frc).getAdvance();
return new TextLayout(text, fontFor(style), frc).getAdvance();
}
/** Высота строки (ascent+descent+leading) для стиля. */
static double textHeight(Style style, FontRenderContext frc) {
Font f = fontFor(style);
java.awt.font.TextLayout tl = new java.awt.font.TextLayout("Xpg", f, frc);
TextLayout tl = new TextLayout("Xpg", f, frc);
return tl.getAscent() + tl.getDescent() + tl.getLeading();
}
}
@@ -63,7 +63,7 @@ import java.util.Set;
*/
public final class DrawingPreRenderer {
private static final Logger log = LoggerFactory.getLogger(DrawingPreRenderer.class);
private static final Logger LOG = LoggerFactory.getLogger(DrawingPreRenderer.class);
private static final String CHART_ELEMENT =
"{http://schemas.openxmlformats.org/drawingml/2006/chart}chart";
@@ -185,7 +185,7 @@ public final class DrawingPreRenderer {
continue;
}
if (cx <= 0 || cy <= 0) {
log.warn("drawing без wp:extent — оставлен как есть");
LOG.warn("drawing без wp:extent — оставлен как есть");
continue;
}
GraphicData gd = graphic.getGraphicData();
@@ -208,7 +208,7 @@ public final class DrawingPreRenderer {
}
continue; // настройка выключена — drawing остаётся в docx как есть
}
img = renderChart(part, (CTRelId) el.getValue(), pkg, colors, cx, cy);
img = renderChart(part, (CTRelId) el.getValue(), colors, cx, cy);
label = "график";
} else if (DIAGRAM_ELEMENT.equals(name)) {
if (!options.renderSmartArt()) {
@@ -217,13 +217,13 @@ public final class DrawingPreRenderer {
}
continue;
}
img = renderDiagram(part, (CTRelIds) el.getValue(), pkg, colors, cx, cy);
img = renderDiagram(part, (CTRelIds) el.getValue(), colors, cx, cy);
label = "SmartArt";
}
}
if (img == null) {
if (label != null) {
log.warn("не удалось отрендерить {} — объект удалён из документа", label);
LOG.warn("не удалось отрендерить {} — объект удалён из документа", label);
gd.getAny().clear();
}
continue;
@@ -232,28 +232,28 @@ public final class DrawingPreRenderer {
}
}
private static BufferedImage renderChart(Part part, CTRelId ref, WordprocessingMLPackage pkg,
private static BufferedImage renderChart(Part part, CTRelId ref,
DrawMlColor colors, long cx, long cy) {
Part target = resolve(part, ref.getId());
if (!(target instanceof JaxbXmlPart<?> jp) || !(jp.getJaxbElement() instanceof CTChartSpace space)) {
log.warn("chart-часть не найдена по r:id={}", ref.getId());
LOG.warn("chart-часть не найдена по r:id={}", ref.getId());
return null;
}
try {
ChartSpec spec = ChartSpec.parse(space, colors);
return ChartRenderer.render(spec, cx / 12700.0, cy / 12700.0, colors);
} catch (RuntimeException e) {
log.warn("рендер графика r:id={} упал: {}", ref.getId(), e.toString());
LOG.warn("рендер графика r:id={} упал: {}", ref.getId(), e.toString());
return null;
}
}
private static BufferedImage renderDiagram(Part part, CTRelIds refs, WordprocessingMLPackage pkg,
private static BufferedImage renderDiagram(Part part, CTRelIds refs,
DrawMlColor colors, long cx, long cy) {
Part drawingPart = diagramDrawingPart(part);
if (!(drawingPart instanceof JaxbXmlPart<?> jp)
|| !(jp.getJaxbElement() instanceof CTDrawing drawing)) {
log.warn("dsp:drawing (SmartArt) не найден — схема пропущена");
LOG.warn("dsp:drawing (SmartArt) не найден — схема пропущена");
return null;
}
CTDataModel data = null;
@@ -264,7 +264,7 @@ public final class DrawingPreRenderer {
try {
return SmartArtRenderer.render(drawing, data, colors, cx / 12700.0, cy / 12700.0);
} catch (RuntimeException e) {
log.warn("рендер SmartArt упал: {}", e.toString());
LOG.warn("рендер SmartArt упал: {}", e.toString());
return null;
}
}
@@ -306,19 +306,19 @@ public final class DrawingPreRenderer {
ImageIO.write(img, "png", bos);
png = bos.toByteArray();
} catch (Exception e) {
log.warn("PNG не собран: {}", e.toString());
LOG.warn("PNG не собран: {}", e.toString());
return;
}
BinaryPartAbstractImage imagePart;
try {
imagePart = BinaryPartAbstractImage.createImagePart(pkg, part, png);
} catch (Exception e) {
log.warn("ImagePart не создан: {}", e.toString());
LOG.warn("ImagePart не создан: {}", e.toString());
return;
}
String relId = relIdFor(part, imagePart);
if (relId == null) {
log.warn("r:id для ImagePart {} не найден", imagePart.getPartName());
LOG.warn("r:id для ImagePart {} не найден", imagePart.getPartName());
return;
}
@@ -84,7 +84,7 @@ final class PiePainter {
double sweep = 360.0 * v / total;
Color fill = s.fillAt(i, palette);
Color outline = s.outlineNoFill ? null
: (s.outlineColor != null ? s.outlineColor : Color.WHITE);
: s.outlineColor != null ? s.outlineColor : Color.WHITE;
double ow = s.outlineWidth > 0 ? s.outlineWidth : 1.0;
slices.add(new Slice(angle, sweep, fill, outline, ow));
angle += sweep;
@@ -48,13 +48,13 @@ final class PrstGeomShapes {
return new Shape(new Area(new Ellipse2D.Double(x, y, w, h)), null);
}
case "gear6", "gear9" -> {
int teeth = p.equals("gear6") ? 6 : 9;
int teeth = "gear6".equals(p) ? 6 : 9;
return gear(x, y, w, h, teeth);
}
case "circularArrow", "leftCircularArrow", "rightCircularArrow",
"curvedRightArrow", "curvedLeftArrow" -> {
return circularArrow(x, y, w, h, adj,
p.equals("leftCircularArrow") || p.equals("curvedLeftArrow"));
"leftCircularArrow".equals(p) || "curvedLeftArrow".equals(p));
}
default -> {
return new Shape(new Area(new Rectangle2D.Double(x, y, w, h)), null);
@@ -126,8 +126,8 @@ final class PrstGeomShapes {
a1 += 2 * Math.PI;
}
Path2D path = new Path2D.Double();
arcSegment(path, cx, cy, rOuter, a0, a1, true);
arcSegment(path, cx, cy, rInner, a1, a0, false);
arcSegment(path, cx, cy, rOuter, a0, a1);
arcSegment(path, cx, cy, rInner, a1, a0);
path.closePath();
Area area = new Area(path);
@@ -152,7 +152,7 @@ final class PrstGeomShapes {
}
private static void arcSegment(Path2D path, double cx, double cy, double r,
double a0, double a1, boolean forward) {
double a0, double a1) {
int steps = Math.max(2, (int) (Math.abs(a1 - a0) / Math.toRadians(4)));
for (int i = 0; i <= steps; i++) {
double t = a0 + (a1 - a0) * i / steps;
@@ -38,7 +38,7 @@ final class RgbHsl {
}
static Color fromHsl(double h, double s, double l) {
double hh = (((h % 360) + 360) % 360) / 360.0;
double hh = (h % 360 + 360) % 360 / 360.0;
double ss = Math.max(0, Math.min(1, s));
double ll = Math.max(0, Math.min(1, l));
double r, g, b;
@@ -8,12 +8,10 @@ import org.docx4j.dml.CTPositiveSize2D;
import org.docx4j.dml.CTPresetGeometry2D;
import org.docx4j.dml.CTShapeProperties;
import org.docx4j.dml.CTShapeStyle;
import org.docx4j.dml.CTTextBody;
import org.docx4j.dml.CTTransform2D;
import org.docx4j.dml.diagram.CTCxn;
import org.docx4j.dml.diagram.CTDataModel;
import org.docx4j.dml.diagram.STCxnType;
import org.docx4j.dml.diagram.CTElemPropSet;
import org.docx4j.dml.diagram.CTPt;
import org.docx4j.dml.diagram2008.CTDrawing;
import org.docx4j.dml.diagram2008.CTShape;
@@ -187,7 +187,7 @@ final class Surface3dPainter {
Fit fit = new Fit(scale, scale, offX, offY);
// 3. Пол, дальняя стенка и их сетки — под поверхностью
drawFloor(g, spec, floor, valueAnchors, nCat, nSer, lo, hi, unit, span,
drawFloor(g, spec, floor, nCat, nSer, lo, hi, unit, span,
rotX, rotY, depthScale, heightScale, persp, fit);
// 4. Грани: два треугольника на ячейку, каждый разрезан по
@@ -379,7 +379,7 @@ final class Surface3dPainter {
/** Сетка пола и дальней стенки; рисуется до поверхности. */
private static void drawFloor(Graphics2D g, ChartSpec spec, Node[] floor,
List<Node> valueAnchors, int nCat, int nSer,
int nCat, int nSer,
double lo, double hi, double unit, double span,
double rotX, double rotY, double depthScale,
double heightScale, double persp,
@@ -193,7 +193,7 @@ public final class SampleDocxGenerator {
// Размеры в EMU (1 px @ 96 dpi = 9525 EMU)
XWPFParagraph imgPara = doc.createParagraph();
XWPFRun imgRun = imgPara.createRun();
imgRun.addPicture(new java.io.ByteArrayInputStream(bos.toByteArray()),
imgRun.addPicture(new ByteArrayInputStream(bos.toByteArray()),
PictureType.PNG, "test-image.png",
120 * 9525, 60 * 9525);
@@ -392,7 +392,7 @@ public final class SampleDocxGenerator {
java.util.zip.ZipEntry e;
while ((e = zin.getNextEntry()) != null) {
byte[] data = zin.readAllBytes();
if (e.getName().equals("word/document.xml")) {
if ("word/document.xml".equals(e.getName())) {
String xml = new String(data, java.nio.charset.StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder(xml.length() + 4096);
int i = 0;
@@ -456,7 +456,7 @@ class WordPdfConverterTest {
*/
@Test
void inputNotAZip_rejectedBeforeRender() {
byte[] junk = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
byte[] junk = {1, 2, 3, 4, 5, 6, 7, 8};
ValidationException ex = assertThrows(ValidationException.class, () ->
WordPdfConverter.convert(junk, "junk"));
assertTrue(ex.getMessage().contains("не zip-архив"),
@@ -164,12 +164,12 @@ class WordPdfValidatorTest {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (java.util.zip.ZipInputStream zin = new java.util.zip.ZipInputStream(
new java.io.ByteArrayInputStream(base));
java.util.zip.ZipOutputStream zout = new java.util.zip.ZipOutputStream(out)) {
java.util.zip.ZipEntry e;
ZipOutputStream zout = new ZipOutputStream(out)) {
ZipEntry e;
while ((e = zin.getNextEntry()) != null) {
byte[] data = zin.readAllBytes();
if (e.getName().equals("word/document.xml")) {
String xml = new String(data, java.nio.charset.StandardCharsets.UTF_8);
if ("word/document.xml".equals(e.getName())) {
String xml = new String(data, StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
for (String t : types) {
sb.append("<w:sectPr><w:type w:val=\"").append(t)
@@ -187,9 +187,9 @@ class WordPdfValidatorTest {
xml = xml.substring(0, at) + "<w:body>" + sb + "</w:body>"
+ xml.substring(at + "<w:body/>".length());
}
data = xml.getBytes(java.nio.charset.StandardCharsets.UTF_8);
data = xml.getBytes(StandardCharsets.UTF_8);
}
zout.putNextEntry(new java.util.zip.ZipEntry(e.getName()));
zout.putNextEntry(new ZipEntry(e.getName()));
zout.write(data);
zout.closeEntry();
}
@@ -238,7 +238,7 @@ class WordPdfValidatorTest {
p.createRun().setText("t" + i);
p.createRun().addBreak(BreakType.PAGE);
}
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
doc.write(bos);
bytes = bos.toByteArray();
}
@@ -277,7 +277,7 @@ class WordPdfValidatorTest {
@Test
void validate_notAZip() {
byte[] junk = new byte[]{1, 2, 3, 4, 5};
byte[] junk = {1, 2, 3, 4, 5};
ValidationException ex = assertThrows(ValidationException.class,
() -> WordPdfValidator.validate(junk, ConvertOptions.defaults()));
assertTrue(ex.getMessage().contains("не zip-архив"),
@@ -92,7 +92,7 @@ class BundledFontsTest {
// populateFontMappings вызывается при setFontMapper; проверяем
// итоговое состояние через публичный get()
java.util.Set<String> names = new java.util.HashSet<>(List.of(
Set<String> names = new java.util.HashSet<>(List.of(
"Calibri", "Times New Roman", "Arial", "Cousine", "UnknownExoticFont"));
// wmlFonts не может быть null (super обращается к getFont()),
// поэтому — пустой объект (как у документа без fontTable)
@@ -24,8 +24,6 @@ class GlyphCoverageNormalizerTest {
private static final String ROMAN = "\u2181";
/** Знак, которого нет ни в одном бандл-шрифте. */
private static final String NOWHERE = "\u2188";
/** Обычная кириллица — есть в Tinos. */
private static final String CYRILLIC = "ы";
@BeforeAll
static void initFonts() {