Слияние docx4j 17.3.5 в wordpdf-core и форк FO-рендерера 2.11-docx4j.8 в реактор
PR checks / web (pull_request) Successful in 38s
PR checks / java (pull_request) Successful in 18m31s

- wordpdf-core/src/main/java впитаны исходники docx4j-core, -export-fo,
  -chart-render, -JAXB-ReferenceImpl, -copy, -generated-objects (17.3.5) +
  сгенерированная XJC JAXB-модель; ресурсы — тем же путём; артефакты группы
  org.docx4j из внешних репозиториев больше не подключаются
- vendor/fop: форк docx4j-fo-renderer 2.11-docx4j.8 (util/events/core/fop)
  собирается в реакторе вместо jar из Nexus
- docx2fo.xslt перевендорен со стилем 17.3.5, оба AUDIT-FIX-патча перенесены;
  дрейф-гейт vendoredXsltTracksJarCopy зелёный
- upstream-тесты docx4j перенесены в src/test/java/org (658 классов, вне гейта);
  execution upstream-docx4j-tests в профиле upstream-tests (./mise.sh run
  upstream-tests, в pr.yml non-blocking шаг): 3470 тестов, 3457 зелёных,
  13 красных — категории окружения/калибровки хоста и следствий слияния
  classpath задокументированы в docs/agent/testing.md
- surefire: провайдер SLF4J фиксируется коротким slf4j.provider по execution;
  перенесён upstream logback.xml (root=DEBUG без конфига ломает visitor-экспорт
  VML); upstream-форки пинят JDK JAXP-фабрики; PMD/JaCoCo исключают org/**
- wordpdf-app: без изменений кода (зависит от слитого ядра); тесты 44/44
- документация синхронизирована (AGENTS.md, README, docs/agent/*), mise task
  upstream-tests
This commit is contained in:
Pjandro
2026-11-08 02:54:49 +00:00
parent f41ac54072
commit 8529b6877b
10191 changed files with 1694473 additions and 75 deletions
+368 -14
View File
@@ -12,24 +12,153 @@
<artifactId>wordpdf-core</artifactId>
<name>wordpdf-core</name>
<description>Библиотека: конвертация docx в PDF (docx4j + FOP, шрифты внутри jar)</description>
<description>Библиотека: конвертация docx в PDF (docx4j 17.3.5 слит в модуль, FOP-форк из vendor/fop, шрифты внутри jar)</description>
<dependencies>
<!-- docx4j: чтение/запись docx, маппинг шрифтов -->
<!-- ============ зависимости слитого docx4j 17.3.5 (org.docx4j.* в src/main/java) ============
Единственные артефакты группы org.docx4j на classpath — форк FO-рендерера
(reactor-модуль vendor/fop); docx4j-core/export-fo/chart-render из Central НЕ
используются. Версии — в корневом dependencyManagement (upstream 17.3.5). -->
<!-- JAXB: API + реализация ReferenceImpl (service-файл jaxb-runtime), txw2 -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>txw2</artifactId>
</dependency>
<!-- рантайм XJC-плагинов модели (-Xcopy: org.docx4j.copy.* слиты сюда же) -->
<dependency>
<groupId>org.jvnet.jaxb</groupId>
<artifactId>jaxb-plugins-runtime</artifactId>
</dependency>
<!-- перепакованные схемы SVG/XSL-FO -->
<dependency>
<groupId>org.plutext</groupId>
<artifactId>jaxb-svg11</artifactId>
</dependency>
<dependency>
<groupId>org.plutext</groupId>
<artifactId>jaxb-xslfo</artifactId>
</dependency>
<dependency>
<groupId>net.engio</groupId>
<artifactId>mbassador</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>SparseBitSet</artifactId>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>xmlgraphics-commons</artifactId>
</dependency>
<!-- перепакованный Xalan для XPathEnhancer -->
<dependency>
<groupId>org.docx4j.org.apache</groupId>
<artifactId>xalan-interpretive</artifactId>
</dependency>
<dependency>
<groupId>org.docx4j.org.apache</groupId>
<artifactId>xalan-serializer</artifactId>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-runtime</artifactId>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>stringtemplate</artifactId>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
</dependency>
<dependency>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_annotations</artifactId>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.qdox</groupId>
<artifactId>qdox</artifactId>
</dependency>
<!-- Batik: SVG/OMML (jeuclid) и chart-render -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-anim</artifactId>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-awt-util</artifactId>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-dom</artifactId>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-extension</artifactId>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-gvt</artifactId>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-svggen</artifactId>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-transcoder</artifactId>
</dependency>
<dependency>
<groupId>de.rototor.jeuclid</groupId>
<artifactId>jeuclid-fop</artifactId>
</dependency>
<!-- форк FO-рендерера: собирается reactor-модулем vendor/fop (2.11-docx4j.8) -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-core</artifactId>
<artifactId>docx4j-fo-renderer</artifactId>
</dependency>
<!-- Реализация JAXB для docx4j -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
</dependency>
<!-- Пайплайн экспорта: docx -> XSL-FO -> Apache FOP -> PDF -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<artifactId>docx4j-fo-renderer-events</artifactId>
</dependency>
<!-- Простой логгер в консоль (slf4j). Обязателен: без него docx4j
пишет предупреждение прямо в выходной PDF. -->
<dependency>
@@ -50,8 +179,8 @@
<artifactId>jcl-over-slf4j</artifactId>
</dependency>
<!-- Используется DependencyGuard (проверка совместимости classpath);
транзитивно приходит от docx4j-core, объявлена явно как контракт
интеграции — потребитель видит её в своём дереве зависимостей -->
объявлена явно как контракт интеграции — потребитель видит её в
своём дереве зависимостей -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
@@ -76,12 +205,112 @@
<artifactId>poi-ooxml</artifactId>
<scope>test</scope>
</dependency>
<!-- ===== upstream-набор тестов docx4j (JUnit 4 через vintage) ===== -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<!-- тесты upstream работают против logback-бэкенда (LoggerContext/ListAppender);
в гейт по умолчанию не попадает: default-test фиксирует slf4j-simple через
-Dslf4j.provider -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>test</scope>
</dependency>
<!-- Saxon XPath (тесты mc-preprocessor/XSLT), tika (детект MIME),
xerces (DOM-каноникализация), fop-hyph (флекс-расстановка) -->
<dependency>
<groupId>net.sf.saxon</groupId>
<artifactId>Saxon-HE</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sf.offo</groupId>
<artifactId>fop-hyph</artifactId>
<scope>test</scope>
</dependency>
<!-- main-код docx4j-markdown перенесён в test-дерево (нужен тестам core-tests) -->
<dependency>
<groupId>org.commonmark</groupId>
<artifactId>commonmark</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.commonmark</groupId>
<artifactId>commonmark-ext-gfm-tables</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.commonmark</groupId>
<artifactId>commonmark-ext-gfm-strikethrough</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.commonmark</groupId>
<artifactId>commonmark-ext-task-list-items</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.commonmark</groupId>
<artifactId>commonmark-ext-footnotes</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.commonmark</groupId>
<artifactId>commonmark-ext-yaml-front-matter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- XSLT-части src/main/java: стилист export-fo (org/docx4j/convert/out/fo/docx2fo.xslt)
и xml-части лежат в дереве исходников — без этой записи они не попадут в jar,
и гейт vendoredXsltTracksJarCopy упадёт. -->
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<!-- фильтруется вторым ресурсом: ${docx4j.version} = 17.3.5 -->
<exclude>docx4j_version.properties</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>docx4j_version.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xslt</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<!-- Тестовый jar с готовыми .docx из src/test/resources/samples:
используется тестами wordpdf-app. -->
используется тестами wordpdf-app. В jar попадают только фикстуры
проекта (samples/, geom/) и тестовые классы ru.pjandro — перенесённые
upstream-тесты (org/**) и их 60 МБ ресурсов в app не нужны. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
@@ -91,15 +320,75 @@
<goals>
<goal>test-jar</goal>
</goals>
<configuration>
<includes>
<include>ru/pjandro/**</include>
<include>samples/**</include>
<include>geom/**</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
<!-- Разделение наборов: гейт по умолчанию — только тесты проекта;
upstream-набор — в профиле upstream-tests (см. ниже). -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<id>default-test</id>
<configuration>
<!-- slf4j-бэкенд тестов проекта — slf4j-simple (as prod);
logback-classic на test-classpath нужен только
upstream-тестам, провайдер фиксируем явно -->
<argLine>@{argLine} -Djava.awt.headless=true -Dslf4j.provider=org.slf4j.simple.SimpleServiceProvider</argLine>
<includes>
<!-- plexus-паттерн: `**` НЕ матчит ноль каталогов —
классы корневого пакета добавлены отдельным паттерном -->
<include>ru/pjandro/wordpdf/*Test.java</include>
<include>ru/pjandro/wordpdf/**/*Test.java</include>
</includes>
<excludes>
<exclude>org/**</exclude>
</excludes>
</configuration>
</execution>
</executions>
</plugin>
<!-- Чужой код (слитый docx4j) не линтеруется и не измеряется:
PMD и JaCoCo — только по ru.pjandro.*. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/org/docx4j/**</exclude>
<exclude>**/org/pptx4j/**</exclude>
<exclude>**/org/xlsx4j/**</exclude>
<exclude>**/org/glox4j/**</exclude>
<exclude>**/org/opendope/**</exclude>
<exclude>**/org/merlin/**</exclude>
</excludes>
</configuration>
</plugin>
<!-- Гейт покрытия ядра: к общему LINE 0.90 (корневой pluginManagement)
добавлен BRANCH 0.85 — только для core; у wordpdf-app бранчи ниже
порога, общий rule в корне остаётся LINE-only. -->
порога, общий rule в корне остаётся LINE-only. Исключения — слитый
docx4j: иначе 4 тыс. чужих файлов уронят порог. -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>org/docx4j/**</exclude>
<exclude>org/pptx4j/**</exclude>
<exclude>org/xlsx4j/**</exclude>
<exclude>org/glox4j/**</exclude>
<exclude>org/opendope/**</exclude>
<exclude>org/merlin/**</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>check</id>
@@ -127,4 +416,69 @@
</plugin>
</plugins>
</build>
<profiles>
<!-- Перенесённый upstream-набор тестов docx4j (409 core + 182 export-fo-tests +
37 in-module + 7 chart-render + 1 JAXB-RI). Не в гейте по умолчанию:
~660 классов × отдельный JVM (требование upstream: Saxon XPath и тесты,
мутирующие статические карты) = десятки минут. Пуск:
mvn -pl wordpdf-core -am test -Pupstream-tests -->
<profile>
<id>upstream-tests</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<id>upstream-docx4j-tests</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<!-- upstream-набор пишет через logback (несколько
классов достают LoggerContext напрямую); JAXP-фабрики —
JDK-реализации, как в upstream docx4j.properties
(xercesImpl на test-classpath иначе перехватывает
DocumentBuilderFactory.newInstance() через
META-INF/services, а standalone-Xerces 2.12.2 не
знает factory-свойство accessExternalDTD, на котором
падает ExtractionConformanceTest) -->
<argLine>@{argLine} -Djava.awt.headless=true -Dslf4j.provider=ch.qos.logback.classic.spi.LogbackServiceProvider -Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl -Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl</argLine>
<includes>
<!-- `**` не матчит ноль каталогов — root-пакеты отдельными паттернами -->
<include>org/docx4j/*Test.java</include>
<include>org/docx4j/*Tests.java</include>
<include>org/docx4j/**/*Test.java</include>
<include>org/docx4j/**/*Tests.java</include>
<include>org/pptx4j/*Test.java</include>
<include>org/pptx4j/**/*Test.java</include>
<include>org/pptx4j/**/*Tests.java</include>
<include>org/xlsx4j/*Test.java</include>
<include>org/xlsx4j/**/*Test.java</include>
<include>org/xlsx4j/**/*Tests.java</include>
</includes>
<excludes>
<exclude>**/samples/**</exclude>
<exclude>**/AbstractNumberingTest.java</exclude>
<!-- читает docx4j.properties из корня classpath — он
намеренно не перенесён (менял бы поведение всем
тестам модуля, см. план слияния); остальные
зависимости от того properties — известно-красные
методы, триаж в docs/agent/testing.md (surefire
запрещает #method в excludes POM'а) -->
<exclude>**/Docx4jPropertiesFoFileTest.java</exclude>
</excludes>
<forkCount>1</forkCount>
<reuseForks>false</reuseForks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
+451
View File
@@ -0,0 +1,451 @@
grammar XPathEnhancer;
options {
output = template;
rewrite = true;
}
tokens {
PATHSEP = '/';
ABRPATH = '//';
LPAR = '(';
RPAR = ')';
LBRAC = '[';
RBRAC = ']';
MINUS = '-';
PLUS = '+';
DOT = '.';
MUL = '*';
DOTDOT = '..';
AT = '@';
COMMA = ',';
PIPE = '|';
LESS = '<';
MORE = '>';
LE = '<=';
GE = '>=';
COLON = ':';
CC = '::';
APOS = '\'';
QUOT = '\"';
}
@parser::header {
/*
Based on the XPath 1.0 (http://www.w3.org/TR/1999/REC-xpath-19991116) grammar by Jan-Willem van den Broek,
version 1.0, downloaded on 2011-06-18 from http://blog.jwbroek.com/2010/07/antlr-grammar-for-parsing-xpath-10.html
That page said "Do with this code as you will."
*/
package org.docx4j.model.datastorage;
}
@lexer::header {
package org.docx4j.model.datastorage;
}
@members {
private String index;
private String prefix;
private int prefixLength;
public static String enhanceXPath(final String prefix, final int index, final String xpath) {
final ANTLRStringStream stringStream = new ANTLRStringStream(xpath);
final XPathEnhancerLexer xl = new XPathEnhancerLexer(stringStream);
final TokenRewriteStream trs = new TokenRewriteStream(xl);
final XPathEnhancerParser xp = new XPathEnhancerParser(trs, index, prefix);
try {
xp.main();
} catch (RecognitionException e) {
throw new IllegalArgumentException(xpath + " is no valid XPath expression", e);
}
final String enhanced = trs.toString();
return enhanced;
}
public XPathEnhancerParser(TokenStream input, final int index, final String prefix) {
this(input);
this.index = "" + index;
this.prefix = prefix;
this.prefixLength = prefix.length();
}
private boolean sharesPrefix(final String path) {
return path != null && path.startsWith(prefix)
&& !positionFunctionPredicateFollows(path.substring(prefixLength));
}
/* True if the part of the path following the repeat prefix begins with
predicates of which one uses position() or last(): the author is
deliberately addressing a specific item of the repeated collection
(eg items[last()]), so the path is left as-is rather than being
contextualized to the current repeat instance.
A numeric predicate (eg [1]) still means the current instance, per the
sample-based authoring convention.
See https://github.com/plutext/docx4j/discussions/691 */
private static boolean positionFunctionPredicateFollows(final String suffix) {
int i = 0;
while (suffix != null && i < suffix.length() && suffix.charAt(i) == '[') {
final int start = i;
int depth = 0;
for (; i < suffix.length(); i++) {
final char c = suffix.charAt(i);
if (c == '[') {
depth++;
} else if (c == ']') {
depth--;
if (depth == 0) {
i++;
break;
}
} else if (c == '\'' || c == '"') {
final int close = suffix.indexOf(c, i + 1);
if (close < 0) return false; // malformed
i = close;
}
}
if (depth != 0) return false; // malformed
final String predicate = suffix.substring(start + 1, i - 1);
if (predicate.contains("position(") || predicate.contains("last(")) {
return true;
}
}
return false;
}
private String remainingSuffix(final String path) {
if (path == null || path.length() < prefixLength) {
return null;
} else {
return path.substring(prefixLength);
}
}
}
main
:
expr
;
locationPath
:
relativeLocationPath
| absoluteLocationPathNoroot
;
absoluteLocationPathNoroot
:
originalAbsoluteLocationPathNoroot
->
template ( sharesPrefix = { sharesPrefix($text) },
commonPrefix = { prefix },
index = { index },
remainingSuffix = { remainingSuffix($text) },
originalPath = { $text } )
"<if(sharesPrefix)><commonPrefix>[<index>]<remainingSuffix><else><originalPath><endif>"
;
originalAbsoluteLocationPathNoroot
:
'/' relativeLocationPath
| '//' relativeLocationPath
;
relativeLocationPath
:
step
(
(
'/'
| '//'
)
step
)*
;
step
:
axisSpecifier nodeTest predicate*
| abbreviatedStep
;
axisSpecifier
:
AxisName '::'
| '@'?
;
nodeTest
:
nameTest
| NodeType '(' ')'
| 'processing-instruction' '(' Literal ')'
;
predicate
:
'[' expr ']'
;
abbreviatedStep
:
'.'
| '..'
;
expr
:
orExpr
;
primaryExpr
:
variableReference
| '(' expr ')'
| Literal
| Number
| functionCall
;
functionCall
:
functionName '(' (expr (',' expr)*)? ')'
;
unionExprNoRoot
:
pathExprNoRoot ('|' unionExprNoRoot)?
| '/' '|' unionExprNoRoot
;
pathExprNoRoot
:
locationPath
| filterExpr absoluteLocationPathNoroot ?
;
filterExpr
:
primaryExpr predicate*
;
orExpr
:
andExpr ('or' andExpr)*
;
andExpr
:
equalityExpr ('and' equalityExpr)*
;
equalityExpr
:
relationalExpr
(
(
'='
| '!='
)
relationalExpr
)*
;
relationalExpr
:
additiveExpr
(
(
'<'
| '>'
| '<='
| '>='
)
additiveExpr
)*
;
additiveExpr
:
multiplicativeExpr
(
(
'+'
| '-'
)
multiplicativeExpr
)*
;
multiplicativeExpr
:
unaryExprNoRoot
(
(
'*'
| 'div'
| 'mod'
)
multiplicativeExpr
)?
| '/'
(
(
'div'
| 'mod'
)
multiplicativeExpr
)?
;
unaryExprNoRoot
:
'-'* unionExprNoRoot
;
qName
:
nCName (':' nCName)?
;
functionName
:
qName // Does not match nodeType, as per spec.
;
variableReference
:
'$' qName
;
nameTest
:
'*'
| nCName ':' '*'
| qName
;
nCName
:
NCName
| AxisName
;
NodeType
:
'comment'
| 'text'
| 'processing-instruction'
| 'node'
;
Number
:
Digits ('.' Digits?)?
| '.' Digits
;
fragment
Digits
:
('0'..'9')+
;
AxisName
:
'ancestor'
| 'ancestor-or-self'
| 'attribute'
| 'child'
| 'descendant'
| 'descendant-or-self'
| 'following'
| 'following-sibling'
| 'namespace'
| 'parent'
| 'preceding'
| 'preceding-sibling'
| 'self'
;
Literal
:
'"' ~'"'* '"'
| '\'' ~'\''* '\''
;
Whitespace
:
(
' '
| '\t'
| '\n'
| '\r'
)+
{
$channel = HIDDEN;
}
;
NCName
:
NCNameStartChar NCNameChar*
;
fragment
NCNameStartChar
:
'A'..'Z'
| '_'
| 'a'..'z'
| '\u00C0'..'\u00D6'
| '\u00D8'..'\u00F6'
| '\u00F8'..'\u02FF'
| '\u0370'..'\u037D'
| '\u037F'..'\u1FFF'
| '\u200C'..'\u200D'
| '\u2070'..'\u218F'
| '\u2C00'..'\u2FEF'
| '\u3001'..'\uD7FF'
| '\uF900'..'\uFDCF'
| '\uFDF0'..'\uFFFD'
| PermittedHighSurrogateChar LowSurrogateChar
;
// UniCode supplementary character support added
// 2011-06-18 Karsten Tinnefeld
// cf. http://java.sun.com/javase/technologies/core/basic/intl/faq.jsp
// [#x10000-#xEFFFF] is [#xD800 0xDC00-#xDB7F 0xDFFF] in UTF-16
// cf. http://en.wikipedia.org/wiki/UTF-16/UCS-2
// cf. http://www.w3.org/TR/xml11/#sec-common-syn
fragment
PermittedHighSurrogateChar
:
'\uD800'..'\uDB7F'
;
fragment
LowSurrogateChar
:
'\uDC00'..'\uDFFF'
;
fragment
NCNameChar
:
NCNameStartChar
| '-'
| '.'
| '0'..'9'
| '\u00B7'
| '\u0300'..'\u036F'
| '\u203F'..'\u2040'
;
@@ -0,0 +1,71 @@
T__37=37
T__38=38
T__39=39
T__40=40
T__41=41
T__42=42
T__43=43
T__44=44
PATHSEP=4
ABRPATH=5
LPAR=6
RPAR=7
LBRAC=8
RBRAC=9
MINUS=10
PLUS=11
DOT=12
MUL=13
DOTDOT=14
AT=15
COMMA=16
PIPE=17
LESS=18
MORE=19
LE=20
GE=21
COLON=22
CC=23
APOS=24
QUOT=25
AxisName=26
NodeType=27
Literal=28
Number=29
NCName=30
Digits=31
Whitespace=32
NCNameStartChar=33
NCNameChar=34
PermittedHighSurrogateChar=35
LowSurrogateChar=36
'/'=4
'//'=5
'('=6
')'=7
'['=8
']'=9
'-'=10
'+'=11
'.'=12
'*'=13
'..'=14
'@'=15
','=16
'|'=17
'<'=18
'>'=19
'<='=20
'>='=21
':'=22
'::'=23
'\''=24
'\"'=25
'processing-instruction'=37
'or'=38
'and'=39
'='=40
'!='=41
'div'=42
'mod'=43
'$'=44
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,313 @@
package org.docx4j;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.docx4j.utils.ResourceUtils;
/**
* docx4j's configuration: {@code docx4j.properties}, loaded once from the classpath, plus
* whatever a caller {@link #setProperty(String, String) sets}.
*
* <p>Since 17.2.0 a second, optional file, {@code docx4j-fo.properties}, supplies
* <b>fallback</b> values: it is loaded from the classpath after {@code docx4j.properties}
* and only its keys that {@code docx4j.properties} does not set are taken. It is where
* the PDF-via-XSL-FO properties ({@code docx4j.convert.out.fo.*} - the Word layout rules'
* opt-outs and tunings, which a deployment rarely changes) live in the reference
* configuration ({@code docx4j-samples-resources}), so that {@code docx4j.properties}
* stays short. A key set in {@code docx4j.properties} wins over the same key in
* {@code docx4j-fo.properties}; a key set programmatically wins over both. Any key may
* appear in either file; a key in {@code docx4j-fo.properties} outside
* {@code docx4j.convert.out.fo} is honoured but logged, since it is probably in the wrong
* file. Absent, the file is not missed (a deployment without docx4j-export-fo has no
* use for it); an absent {@code docx4j.properties} is still warned about.</p>
*/
public class Docx4jProperties {
protected static Logger log = LoggerFactory.getLogger(Docx4jProperties.class);
/** The optional second file; see the class comment. @since 17.2.0 */
public static final String FO_PROPERTIES = "docx4j-fo.properties";
/** Keys expected in {@link #FO_PROPERTIES}; others there are honoured but logged. @since 17.2.0 */
public static final String FO_PREFIX = "docx4j.convert.out.fo";
private static Properties properties;
private static void init() {
defaultTheme = null;
InputStream main = null;
try {
main = ResourceUtils.getResource("docx4j.properties");
} catch (Exception e) {
log.warn("Couldn't find/read docx4j.properties; " + e.getMessage());
}
InputStream fo = null;
try {
fo = ResourceUtils.getResourceIfPresent(FO_PROPERTIES);
} catch (Exception e) {
log.warn("Couldn't read " + FO_PROPERTIES + "; " + e.getMessage());
}
try {
properties = load(main, fo);
} finally {
close(main);
close(fo);
}
}
/**
* The table {@link #init()} builds: {@code docx4j.properties}' entries, then those of
* {@code docx4j-fo.properties} the first did not set. Either stream may be null (the
* file is absent); neither is closed here.
*
* @since 17.2.0
*/
public static Properties load(InputStream docx4jProperties, InputStream foProperties) {
Properties p = new Properties();
if (docx4jProperties != null) {
try {
p.load(docx4jProperties);
} catch (Exception e) {
log.warn("Couldn't read docx4j.properties; " + e.getMessage());
}
}
if (foProperties != null) {
Properties fo = new Properties();
try {
fo.load(foProperties);
} catch (Exception e) {
log.warn("Couldn't read " + FO_PROPERTIES + "; " + e.getMessage());
}
int taken = 0;
for (String key : fo.stringPropertyNames()) {
if (!key.startsWith(FO_PREFIX)) {
log.info(FO_PROPERTIES + " sets " + key + ", which is not a " + FO_PREFIX
+ " property; honoured, but docx4j.properties is its usual place");
}
if (p.containsKey(key)) {
log.debug(key + ": docx4j.properties' value kept over " + FO_PROPERTIES + "'s");
} else {
p.setProperty(key, fo.getProperty(key));
taken++;
}
}
log.debug(FO_PROPERTIES + ": " + taken + " of " + fo.size() + " properties taken");
}
return p;
}
private static void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (Exception e) {
log.debug("closing: " + e.getMessage());
}
}
}
/**
* Which Office theme docx4j supplies where a document asks for a theme font and its
* package has <b>no theme part</b>, and which theme part
* {@code WordprocessingMLPackage.createPackage} puts in a new package.
*
* <p>Word supplies its own default theme to such a document, and which faces that names
* has changed twice: measured on a Word 365 rendering of a package with no theme part
* (CR-001 batch 49), the body face is <b>Aptos</b> and the heading face
* <b>Aptos Display</b>, where Office 2013 to 2022 answered Calibri and Calibri Light and
* Office 2007 to 2010 answered Calibri and Cambria. So this is the version of Word a
* themeless document should be read as having come from - not a docx4j preference - and
* the default is the current one.</p>
*
* <p>Values: {@code 2023} (the default), {@code 2013}, {@code 2007};
* see {@link DefaultTheme}. Anything else logs a warning and falls back to the default.</p>
*
* @since 17.2.0
*/
public static final String DEFAULT_THEME = "docx4j.fonts.defaultTheme";
/**
* The three answers {@link Docx4jProperties#DEFAULT_THEME} takes, each with the Latin
* faces its font scheme names and the theme part docx4j bundles for it.
*
* @since 17.2.0
*/
public enum DefaultTheme {
/** Word 365's Office theme: Aptos Display / Aptos. The default. */
THEME_2023("2023", "Aptos Display", "Aptos"),
/** Office 2013 to 2022: Calibri Light / Calibri. */
THEME_2013("2013", "Calibri Light", "Calibri"),
/** Office 2007 to 2010: Cambria / Calibri; docx4j's answer up to 17.1.0. */
THEME_2007("2007", "Cambria", "Calibri");
private final String value;
private final String majorLatin;
private final String minorLatin;
private DefaultTheme(String value, String majorLatin, String minorLatin) {
this.value = value;
this.majorLatin = majorLatin;
this.minorLatin = minorLatin;
}
/** The property value which selects this theme. */
public String value() {
return value;
}
/** The face its font scheme names for the major (heading) Latin slot. */
public String majorLatin() {
return majorLatin;
}
/** The face its font scheme names for the minor (body) Latin slot. */
public String minorLatin() {
return minorLatin;
}
/** The classpath resource holding this theme's own theme1.xml. */
public String resource() {
return "org/docx4j/openpackaging/parts/WordprocessingML/theme-" + value + ".xml";
}
/** The theme this property value names, or null where it names none. */
public static DefaultTheme of(String value) {
if (value == null) return null;
String v = value.trim();
for (DefaultTheme t : values()) {
if (t.value.equalsIgnoreCase(v)) return t;
}
return null;
}
}
/** Read once (see {@link #getDefaultTheme()}); cleared by {@link #setProperty}. */
private static DefaultTheme defaultTheme;
/**
* {@link #DEFAULT_THEME}, parsed; never null.
*
* <p>Read once and remembered, because it is asked for per run of a themeless document.
* {@code setProperty} clears it, so a unit test can change it.</p>
*
* @since 17.2.0
*/
public static DefaultTheme getDefaultTheme() {
DefaultTheme t = defaultTheme;
if (t != null) return t;
String value = getProperty(DEFAULT_THEME);
t = DefaultTheme.of(value);
if (t == null) {
if (value != null && value.trim().length() > 0) {
log.warn(DEFAULT_THEME + "=" + value + " is not one of 2023, 2013 or 2007; using "
+ DefaultTheme.THEME_2023.value());
}
t = DefaultTheme.THEME_2023;
}
defaultTheme = t;
return t;
}
public static String getProperty(String key) {
if (properties==null) {init();}
return properties.getProperty(key);
}
/**
* @since 2.7.2
*/
public static String getProperty(String key, String defaultValue) {
if (properties==null) {init();}
return properties.getProperty(key, defaultValue);
}
/**
* @since 3.3.0
*/
public static boolean getProperty(String key, boolean defaultValue) {
if (properties==null) {init();}
String result = properties.getProperty(key, Boolean.toString(defaultValue));
return Boolean.parseBoolean(result);
}
public static int getProperty(String key, int defaultValue) {
if (properties==null) {init();}
String val = properties.getProperty(key);
if (val==null) return defaultValue;
try {
return (Integer.parseInt(val));
} catch (NumberFormatException e) {
log.info(e.getMessage(),e);
return defaultValue;
}
}
/**
* @since 6.0.0
*/
public static long getPropertyLong(String key, long defaultValue) {
if (properties==null) {init();}
String val = properties.getProperty(key);
if (val==null) return defaultValue;
try {
return (Long.parseLong(val));
} catch (NumberFormatException e) {
log.info(e.getMessage(),e);
return defaultValue;
}
}
public static Properties getProperties() {
if (properties==null) {init();}
return properties;
}
/**
* Useful if a unit test requires a certain property value.
*
* @since 3.0.0
*/
public static void setProperty(String key, Boolean value) {
if (properties==null) {init();}
properties.setProperty(key, value.toString());
if (DEFAULT_THEME.equals(key)) defaultTheme = null;
}
/**
* Useful if a unit test requires a certain property value.
*
* @since 3.0.0
*/
public static void setProperty(String key, String value) {
if (properties==null) {init();}
properties.setProperty(key, value);
if (DEFAULT_THEME.equals(key)) defaultTheme = null;
}
/**
* @since 6.0.0
*/
public static void setPropertyLong(String key, long value) {
if (properties==null) {init();}
properties.setProperty(key, Long.toString(value));
}
}
@@ -0,0 +1,295 @@
/*
* Copyright 2007-2008, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.docx4j.jaxb.Context;
import org.docx4j.jaxb.NamespacePrefixMapperUtils;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* The character content of an object's XML, as its marshalled form gives it.
*
* @deprecated since 17.3.4: this is not docx4j's text model, and no reader docx4j ships uses it
* (CR-046 phase 3, WD REQ-202). It returns the text of whatever it is given, in whatever view the
* object is (deleted text included), with no stories, no hidden text left out, no separators
* between paragraphs, and field codes for some objects. Use {@link org.docx4j.model.text.Texts}
* ({@code Texts.plainText(pkg, options)}, or {@code Texts.of(part or content, options)} for the
* block model), which reads a document as the text model specifies. Its output is unchanged.
*/
@Deprecated
public class TextUtils {
private static Logger log = LoggerFactory.getLogger(TextUtils.class);
/**
* Extract contents of descendant <w:t> elements.
*
* @param o
* @return String
* @since 6.0.0
* @deprecated since 17.3.4: not the text model; see {@link org.docx4j.model.text.Texts}
*/
@Deprecated
public static String getText(Object o) {
StringWriter w = new StringWriter();
try {
extractText(o, w, Context.jc);
} catch (Exception e) {
log.warn(e.getMessage());
return null;
}
return w.toString();
}
/**
* Extract contents of descendant <w:t> elements.
*
* @param o
* @param jcSVG JAXBContext
* @return
* @deprecated since 17.3.4: not the text model; see {@link org.docx4j.model.text.Texts}
*/
@Deprecated
public static void extractText(Object o, Writer w) throws Docx4JException {
extractText(o, w, Context.jc);
}
/**
* Extract contents of descendant <w:t> elements.
*
* @param o
* @param jc JAXBContext
* @return
* @throws Docx4JException
* @deprecated since 17.3.4: not the text model; see {@link org.docx4j.model.text.Texts}
*/
@Deprecated
public static void extractText(Object o, Writer w, JAXBContext jc) throws Docx4JException {
if (o==null) {
throw new Docx4JException("Can't extractText from null object");
}
try {
Marshaller marshaller=jc.createMarshaller();
NamespacePrefixMapperUtils.setProperty(marshaller,
NamespacePrefixMapperUtils.getPrefixMapper());
marshaller.marshal(o, new TextExtractor(w));
} catch (JAXBException e) {
throw new Docx4JException("JAXB error marshalling to extractText", e);
}
}
/**
* Extract contents of descendant <w:t> elements.
* Use this for objects which don't have @XmlRootElement
*
* @param o
* @param w
* @param jc
* @param uri
* @param local
* @param declaredType
* @throws Exception
* @deprecated since 17.3.4: not the text model; see {@link org.docx4j.model.text.Texts}
*/
@Deprecated
public static void extractText(Object o, Writer w, JAXBContext jc,
String uri, String local, Class declaredType) throws Docx4JException {
try {
Marshaller marshaller=jc.createMarshaller();
NamespacePrefixMapperUtils.setProperty(marshaller,
NamespacePrefixMapperUtils.getPrefixMapper());
marshaller.marshal(
new JAXBElement(new QName(uri,local), declaredType, o ),
new TextExtractor(w));
} catch (JAXBException e) {
throw new Docx4JException("JAXB error marshalling to extractText", e);
}
}
/**
* A SAX ContentHandler that writes all #PCDATA onto a java.io.Writer
*
* From http://www.cafeconleche.org/books/xmljava/chapters/ch06s03.html
*
*/
/**
* Writes the character content it is handed.
*
* <p>mc:AlternateContent (since 17.2.0, CR-021): the text of ONE branch - the one
* {@link org.docx4j.jaxb.McSelection} draws - is written; the other branches are
* skipped, so a text box's text appears once. The rule is McSelection's exactly:
* the first Choice whose Requires prefixes are all preferred, else the Fallback,
* else (Choices but no Fallback) the first Choice. Being a stream, this cannot
* know a Fallback is absent until the element ends, so the first unpreferred
* Choice's text is held back and written only then, if nothing else was taken.</p>
*/
public static class TextExtractor extends DefaultHandler {
private static final String MC_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006";
private Writer out;
/** One open mc:AlternateContent. */
private static final class Alternate {
boolean taken;
StringBuilder firstChoice; // held-back text of the first unpreferred Choice
int firstChoiceDepth; // the depth of that Choice element
}
private final java.util.ArrayDeque<Alternate> alternates = new java.util.ArrayDeque<Alternate>();
/** Where characters go: the innermost held-back Choice's buffer, else the writer. */
private final java.util.ArrayDeque<StringBuilder> captures = new java.util.ArrayDeque<StringBuilder>();
/** Depth inside a skipped branch; 0 when writing. */
private int skipping = 0;
private int depth = 0;
public TextExtractor(Writer out) {
this.out = out;
}
private void emit(CharSequence text) throws SAXException {
if (captures.isEmpty()) {
try {
out.write(text.toString());
} catch (IOException e) {
throw new SAXException(e);
}
} else {
captures.peek().append(text);
}
}
@Override
public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts)
throws SAXException {
depth++;
if (skipping > 0) {
skipping++;
return;
}
if (!MC_NS.equals(uri)) return;
if ("AlternateContent".equals(localName)) {
alternates.push(new Alternate());
} else if ("Choice".equals(localName)) {
Alternate alt = alternates.peek();
String requires = atts.getValue("Requires");
if (requires == null) requires = atts.getValue("", "Requires");
if (alt == null) return; // a stray Choice: written through
if (!alt.taken && org.docx4j.jaxb.McSelection.prefersChoice(requires)) {
alt.taken = true;
alt.firstChoice = null;
} else if (!alt.taken && alt.firstChoice == null) {
// the last resort, held back until the element ends
alt.firstChoice = new StringBuilder();
alt.firstChoiceDepth = depth;
captures.push(alt.firstChoice);
} else {
skipping = 1;
}
} else if ("Fallback".equals(localName)) {
Alternate alt = alternates.peek();
if (alt == null) return;
if (!alt.taken) {
alt.taken = true;
alt.firstChoice = null; // the held-back Choice is not needed
} else {
skipping = 1;
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (skipping > 0) {
skipping--;
depth--;
return;
}
if (MC_NS.equals(uri)) {
if ("Choice".equals(localName)) {
Alternate alt = alternates.peek();
if (alt != null && alt.firstChoiceDepth == depth && !captures.isEmpty()
&& (alt.firstChoice == null || captures.peek() == alt.firstChoice)) {
captures.pop();
}
} else if ("AlternateContent".equals(localName) && !alternates.isEmpty()) {
Alternate alt = alternates.pop();
if (!alt.taken && alt.firstChoice != null) {
emit(alt.firstChoice);
}
}
}
depth--;
}
public void characters(char[] text, int start, int length) throws SAXException {
if (skipping > 0) return;
emit(new String(text, start, length));
}
} // end TextExtractor
public static void main(String[] args) throws Exception {
String inputfilepath = System.getProperty("user.dir") + "/sample-docs/Table.docx";
//String inputfilepath = System.getProperty("user.dir") + "/sample-docs/Word2007-fonts.docx";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document)documentPart.getJaxbElement();
// UTF-8 whatever the platform's default, so that no character is lost to a code page (WD REQ-711)
Writer out = new OutputStreamWriter(System.out, java.nio.charset.StandardCharsets.UTF_8);
extractText(wmlDocumentEl, out);
//out.flush();
out.close();
}
}
@@ -0,0 +1,968 @@
/*
* Copyright 2010-2011, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.JAXBElement;
import org.docx4j.com.microsoft.schemas.office.word.x2010.wordprocessingShape.CTWordprocessingShape;
import org.docx4j.dml.CTHyperlink;
import org.docx4j.dml.CTNonVisualDrawingProps;
import org.docx4j.dml.diagram.CTDataModel;
import org.docx4j.jaxb.Context;
import org.docx4j.jaxb.McMode;
import org.docx4j.jaxb.McSelection;
import org.docx4j.mce.AlternateContent;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.CommentsPart;
import org.docx4j.openpackaging.parts.WordprocessingML.EndnotesPart;
import org.docx4j.openpackaging.parts.WordprocessingML.FooterPart;
import org.docx4j.openpackaging.parts.WordprocessingML.FootnotesPart;
import org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.openpackaging.parts.relationships.Namespaces;
import org.docx4j.openpackaging.parts.relationships.RelationshipsPart;
import org.docx4j.relationships.Relationship;
import org.docx4j.utils.CompoundTraversalUtilVisitorCallback;
import org.docx4j.utils.SingleTraversalUtilVisitorCallback;
import org.docx4j.utils.TraversalUtilVisitor;
import org.docx4j.wml.Br;
import org.docx4j.wml.CTBookmark;
import org.docx4j.wml.CTMarkupRange;
import org.docx4j.wml.CTObject;
import org.docx4j.wml.Comments.Comment;
import org.docx4j.wml.FldChar;
import org.docx4j.wml.Pict;
import org.docx4j.wml.ProofErr;
import org.docx4j.wml.R;
import org.jvnet.jaxb.lang.Child;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Traverse a list of JAXB objects (eg document.xml's document/body
* children), and do something to them.
*
* This is similar to what one could do via XSLT,
* but avoids marshalling/unmarshalling. The downside is that
* not everything will necessarily get traversed here
* since visitChildren is not (yet) comprehensive.
*
* This utility might be redundant if we used
* http://code.google.com/p/jaxb-visitor/ or
* https://github.com/ops4j/org.ops4j.xvisitor
* at XJC time. Haven't tried them though.
*
* See also org.docx4j.utils.SingleTraversalUtilVisitorCallback
* and CompoundTraversalUtilVisitorCallback
*
* <p><b>mc:AlternateContent</b> (since 17.2.0, CR-021): a walk visits ONE branch of
* each mc:AlternateContent by default, which is {@link McMode#READ}: since 17.3.4 the
* branch docx4j reads for text ({@link org.docx4j.jaxb.McPurpose#TEXT}, CR-046 phase 3),
* before it the branch docx4j draws, which a walk serving an output's layout asks for
* with {@link McMode#DRAW} (see {@link McSelection}). A walk that edits the tree
* (binding, field update, merge, anonymisation, find and replace) must ask for
* {@link McMode#ALL} through the constructor or visit overload that takes a mode,
* or by {@link CallbackImpl#setMcMode}, so its edit reaches every branch. Before
* 17.2.0 every walk saw every branch, and a text box's paragraphs twice.</p>
*
* @author jharrop, alberto
*
*/
public class TraversalUtil {
private static Logger log = LoggerFactory.getLogger(TraversalUtil.class);
public interface Callback {
void walkJAXBElements(Object parent);
List<Object> getChildren(Object o);
/**
* Visits a node in pre order (before its children have been visited).
*
* A node is visited only if all its parents have been traversed (
* {@link #shouldTraverse(Object)}).</p>
*
* <p>
* Implementations can have side effects.
* </p>
*/
List<Object> apply(Object o);
/**
* Decide whether this node's children should be traversed.
*
* @return whether the children of this node should be visited
*/
boolean shouldTraverse(Object o);
// TODO for next gen interface, add
// List<Object> applyAfterWalkChildren(Object o);
}
public static abstract class CallbackImpl implements Callback {
// Depth first
public void walkJAXBElements(Object parent) {
List children = getChildren(parent);
if (children != null) {
Object o2;
for (Object o : children) {
// In 3.3.4, we don't expect to do any parent fixes here.
if (o instanceof jakarta.xml.bind.JAXBElement) {
// get its value; this is ok,
// provided the results of the Callback
// won't be marshalled
o2 = ((JAXBElement)o).getValue();
if (o2 instanceof Child) {
if (parent instanceof List){
// It shouldn't be (as ArrayListWml usually handles), but do nothing
if (log.isDebugEnabled()) {
if ( ((Child)o2).getParent()==null) {
log.debug("Unknown parent for " + o2.getClass().getName());
} else {
log.debug("Parent of " + o2.getClass().getName()
+ " is currently " + ((Child)o2).getParent().getClass().getName());
}
}
} else {
if (parent==((Child)o2).getParent()) {
// all good
} else {
// workaround for broken getParent in cases where ArrayListWml doesn't help
// (ie we're not in a content list)
if ( ((Child)o2).getParent()==null) {
// 3.3.4: to setParent, or not?
// Yes, let's, since something is better than null.
// But note, we could be setting it to some other ancestor because of how getChildren works
// When does this ever happen? Log at warn level to find out..
// I think it would only ever happen if there was foo.setBar(JAXBElement z)
if (log.isWarnEnabled()) {
log.warn("Unknown parent for " + o2.getClass().getName()
+ "; setting to " + parent.getClass().getName()
);
}
((Child)o2).setParent(parent);
} else if (((Child)o2).getParent() instanceof org.docx4j.dml.GraphicData) {
// by design: handleGraphicData flattens a:graphicData's content (a chart's
// c:chart or cx:chart) into the anchor's children, so the child's own parent
// is the GraphicData while the walk's is the anchor; not a defect (a chartex
// chart's CTRelId warned here once per chart, Enterprise's finding 2026-10-28)
if (log.isDebugEnabled()) {
log.debug("Parent of " + o2.getClass().getName() + " is its GraphicData; the walk's is "
+ parent.getClass().getName());
}
} else {
// If this happens, we need to understand why
// eg Parent of org.docx4j.wml.Tc is currently org.docx4j.wml.CTSdtContentCell
if (log.isWarnEnabled()) {
log.warn("Parent of " + o2.getClass().getName()
+ " is currently " + ((Child)o2).getParent().getClass().getName()
+ " not " + parent.getClass().getName()
);
}
// We don't things in this case
//((Child)o2).setParent(parent);
}
if (log.isInfoEnabled()) {
log.info("setting to " + parent.getClass().getName() );
}
}
}
}
} else /* not wrapped in JAXBElement, so getParent should be OK. We never change in this case. */ {
o2 = o;
if (log.isDebugEnabled()) {
if (o2 instanceof Child) {
if (((Child) o2).getParent() == null) {
log.debug("Unknown parent for "
+ o2.getClass().getName());
} else if (parent != ((Child) o2).getParent()) {
// This can happen because getChildren() skips layers,
// so the 'parent' passed in here might actually be the grandparent
log.debug("Parent of "
+ o2.getClass().getName()
+ " is currently "
+ ((Child) o2).getParent().getClass()
.getName()
+ " not " + parent.getClass().getName() );
// Parent of org.docx4j.wml.P is org.docx4j.wml.Body
// (org.docx4j.wml.ArrayListWml should never be the parent; that's an implementation detail)
}
} else {
log.info(o2.getClass().getName() + " not an instanceof Child!");
// eg org.docx4j.wml.STFldCharType
}
}
}
this.apply(o2);
if (this.shouldTraverse(o2)) {
walkJAXBElements(o2);
}
}
}
}
private McMode mcMode = McMode.READ;
/** How this walk treats mc:AlternateContent; {@link McMode#READ} unless set.
* @since 17.2.0 */
public McMode getMcMode() {
return mcMode;
}
/** A walk that edits the tree sets {@link McMode#ALL} before walking, so its
* edit lands in every branch of each mc:AlternateContent. @since 17.2.0 */
public void setMcMode(McMode mcMode) {
this.mcMode = mcMode == null ? McMode.READ : mcMode;
}
public List<Object> getChildren(Object o) {
return TraversalUtil.getChildrenImpl(o, mcMode);
}
/**
* Visits a node in pre order (before its children have been visited).
*
* A node is visited only if all its parents have been traversed (
* {@link #shouldTraverse(Object)}).</p>
*
* <p>
* Implementations can have side effects.
* </p>
*/
public abstract List<Object> apply(Object o);
/**
* Decide whether this node's children should be traversed.
*
* @return whether the children of this node should be visited
*/
public boolean shouldTraverse(Object o) {
return true;
}
}
Callback cb;
/**
* Traverse the object using your callback. Invoking this constructor starts the
* traverse, by invoking the callback's walkJAXBElements method.
*
* @param parent
* @param cb
*/
public TraversalUtil(Object parent, Callback cb) {
this.cb = cb;
cb.walkJAXBElements(parent);
}
/**
* As {@link #TraversalUtil(Object, Callback)}, with the walk's treatment of
* mc:AlternateContent: {@link McMode#ALL} for a callback that edits the tree.
* The mode is set on a {@link CallbackImpl}; a callback implementing
* {@link Callback} directly applies it in its own getChildren, by calling
* {@link #getChildrenImpl(Object, McMode)}.
*
* @since 17.2.0 (CR-021)
*/
public TraversalUtil(Object parent, Callback cb, McMode mcMode) {
this.cb = cb;
if (cb instanceof CallbackImpl) {
((CallbackImpl) cb).setMcMode(mcMode);
} else if (mcMode == McMode.ALL) {
log.debug(cb.getClass().getName() + " does not extend CallbackImpl; it applies McMode.ALL itself or not at all");
}
cb.walkJAXBElements(parent);
}
static void visitChildrenImpl(Object o) {
}
private static List<Object> handleGraphicData(org.docx4j.dml.GraphicData graphicData) {
// Added by Peter Buil
List<Object> tmpArtificialList = new ArrayList<Object>();
if (graphicData.getPic() != null) {
//GraphicData can have a hyperlink reference, which can be found this way
CTNonVisualDrawingProps picNonVisual = graphicData.getPic().getNvPicPr().getCNvPr();
if (picNonVisual != null) {
handleCTNonVisualDrawingProps(picNonVisual, tmpArtificialList);
}
}
// Its not graphicData.getAny() we're typically interested in
if (graphicData.getPic() != null && graphicData.getPic().getBlipFill() != null
&& graphicData.getPic().getBlipFill().getBlip() != null) {
log.debug("found CTBlip");
List<Object> artificialList = new ArrayList<Object>();
if (!tmpArtificialList.isEmpty())
artificialList.addAll(tmpArtificialList);
artificialList.add(graphicData.getPic().getBlipFill().getBlip());
return artificialList;
} else if (graphicData.getWordprocessingShape() != null) {
CTWordprocessingShape wsp = graphicData.getWordprocessingShape();
if (wsp.getTxbx()==null) {
return null;
} else {
return wsp.getTxbx().getTxbxContent().getContent();
// grandchildren, like we do for vml textbox
}
} else {
// Chart is in here
return graphicData.getAny();
}
}
/**
* There can be hyperlinks references in CTNonVisualDrawingProps.
* @param drawingProps
* @param artificialList
*/
private static void handleCTNonVisualDrawingProps(CTNonVisualDrawingProps drawingProps, List<Object> artificialList){
if (drawingProps != null) {
CTHyperlink docPrHyperLink = drawingProps.getHlinkClick();
if (docPrHyperLink != null)
artificialList.add(docPrHyperLink);
}
}
/**
* Get the children of some docx content object
* (as opposed to pptx, xlsx content).
*
* @param o
* @return
*/
public static List<Object> getChildrenImpl(Object o) {
return getChildrenImpl(o, McMode.READ);
}
/**
* As {@link #getChildrenImpl(Object)}, with the treatment of mc:AlternateContent:
* in {@link McMode#READ} its children are the one branch docx4j reads for text (since
* 17.3.4; {@link McSelection#branches(AlternateContent, McMode)}), in {@link McMode#DRAW}
* the one it draws ({@link McSelection#selectedBranch}); in {@link McMode#ALL} every
* Choice and the Fallback. Everything else is the same in every mode.
*
* @since 17.2.0 (CR-021)
*/
public static List<Object> getChildrenImpl(Object o, McMode mcMode) {
if (o==null) {
log.warn("null passed to getChildrenImpl");
return null;
}
if (o instanceof JAXBElement) {
log.debug(".. unwrapping");
o = XmlUtils.unwrap(o);
}
if (log.isDebugEnabled()) log.debug("getting children of " + o.getClass().getName() );
if (o instanceof org.docx4j.wml.Text) return null;
// Short circuit for common elements
if (o instanceof List) {
// Handy if you have your own list of objects you wish to process
return (List<Object>) o;
} else if (o instanceof org.docx4j.wml.Document) {
// since 3.3.4, so traverse visits Body as well. This is more correct, and potentially useful.
List<Object> artificialList = new ArrayList<Object>();
artificialList.add( ((org.docx4j.wml.Document)o).getBody() );
return artificialList;
} else if (o instanceof Br
|| o instanceof CTBookmark
|| o instanceof CTMarkupRange) {
return null;
} else if (o instanceof R.Tab
|| o instanceof R.LastRenderedPageBreak) {
return null;
} else if (o instanceof org.docx4j.wml.ContentAccessor) {
return ((org.docx4j.wml.ContentAccessor) o).getContent();
} else if (o instanceof org.docx4j.wml.SdtElement) {
if (((org.docx4j.wml.SdtElement) o).getSdtContent()!=null) {
return ((org.docx4j.wml.SdtElement) o).getSdtContent().getContent();
} else {
log.warn("SdtElement is missing content element");
return null;
}
// For 3.3.4, I'd prefer to do the following, but it breaks OpenDoPE repeat handling!!
// } else if (o instanceof org.docx4j.wml.SdtElement) {
// // 3.3.4: don't just return ((org.docx4j.wml.SdtElement) o).getSdtContent().getContent()
// // since then we're passing the grandparent as the parent,
// // and we don't want to use that in any parent fix...
// List<Object> artificialList = new ArrayList<Object>();
// artificialList.add(
// ((org.docx4j.wml.SdtElement) o).getSdtContent());
// return artificialList;
} else if (o instanceof org.docx4j.dml.wordprocessingDrawing.Anchor) {
org.docx4j.dml.wordprocessingDrawing.Anchor anchor = (org.docx4j.dml.wordprocessingDrawing.Anchor) o;
List<Object> artificialList = new ArrayList<Object>();
CTNonVisualDrawingProps drawingProps = anchor.getDocPr();
if (drawingProps != null) {
handleCTNonVisualDrawingProps(drawingProps, artificialList);
}
if (anchor.getGraphic() != null) {
log.debug("found a:graphic");
org.docx4j.dml.Graphic graphic = anchor.getGraphic();
if (graphic.getGraphicData() != null) {
List<Object> handledGraphicData = handleGraphicData(graphic.getGraphicData());
if (handledGraphicData==null) {
// log.info("handleGraphicData returned an empty list");
if (log.isDebugEnabled()) {
log.debug(XmlUtils.marshaltoString(graphic, true, true, Context.jc,
"http://schemas.openxmlformats.org/drawingml/2006/main", "graphic", org.docx4j.dml.Graphic.class));
}
} else {
artificialList.addAll(handledGraphicData);
}
}
}
if (!artificialList.isEmpty())
return artificialList;
} else if (o instanceof org.docx4j.dml.wordprocessingDrawing.Inline) {
org.docx4j.dml.wordprocessingDrawing.Inline inline = (org.docx4j.dml.wordprocessingDrawing.Inline) o;
List<Object> artificialList = new ArrayList<Object>();
CTNonVisualDrawingProps drawingProps = inline.getDocPr();
if (drawingProps != null) {
handleCTNonVisualDrawingProps(drawingProps, artificialList);
}
if (inline.getGraphic() != null) {
log.debug("found a:graphic");
org.docx4j.dml.Graphic graphic = inline.getGraphic();
if (graphic.getGraphicData() != null) {
List<Object> handledGraphicData = handleGraphicData(graphic.getGraphicData());
if (handledGraphicData==null) {
// log.info("handleGraphicData returned an empty list");
if (log.isDebugEnabled()) {
log.debug(XmlUtils.marshaltoString(graphic, true, true, Context.jc,
"http://schemas.openxmlformats.org/drawingml/2006/main", "graphic", org.docx4j.dml.Graphic.class));
}
} else {
artificialList.addAll(handledGraphicData);
}
}
}
if (!artificialList.isEmpty())
return artificialList;
} else if (o instanceof Pict) {
return ((Pict)o).getAnyAndAny(); // (why didn't the reflection below find this?)
} else if (o instanceof ProofErr) {
return null;
} else if (o instanceof org.docx4j.dml.picture.Pic) { // Post 2.7.1; untested
org.docx4j.dml.picture.Pic dmlPic = ((org.docx4j.dml.picture.Pic)o);
if (dmlPic.getBlipFill()!=null
&& dmlPic.getBlipFill().getBlip()!=null) {
log.debug("found DML Blip");
List<Object> artificialList = new ArrayList<Object>();
artificialList.add(dmlPic.getBlipFill().getBlip());
return artificialList;
} else {
return null;
}
} else if (o instanceof org.docx4j.dml.CTGvmlPicture) { // Post 2.7.1
org.docx4j.dml.CTGvmlPicture dmlPic = ((org.docx4j.dml.CTGvmlPicture)o);
if (dmlPic.getBlipFill()!=null
&& dmlPic.getBlipFill().getBlip()!=null) {
log.debug("found DML Blip");
List<Object> artificialList = new ArrayList<Object>();
artificialList.add(dmlPic.getBlipFill().getBlip());
return artificialList;
} else {
return null;
}
} else if (o instanceof org.docx4j.vml.CTShape) {
// return ((org.docx4j.vml.CTShape)o).getAny();
List<Object> artificialList = new ArrayList<Object>();
for (JAXBElement<?> j : ((org.docx4j.vml.CTShape)o).getPathOrFormulasOrHandles() ) {
// System.out.println(XmlUtils.unwrap(j).getClass().getName() );
artificialList.add(j);
}
return artificialList;
} else if (o instanceof CTDataModel) {
CTDataModel dataModel = (CTDataModel)o;
List<Object> artificialList = new ArrayList<Object>();
// We're going to create a list merging two children ..
artificialList.addAll(dataModel.getPtLst().getPt());
artificialList.addAll(dataModel.getCxnLst().getCxn());
return artificialList;
} else if (o instanceof org.docx4j.dml.diagram2008.CTDrawing) {
return ((org.docx4j.dml.diagram2008.CTDrawing)o).getSpTree().getSpOrGrpSp();
} else if (o instanceof org.docx4j.vml.CTTextbox) {
// return ((org.docx4j.vml.CTTextbox)o).getAny();
org.docx4j.vml.CTTextbox textBox = ((org.docx4j.vml.CTTextbox)o);
if (textBox.getTxbxContent()==null) {
return null;
} else {
return textBox.getTxbxContent().getContent();
// grandchildren
}
// } else if (o instanceof org.docx4j.wml.CTTxbxContent) {
// return ((org.docx4j.wml.CTTxbxContent)o).getEGBlockLevelElts();
} else if (o instanceof CTObject) {
CTObject ctObject = (CTObject)o;
List<Object> artificialList = new ArrayList<Object>();
artificialList.addAll(ctObject.getAnyAndAny());
if (ctObject.getControl()!=null) {
artificialList.add(ctObject.getControl() ); // CTControl
}
return artificialList;
} else if (o instanceof org.docx4j.dml.CTGvmlGroupShape) {
return ((org.docx4j.dml.CTGvmlGroupShape)o).getTxSpOrSpOrCxnSp();
} else if (o instanceof org.docx4j.dml.CTGvmlShape) {
org.docx4j.dml.CTGvmlShape sp = (org.docx4j.dml.CTGvmlShape)o;
if (sp!=null
&& sp.getTxSp()!=null
&& sp.getTxSp().getTxBody()!=null) {
List<Object> artificialList = new ArrayList<Object>();
artificialList.addAll(sp.getTxSp().getTxBody().getP());
return artificialList;
}
return null;
} else if(o instanceof FldChar) {
FldChar fldChar = ((FldChar)o);
List<Object> artificialList = new ArrayList<Object>();
artificialList.add(fldChar.getFldCharType());
if(fldChar.getFfData() != null) {
artificialList.add(fldChar.getFfData());
}
if(fldChar.getFldData() != null) {
artificialList.add(fldChar.getFldData());
}
if(fldChar.getNumberingChange() != null) {
artificialList.add(fldChar.getNumberingChange());
}
return artificialList;
} else if (o instanceof org.docx4j.mce.AlternateContent) {
// CR-021: one branch (the one docx4j draws) unless the walk asked for ALL
return McSelection.branches((AlternateContent)o, mcMode);
} else if (o instanceof org.docx4j.com.microsoft.schemas.office.word.x2010.wordprocessingShape.CTWordprocessingShape) {
org.docx4j.com.microsoft.schemas.office.word.x2010.wordprocessingShape.CTWordprocessingShape sp = (org.docx4j.com.microsoft.schemas.office.word.x2010.wordprocessingShape.CTWordprocessingShape)o;
if (sp!=null
&& sp.getTxbx()!=null
&& sp.getTxbx().getTxbxContent()!=null) {
return sp.getTxbx().getTxbxContent().getContent();
}
return null;
}
// OK, what is this? Use reflection ..
// This should work for things including w:drawing
if (log.isDebugEnabled()) log.debug(o.getClass().getName() + " .. looking for method which returns list " );
try {
// the first List-returning method of the class, looked up once per class (before
// 17.3.4 on every call, which made a walk's cost mostly reflection: CR-052 phase 1)
Method listGetter = LIST_GETTERS.get(o.getClass());
if (listGetter == null) {
listGetter = NO_LIST_GETTER;
Method[] methods = o.getClass().getDeclaredMethods();
for (int i = 0; i<methods.length; i++) {
Method m = methods[i];
if (m.getReturnType().getName().equals("java.util.List") && m.getParameterCount() == 0) {
listGetter = m;
break;
}
}
LIST_GETTERS.put(o.getClass(), listGetter);
}
if (listGetter != NO_LIST_GETTER) {
return (List<Object>)listGetter.invoke(o);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
log.debug(".. no list member");
return null;
}
private static final java.util.concurrent.ConcurrentHashMap<Class<?>, Method> LIST_GETTERS
= new java.util.concurrent.ConcurrentHashMap<Class<?>, Method>();
private static final Method NO_LIST_GETTER;
static {
try {
NO_LIST_GETTER = Object.class.getMethod("hashCode");
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
public static void replaceChildren(Object o, List<Object> newChildren) {
// Available if you need something like this. Would be used with
// something like:
/*
* public void walkJAXBElements(Object parent){
// Breadth first
List<Object> newChildren = new ArrayList<Object>();
List children = getChildren(parent);
if (children==null) {
log.warn("no children: " + parent.getClass().getName() );
} else {
for (Object o : getChildren(parent) ) {
// if its wrapped in jakarta.xml.bind.JAXBElement, get its value
o = XmlUtils.unwrap(o);
newChildren.addAll(this.apply(o));
}
}
// Replace list, so we'll traverse all the new sdts we've just created
replaceChildren(parent, newChildren);
for (Object o : getChildren(parent) ) {
this.apply(o);
if ( this.shouldTraverse(o) ) {
walkJAXBElements(o);
}
}
}
*/
//log.debug("Clearing " + o.getClass().getName() );
if (o instanceof org.docx4j.wml.ContentAccessor) {
((org.docx4j.wml.ContentAccessor) o).getContent().clear();
((org.docx4j.wml.ContentAccessor) o).getContent().addAll(newChildren);
} else if (o instanceof List /* eg org.docx4j.wml.ArrayListWml */) {
// a little unexpected? Would happen if you pass walkJAXBElements a list,
// and your walkJAXBElements invokes replaceChildren
// That is best avoided, since this was not added until after 6.1.0
log.debug("replaceChildren invoked on list object");
((List) o).clear();
((List) o).addAll(newChildren);
} else if (o instanceof org.docx4j.wml.SdtElement) {
((org.docx4j.wml.SdtElement) o).getSdtContent().getContent().clear();
((org.docx4j.wml.SdtElement) o).getSdtContent().getContent().addAll(newChildren);
} else if (o instanceof org.docx4j.wml.CTTxbxContent) {
((org.docx4j.wml.CTTxbxContent) o).getContent().clear();
((org.docx4j.wml.CTTxbxContent) o).getContent().addAll(newChildren);
} else if (o instanceof AlternateContent.Choice) {
// a walk in McMode.ALL (OpenDoPE's) edits a branch's content too (CR-051 section 10.5)
((AlternateContent.Choice) o).getAny().clear();
((AlternateContent.Choice) o).getAny().addAll(newChildren);
} else if (o instanceof AlternateContent.Fallback) {
((AlternateContent.Fallback) o).getAny().clear();
((AlternateContent.Fallback) o).getAny().addAll(newChildren);
} else {
log.info("Don't know how to replaceChildren in " + o.getClass().getName() );
if (o instanceof org.w3c.dom.Node) {
log.warn(" IGNORED " + ((org.w3c.dom.Node) o).getNodeName());
} else {
// log.warn(" IGNORED " + o.getClass().getName());
}
}
}
/**
* Use this if there is only a single object type (eg just P's)
* you are interested in doing something with.
*
* This method allows you to traverse just the main document
* part, or also headers/footers, footnotes/endnotes, and comments
* as well.
*
* @param wmlPackage
* @param bodyOnly
* @param visitor
*/
public static void visit(WordprocessingMLPackage wmlPackage,
boolean bodyOnly, TraversalUtilVisitor visitor) {
if (visitor != null) {
visit(wmlPackage, bodyOnly, new SingleTraversalUtilVisitorCallback(visitor));
}
}
/**
* Use this if there is only a single object type (eg just P's)
* you are interested in doing something with.
*
* This method is for traversing an arbitrary WML object (eg a table), as opposed to
* eg the main document part, or a header.
*
* @param parent
* @param visitor
*/
public static void visit(Object parent, TraversalUtilVisitor visitor) {
if (visitor != null) {
visit(parent, new SingleTraversalUtilVisitorCallback(visitor));
}
}
/**
* Use this if there is more than one object type (eg Tables and Paragraphs)
* you are interested in doing something with during the traversal.
*
* This method allows you to traverse just the main document
* part, or also headers/footers, footnotes/endnotes, and comments
* as well.
*
* @param wmlPackage
* @param bodyOnly
* @param visitorList
*/
public static void visit(WordprocessingMLPackage wmlPackage,
boolean bodyOnly, List<TraversalUtilVisitor> visitorList) {
CompoundTraversalUtilVisitorCallback callback = null;
if ((visitorList != null) && (!visitorList.isEmpty())) {
if (visitorList.size() > 1) {
visit(wmlPackage, bodyOnly,
new CompoundTraversalUtilVisitorCallback(visitorList));
} else {
visit(wmlPackage, bodyOnly, visitorList.get(0));
}
}
}
/**
* Use this if there is more than one object type (eg Tables and Paragraphs)
* you are interested in doing something with during the traversal.
*
* This method is for traversing an arbitrary WML object (eg a table), as opposed to
* eg the main document part, or a header.
*
* @param parent
* @param visitorList
*/
public static void visit(Object parent,
List<TraversalUtilVisitor> visitorList) {
CompoundTraversalUtilVisitorCallback callback = null;
if ((visitorList != null) && (!visitorList.isEmpty())) {
if (visitorList.size() > 1) {
visit(parent, new CompoundTraversalUtilVisitorCallback(
visitorList));
} else {
visit(parent, visitorList.get(0));
}
}
}
public static void visit(Object parent, Callback callback) {
if ((parent != null) && (callback != null)) {
callback.walkJAXBElements(parent);
}
}
/** As {@link #visit(Object, Callback)}, in this {@link McMode} (see
* {@link #TraversalUtil(Object, Callback, McMode)}). @since 17.2.0 */
public static void visit(Object parent, Callback callback, McMode mcMode) {
if (callback instanceof CallbackImpl) ((CallbackImpl) callback).setMcMode(mcMode);
visit(parent, callback);
}
/** As {@link #visit(Object, TraversalUtilVisitor)}, in this {@link McMode}. @since 17.2.0 */
public static void visit(Object parent, TraversalUtilVisitor visitor, McMode mcMode) {
if (visitor != null) {
visit(parent, new SingleTraversalUtilVisitorCallback(visitor), mcMode);
}
}
/** As {@link #visit(WordprocessingMLPackage, boolean, Callback)}, in this {@link McMode}. @since 17.2.0 */
public static void visit(WordprocessingMLPackage wmlPackage, boolean bodyOnly, Callback callback, McMode mcMode) {
if (callback instanceof CallbackImpl) ((CallbackImpl) callback).setMcMode(mcMode);
visit(wmlPackage, bodyOnly, callback);
}
/** As {@link #visit(WordprocessingMLPackage, boolean, TraversalUtilVisitor)}, in this {@link McMode}. @since 17.2.0 */
public static void visit(WordprocessingMLPackage wmlPackage, boolean bodyOnly, TraversalUtilVisitor visitor, McMode mcMode) {
if (visitor != null) {
visit(wmlPackage, bodyOnly, new SingleTraversalUtilVisitorCallback(visitor), mcMode);
}
}
/** As {@link #visit(WordprocessingMLPackage, boolean, List)}, in this {@link McMode}. @since 17.2.0 */
public static void visit(WordprocessingMLPackage wmlPackage, boolean bodyOnly, List<TraversalUtilVisitor> visitorList, McMode mcMode) {
if ((visitorList != null) && (!visitorList.isEmpty())) {
if (visitorList.size() > 1) {
visit(wmlPackage, bodyOnly, new CompoundTraversalUtilVisitorCallback(visitorList), mcMode);
} else {
visit(wmlPackage, bodyOnly, visitorList.get(0), mcMode);
}
}
}
public static void visit(WordprocessingMLPackage wmlPackage,
boolean bodyOnly, Callback callback) {
MainDocumentPart mainDocument = null;
RelationshipsPart relPart = null;
List<Relationship> relList = null;
List<Object> elementList = null;
if ((wmlPackage != null) && (callback != null)) {
mainDocument = wmlPackage.getMainDocumentPart();
callback.walkJAXBElements(mainDocument.getJaxbElement().getBody());
if (!bodyOnly) {
relPart = mainDocument.getRelationshipsPart();
relList = relPart.getRelationships().getRelationship();
for (Relationship rs : relList) {
elementList = null;
if (Namespaces.HEADER.equals(rs.getType())) {
elementList = ((HeaderPart) relPart.getPart(rs))
.getJaxbElement().getContent();
} else if (Namespaces.FOOTER.equals(rs.getType())) {
elementList = ((FooterPart) relPart.getPart(rs))
.getJaxbElement().getContent();
} else if (Namespaces.ENDNOTES.equals(rs.getType())) {
//elementList = ((EndnotesPart) relPart.getPart(rs)).getContent();
elementList = new ArrayList();
elementList.addAll(
((EndnotesPart) relPart.getPart(rs)).getJaxbElement().getEndnote() );
} else if (Namespaces.FOOTNOTES.equals(rs.getType())) {
//elementList = ((FootnotesPart) relPart.getPart(rs)).getContent();
elementList = new ArrayList();
elementList.addAll(
((FootnotesPart) relPart.getPart(rs)).getJaxbElement().getFootnote() );
} else if (Namespaces.COMMENTS.equals(rs.getType())) {
elementList = new ArrayList();
for (Comment comment : ((CommentsPart) relPart
.getPart(rs)).getJaxbElement().getComment()) {
elementList.addAll(comment.getContent());
}
}
if ((elementList != null) && (!elementList.isEmpty())) {
log.debug("Processing target: "
+ rs.getTarget() + ", type: " + rs.getType());
callback.walkJAXBElements(elementList);
}
}
}
}
}
// private void describeDrawing( org.docx4j.wml.Drawing d) {
//
// log.info("In wml.Drawing" );
//
// if ( d.getAnchorOrInline().get(0) instanceof Anchor ) {
//
// log.info(" ENCOUNTERED w:drawing/wp:anchor " );
// // That's all for now...
//
// } else if ( d.getAnchorOrInline().get(0) instanceof Inline ) {
//
// // Extract
// w:drawing/wp:inline/a:graphic/a:graphicData/pic:pic/pic:blipFill/a:blip/@r:embed
//
// Inline inline = (Inline )d.getAnchorOrInline().get(0);
//
// Pic pic = inline.getGraphic().getGraphicData().getPic();
//
// if (pic!=null) {
// log.info("image relationship: " + pic.getBlipFill().getBlip().getEmbed()
// );
// }
//
//
// } else {
//
// log.info(" Didn't get Inline :( How to handle " +
// d.getAnchorOrInline().get(0).getClass().getName() );
// }
//
// }
}
@@ -0,0 +1,246 @@
/*
* Copyright 2009, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jharrop, azerolo
*
*/
public class UnitsOfMeasurement {
private final static Logger log = LoggerFactory.getLogger(UnitsOfMeasurement.class);
public final static DecimalFormat format2DP;
public final static int DPI;
static {
format2DP = new DecimalFormat("##.##",
new DecimalFormatSymbols(Locale.ENGLISH));
DPI = Integer.parseInt(Docx4jProperties.getProperty("docx4j.DPI", "96"));
}
public static long twipToEMU(double twips) {
return Math.round(635 * twips);
}
public static int inchToTwip(float inch ) {
// 1440 twip = 1 inch;
return Math.round(inch*1440);
}
public static float twipToInch(int twip) {
return twip/1440.00f;
}
/**
* @since 3.0.0
*/
public static float twipToMm(int twip) {
return twip / 56.6928f;
}
public static int mmToTwip(float mm ) {
float inch = mm*0.0394f;
return inchToTwip(inch);
}
/**
* @since 3.0.0
*/
public static float twipToPoint(int twip) {
return twip / 20f;
}
/**
* @since 3.0.0
*/
public static int pointToTwip(float point ) {
return Math.round(20 * point);
}
/**
* @since 3.0.0
*/
public static int pxToTwip(float px) {
float inch = px/DPI;
return inchToTwip(inch);
}
/**
* Convert an inches value to twips and return as a double.
*/
public static double inchToTwipDouble(double inch) {
// 1440 twip = 1 inch;
return inch * 1440;
}
/**
* Convert a pixel value to twips and return as a double. This may be useful
* where the returned value will then be converted to another unit, and we
* don't want to lose precision due to rounding.
*/
public static double pxToTwipDouble(double px) {
double inch = px / DPI;
return inchToTwipDouble(inch);
}
/**
* 1440 twip = 1 inch;Try to guess whether inches or mm looks nicer
* @param left
* @return
*/
/**
* A twips value as a CSS/XSL-FO length, losslessly: whole inches as "Nin",
* otherwise points ("12pt", "35.4pt"; a twip is 0.05pt, so two decimals are exact).
*
* Before 17.0.5 this rounded to whole millimetres whenever the value was not a
* multiple of 1/80 inch, which lost up to 0.5mm (1.4pt) per value: a 708-twip
* header distance became "12mm" (12.49), 12pt paragraph spacing became "4mm"
* (11.34pt). Measured against Word (CR-001 harness), those losses were a
* visible part of the page layout error.
*/
public static String twipToBest(int leftL ) {
if (leftL % 1440 == 0) {
return (leftL / 1440) + "in";
}
if (leftL % 20 == 0) {
return (leftL / 20) + "pt";
}
String s = String.format(java.util.Locale.ROOT, "%.2f", leftL / 20f);
s = s.replaceAll("0+$", "").replaceAll("\\.$", "");
return s + "pt";
}
public static String rgbTripleToHex(float red, float green, float blue) {
return getHex(red) + getHex(green) + getHex(blue);
}
private static String getHex(float f) {
int i = Math.round(f);
String hexValue = Integer.toHexString(i);
if (i < 16) {
// Pad so we have 2 digits
return "0" + hexValue;
}
return hexValue;
}
/**
* @since 3.0.0
*/
public static String toHexColor(int color) {
String ret = Integer.toHexString(color).toUpperCase();
return (ret.length() < 6 ?
"000000".substring(0, 6 - ret.length()) + ret :
ret);
}
/**
* @since 3.0.0
*/
public static int combineColors(int fgColor, int bgColor, int pctFg) {
int resColor = 0;
if (pctFg < 1) {
resColor = bgColor;
}
else if (pctFg == 100) {
resColor = fgColor;
}
else {
int pctBg = 100 - pctFg;
resColor =
//Red
(((((((fgColor >> 16) & 0xff) * pctFg) +
(((bgColor >> 16) & 0xff) * pctBg))) / 100) << 16) |
//Green
(((((((fgColor >> 8) & 0xff) * pctFg) +
(((bgColor >> 8) & 0xff) * pctBg))) / 100) << 8) |
//Blue
(((((fgColor & 0xff) * pctFg) +
((bgColor & 0xff) * pctBg))) / 100);
}
return resColor;
}
private String calcHexColor(int value) {
String ret = Integer.toHexString(value).toUpperCase();
return (ret.length() < 6 ?
"000000".substring(0, 6 - ret.length()) + ret :
ret);
}
// public static void main(String[] args) throws Exception {
// System.out.println(format2DP.format(twipToInch(2235)));
// System.out.println(twipToBest(2235) );
// }
/** Word's 1/300 inch grid, in points: 0.24pt a cell, the unit its layout works in. */
private static final double BORDER_GRID_PT = 72.0 / 300.0;
/**
* The width Word inks a {@code w:sz} border: the eighths of a point it names, laid on
* Word's 1/300-inch grid and <b>truncated</b> to whole cells.
*
* <p>Measured on four Word goldens, five distinct widths, every one the floor:</p>
*
* <pre>
* w:sz named cells Word inks golden
* 4 0.50pt 2.083 0.480pt table-cell-measure, table-first-row-border
* 8 1.00pt 4.167 0.960pt page-top-space-before, table-first-row-border
* 12 1.50pt 6.250 1.440pt table-cell-measure
* 18 2.25pt 9.375 2.160pt border-hanging
* 24 3.00pt 12.500 2.880pt table-cell-measure
* </pre>
*
* <p>{@code w:sz} 24 is the one that settles the rounding: 3.00pt is <b>exactly</b> 12.5
* cells and Word inks 12, not 13, so it truncates rather than rounding half up. (Half to
* even would agree on all five; truncation is the simpler statement of the same readings.)</p>
*
* <p>Used by the XSL FO paths only. The paragraph border wrote millimetres to two
* decimals until 17.2.0 - {@code w:sz} 18 came out as 0.79mm = 2.2394pt against Word's
* 2.160 - and the table border wrote the named points, 0.50 where Word inks 0.480; both
* were part of the residue measured on every bar of the {@code border-hanging} golden
* (CR-001 batch 48 item 9 §2, batch 49 item 5). The CSS paths still write millimetres:
* a browser has no 1/300-inch grid to honour.</p>
*
* @param eighths the {@code w:sz}, in eighths of a point
* @since 17.2.0 (CR-001 batch 49 item 5)
*/
public static double eighthsToGridPt(int eighths) {
if (eighths <= 0) return 0;
return Math.floor((eighths / 8.0) / BORDER_GRID_PT) * BORDER_GRID_PT;
}
}
@@ -0,0 +1,59 @@
package org.docx4j;
import java.util.Properties;
import org.docx4j.jaxb.Context;
import org.docx4j.utils.ResourceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Version {
protected static Logger log = LoggerFactory.getLogger(Version.class);
private static Properties properties;
private static void init() {
properties = new Properties();
try {
properties.load(
ResourceUtils.getResource("docx4j_version.properties"));
} catch (Exception e) {
log.warn("Couldn't find/read docx4j_version.properties; " + e.getMessage());
}
}
private static String version;
public static String getDocx4jVersion() {
if (version==null) {
if (properties==null) {init();}
version = properties.getProperty("version");
}
return version;
}
private static String poweredBy;
public static String getPoweredBy(boolean isNewPkg) {
if (poweredBy==null) {
String vendor = System.getProperty("java.vendor");
if (vendor !=null
&& vendor.equals("Oracle Corporation") ) {
vendor = "Oracle";
}
String verb = isNewPkg ? "Created" : "Modified";
poweredBy = verb + " by docx4j " + Version.getDocx4jVersion()
+ " (Apache licensed) using " + Context.getJaxbImplementation() + " JAXB"
+ " in " + vendor + " Java " + System.getProperty("java.version")
+ " on " + System.getProperty("os.name") ;
}
return poweredBy;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,461 @@
package org.docx4j.anon;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import jakarta.xml.bind.JAXBElement;
import org.docx4j.TraversalUtil;
import org.docx4j.anon.AnonymizeResult.Action;
import org.docx4j.anon.JaxbGraphWalker.Visitor;
import org.docx4j.anon.PartsAnalyzer.Treatment;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.packages.PresentationMLPackage;
import org.docx4j.openpackaging.packages.SpreadsheetMLPackage;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.JaxbXmlPart;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.XmlPart;
import org.docx4j.openpackaging.parts.WordprocessingML.FooterPart;
import org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Anonymises a docx (or, since 17.2.1, a pptx or xlsx) in place: the text is scrambled,
* identities, references and metadata scrubbed, media replaced, and whatever
* cannot be made clean removed (STRICT, the default) or kept and reported (KEEP).
* <p>
* The guarantee (CR-019): a document this returns with {@code result.isClean()}
* contains no text from the original in any text-bearing part (scrambled per
* Unicode range); no author, initials, user id or presence information; no
* external target or field-instruction argument; no metadata beyond what the
* package needs to open; no media but placeholder pixels; no embedded object,
* chart data, diagram text, macro, custom XML or altChunk. What it keeps, by
* design, is the document's structure - paragraphs, runs, tables, sections,
* styles, numbering, fonts, sizes, the shape of fields and content controls -
* because that is what a layout, a corruption or a converter bug lives in.
* <p>
* One thing the structure does not keep is the conformance class: docx4j reads a
* strict (ISO/IEC 29500 Strict) package by converting each part to the
* transitional namespaces, and never writes strict, so an anonymised strict
* document is a transitional one. Nothing else about it changes, but a bug which
* is the strict dialect's own will not reproduce from the anonymised copy - ask
* for the original in that case.
* <p>
* Usage:
* <pre>
* WordprocessingMLPackage pkg = WordprocessingMLPackage.load(in, McLoadMode.PRESERVE);
* AnonymizeResult result = new Anonymize(pkg).go();
* if (result.isClean()) pkg.save(out);
* System.out.println(result.toJson());
* </pre>
* Set a font mapper on the package first if the non-Latin replacement characters
* should be chosen from the glyphs the document's fonts have (the CLI does).
* <p>
* For a pptx (CR-019 phase 2) the same walk covers the slides, layouts, masters,
* notes and handout master, the presentation (section names, custom shows, the
* modify verifier, the embedded-font list), legacy and 2018 comments with their
* authors, tags, table styles, charts and diagrams; media, OLE objects, ActiveX,
* ink, embedded fonts, VBA and the thumbnail go as in a docx. A pptx has no
* styles part and no font mapper, so non-Latin replacement characters stay in the
* character's Unicode block with no glyph check.
* <p>
* Load in {@link org.docx4j.jaxb.McLoadMode#PRESERVE} mode (as the CLI does): the output is a
* reproduction of the document, so a block-level {@code mc:AlternateContent} must come through
* whole rather than resolved to the branch Word reads (CR-051 section 3.2).
* <p>
* For an xlsx (CR-019 phase 3) a third visitor, {@link SpreadsheetScrubber},
* covers the workbook, sheets, shared strings, styles, tables, comments (legacy
* and threaded), connections, query tables and external links: strings are
* scrambled consistently (a table column still matches its header), numbers have
* their digits randomised ({@link #setKeepNumbers(boolean)} keeps them, decision
* 3), formulas are rewritten to compute over the result ({@link SmlFormulas}),
* sheets become {@code Sheet<n>} and defined names {@code n_<hash>}; pivot tables
* and caches, slicers, timelines and the data model are removed (their cells stay
* as values) whatever the mode; OLE, ActiveX, printer settings and the rich-value
* parts go in STRICT.
*/
public class Anonymize {
private static Logger log = LoggerFactory.getLogger(Anonymize.class);
/** What to do with a part the tool cannot make clean. */
public enum Mode {
/** remove it (with its relationships and the markup that pointed at it); the default */
STRICT,
/** keep it, report it, and never call the result clean */
KEEP
}
private final OpcPackage pkg;
private final Mode mode;
private boolean verify = true;
private boolean keepNumbers = false;
ScrambleText latinizer = null;
MarkupScrubber markupScrubber = null;
SpreadsheetScrubber spreadsheetScrubber = null;
DmlVmlAnalyzer dmlVmlAnalyzer = null;
Names names = null;
AnonymizeResult result;
public Anonymize(WordprocessingMLPackage wordMLPackage) {
this((OpcPackage) wordMLPackage, Mode.STRICT);
}
/**
* @since 17.2.0
*/
public Anonymize(WordprocessingMLPackage wordMLPackage, Mode mode) {
this((OpcPackage) wordMLPackage, mode);
}
/**
* @since 17.2.1
*/
public Anonymize(PresentationMLPackage pmlPackage, Mode mode) {
this((OpcPackage) pmlPackage, mode);
}
/**
* @since 17.2.1
*/
public Anonymize(SpreadsheetMLPackage smlPackage, Mode mode) {
this((OpcPackage) smlPackage, mode);
}
/**
* A docx, pptx or xlsx (as {@link OpcPackage#load(java.io.File)} returns it).
*
* @throws IllegalArgumentException for a package of another kind
* @since 17.2.1
*/
public Anonymize(OpcPackage pkg, Mode mode) {
if (!(pkg instanceof WordprocessingMLPackage) && !(pkg instanceof PresentationMLPackage)
&& !(pkg instanceof SpreadsheetMLPackage)) {
throw new IllegalArgumentException("only docx, pptx and xlsx are supported: "
+ (pkg == null ? "null" : pkg.getClass().getSimpleName()));
}
this.pkg = pkg;
this.mode = mode;
result = new AnonymizeResult();
}
/**
* STRICT.
*
* @since 17.2.1
*/
public Anonymize(OpcPackage pkg) {
this(pkg, Mode.STRICT);
}
/**
* Whether {@link #go()} extracts the tokens of the document before and after
* and checks that none survived ({@link Verify}). On by default; it costs a
* marshal of every part twice.
*
* @since 17.2.0
*/
public void setVerify(boolean verify) {
this.verify = verify;
}
/**
* Whether a workbook's numbers (cell values, formula constants, filter and
* input-cell values) keep their digits. Off by default: numbers are usually
* the confidential part of a spreadsheet, and a layout or corruption bug rarely
* depends on their values (CR-019 decision 3); on for the bug that does (a
* number format, a formula result). No effect on a docx or pptx.
*
* @since 17.2.1
*/
public void setKeepNumbers(boolean keepNumbers) {
this.keepNumbers = keepNumbers;
}
public AnonymizeResult go() throws Docx4JException {
result.mode = mode;
if (pkg.isWasStrict()) {
// docx4j reads a strict package by converting each part to the transitional
// namespaces, and never writes strict; the report says so, because a bug which is
// the strict dialect's own will not reproduce from the anonymised copy
result.notes.add("the input was ISO/IEC 29500 Strict; docx4j converts on read and writes transitional, "
+ "so this output is a transitional package");
}
Verify.Extraction before = verify ? Verify.extract(pkg) : null;
names = new Names(pkg);
// the visitors first: the text scrambler's font selection reads the font table and
// its embedded fonts, which STRICT is about to remove
latinizer = new ScrambleText(pkg, names);
markupScrubber = new MarkupScrubber(names, mode == Mode.STRICT, result.notes::add);
if (pkg instanceof SpreadsheetMLPackage) {
latinizer.setKeepNumbers(keepNumbers);
spreadsheetScrubber = new SpreadsheetScrubber(latinizer, names, mode == Mode.STRICT, result.notes::add,
markupScrubber.objectPreviews);
// a chart's c:f in a workbook keeps pointing at its (scrambled) cells
latinizer.setFormulas(spreadsheetScrubber.formulas()::scrub);
}
// the inventory (fields present, VML, objects of interest), read before the scramble;
// it walks the WordprocessingML story parts, so a pptx has none
if (pkg instanceof WordprocessingMLPackage) {
detectDmlVmlContent();
}
// what each part is
Map<Part, Treatment> treatments = new LinkedHashMap<Part, Treatment>();
for (Entry<PartName, Part> entry : pkg.getParts().getParts().entrySet()) {
treatments.put(entry.getValue(), PartsAnalyzer.classify(entry.getValue()));
}
// remove what goes: always-removed parts, and in STRICT mode what cannot be made clean
removeParts(treatments);
// metadata
MetadataScrubber metadata = new MetadataScrubber(pkg);
metadata.scrubDocProps();
for (Entry<Part, Treatment> e : treatments.entrySet()) {
if (e.getValue() == Treatment.METADATA && pkg.getParts().get(e.getKey().getPartName()) != null) {
result.record(e.getKey(), Action.CLEARED, "descriptive properties, identities and dates cleared");
}
}
// text, identities, references, embedded-object markup: one walk over every JAXB part
walkParts(treatments);
// relationships to outside the package
result.externalTargetsReplaced = metadata.scrubExternalTargets();
// media
replaceMedia(treatments);
result.authorsRenamed = names.authorCount();
result.hasGreek = latinizer.hasGreek;
result.hasCyrillic = latinizer.hasCyrillic;
result.hasHebrew = latinizer.hasHebrew;
result.hasArabic = latinizer.hasArabic;
result.hasHiragana = latinizer.hasHiragana;
result.hasKatakana = latinizer.hasKatakana;
result.hasCJK = latinizer.hasCJK;
if (before != null) {
Verify.Extraction after = Verify.extract(pkg);
result.leaks.addAll(Verify.compare(before, after));
result.verified = result.leaks.isEmpty();
}
return result;
}
private void removeParts(Map<Part, Treatment> treatments) {
for (Entry<Part, Treatment> e : treatments.entrySet()) {
Part p = e.getKey();
if (pkg.getParts().get(p.getPartName()) == null) continue; // went with an earlier removal
if (e.getValue() == Treatment.REMOVE) {
List<PartName> removed = MediaReplacer.removePart(pkg, p);
result.record(p, Action.REMOVED, "always removed: " + p.getClass().getSimpleName());
recordCascade(removed, p);
} else if (e.getValue() == Treatment.UNSCRUBBABLE) {
result.unsafeParts.add(p);
if (mode == Mode.STRICT) {
List<PartName> removed = MediaReplacer.removePart(pkg, p);
result.record(p, Action.REMOVED, "cannot be made clean: " + p.getClass().getSimpleName());
recordCascade(removed, p);
} else {
result.record(p, Action.KEPT_UNSAFE, "cannot be made clean: " + p.getClass().getSimpleName());
}
}
}
}
private void recordCascade(List<PartName> removed, Part p) {
for (PartName name : removed) {
if (!name.equals(p.getPartName())) {
result.record(name.getName(), "", Action.REMOVED, "target of " + p.getPartName().getName());
}
}
}
private void walkParts(Map<Part, Treatment> treatments) throws Docx4JException {
final Visitor composite = new Visitor() {
@Override
public JaxbGraphWalker.Action visit(Object o, JAXBElement<?> wrapper) {
JaxbGraphWalker.Action a = latinizer.visit(o, wrapper);
JaxbGraphWalker.Action b = markupScrubber.visit(o, wrapper);
JaxbGraphWalker.Action c = spreadsheetScrubber == null ? JaxbGraphWalker.Action.CONTINUE : spreadsheetScrubber.visit(o, wrapper);
if (a == JaxbGraphWalker.Action.REMOVE || b == JaxbGraphWalker.Action.REMOVE || c == JaxbGraphWalker.Action.REMOVE) return JaxbGraphWalker.Action.REMOVE;
if (a == JaxbGraphWalker.Action.REPLACE || b == JaxbGraphWalker.Action.REPLACE) return JaxbGraphWalker.Action.REPLACE;
if (a == JaxbGraphWalker.Action.SKIP_CHILDREN || b == JaxbGraphWalker.Action.SKIP_CHILDREN || c == JaxbGraphWalker.Action.SKIP_CHILDREN) return JaxbGraphWalker.Action.SKIP_CHILDREN;
return JaxbGraphWalker.Action.CONTINUE;
}
@Override
public Object replacement() {
return markupScrubber.replacement();
}
};
for (Entry<Part, Treatment> e : treatments.entrySet()) {
Part p = e.getKey();
Treatment t = e.getValue();
if (pkg.getParts().get(p.getPartName()) == null) continue; // removed
if (t == Treatment.METADATA || t == Treatment.REPLACE_IMAGE) continue;
if (!(p instanceof JaxbXmlPart)) {
if (t == Treatment.SCRUB && p instanceof XmlPart) {
// a DOM part the table names: the 2018 PowerPoint comments and authors
scrubDom((XmlPart) p);
} else if (t == Treatment.SAFE) {
result.record(p, Action.KEPT, "structure");
}
continue;
}
JaxbXmlPart<?> jp = (JaxbXmlPart<?>) p;
Object contents;
try {
contents = jp.getContents();
} catch (Exception ex) {
log.warn(p.getPartName().getName() + " could not be read: " + ex);
contents = null;
}
if (contents == null) {
result.unsafeParts.add(p);
if (mode == Mode.STRICT) {
MediaReplacer.removePart(pkg, p);
result.record(p, Action.REMOVED, "could not be read, so could not be scrubbed");
} else {
result.record(p, Action.KEPT_UNSAFE, "could not be read, so could not be scrubbed");
}
continue;
}
log.debug("Scrubbing " + p.getPartName().getName());
latinizer.latinText = null;
markupScrubber.setCurrentPart(p);
if (spreadsheetScrubber != null) spreadsheetScrubber.setCurrentPart(p);
new JaxbGraphWalker(composite).walk(contents);
if (contents instanceof org.xlsx4j.sml.CTConnections && ((org.xlsx4j.sml.CTConnections) contents).getConnection().isEmpty()) {
// every connection was a data-model or Power Query one: an empty part is no use
MediaReplacer.removePart(pkg, p);
result.record(p, Action.REMOVED, "no connection left after the data-model and Power Query ones");
continue;
}
if (t == Treatment.SCRUB) {
result.record(p, Action.SCRUBBED, null);
} else if (t == Treatment.SAFE) {
result.record(p, Action.KEPT, "structure (walked)");
}
// an UNSCRUBBABLE JAXB part kept in KEEP mode was recorded as KEPT_UNSAFE already;
// the walk scrubbed what it recognised in it, but it is not vouched for
}
}
private void scrubDom(XmlPart p) {
org.w3c.dom.Document doc;
try {
doc = p.getDocument();
} catch (Exception ex) {
log.warn(p.getPartName().getName() + " could not be read: " + ex);
doc = null;
}
if (doc == null) {
result.unsafeParts.add(p);
if (mode == Mode.STRICT) {
MediaReplacer.removePart(pkg, p);
result.record(p, Action.REMOVED, "could not be read, so could not be scrubbed");
} else {
result.record(p, Action.KEPT_UNSAFE, "could not be read, so could not be scrubbed");
}
return;
}
log.debug("Scrubbing (DOM) " + p.getPartName().getName());
new ModernCommentsScrubber(names, latinizer).scrub(doc.getDocumentElement());
result.record(p, Action.SCRUBBED, "2018 comments: authors and persons renamed, dates fixed, text scrambled");
}
private void replaceMedia(Map<Part, Treatment> treatments) throws Docx4JException {
MediaReplacer media = new MediaReplacer(pkg, markupScrubber.objectPreviews);
for (Entry<Part, Treatment> e : treatments.entrySet()) {
Part p = e.getKey();
if (e.getValue() != Treatment.REPLACE_IMAGE) continue;
if (pkg.getParts().get(p.getPartName()) == null) continue; // went with a removed part
result.record(p, Action.REPLACED, media.replace(p));
}
}
// ---- the inventory walk (pre-17.2.0), kept for its report
private void detectDmlVmlContent() throws InvalidFormatException {
dmlVmlAnalyzer = new DmlVmlAnalyzer();
WordprocessingMLPackage pkg = (WordprocessingMLPackage) this.pkg;
detectDmlVml(pkg.getMainDocumentPart());
for (Entry<PartName, Part> entry : new ArrayList<Entry<PartName, Part>>(pkg.getParts().getParts().entrySet())) {
Part p = entry.getValue();
if (p instanceof HeaderPart) {
detectDmlVml((HeaderPart) p);
}
if (p instanceof FooterPart) {
detectDmlVml((FooterPart) p);
}
}
if (pkg.getMainDocumentPart().getFootnotesPart() != null) {
detectDmlVml(pkg.getMainDocumentPart().getFootnotesPart());
}
if (pkg.getMainDocumentPart().getEndNotesPart() != null) {
detectDmlVml(pkg.getMainDocumentPart().getEndNotesPart());
}
if (pkg.getMainDocumentPart().getCommentsPart() != null) {
detectDmlVml(pkg.getMainDocumentPart().getCommentsPart());
}
}
public void detectDmlVml(JaxbXmlPart p) {
log.debug("Inspecting " + p.getPartName().getName());
Object contents;
try {
contents = p.getContents();
} catch (Docx4JException e) {
log.warn(p.getPartName().getName() + " could not be read: " + e);
return;
}
dmlVmlAnalyzer.reinit();
dmlVmlAnalyzer.setPart(p);
// CR-021: ALL - a shape in any branch must be inspected
new TraversalUtil(contents, dmlVmlAnalyzer, org.docx4j.jaxb.McMode.ALL);
result.unsafeObjectsByPart.put(p, dmlVmlAnalyzer.unsafeObjects);
if (dmlVmlAnalyzer.unsafeObjects.size() > 0) {
result.anyUnsafeObjects = true;
}
result.inventoryObjectsByPart.put(p, dmlVmlAnalyzer.inventoryObjects);
if (!result.containsVML) {
result.containsVML = dmlVmlAnalyzer.containsVML;
}
result.fieldsPresent.addAll(dmlVmlAnalyzer.fieldsPresent);
}
}
@@ -0,0 +1,136 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.jaxb.McLoadMode;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
/**
* The command line:
* <pre>
* java -cp "docx4j-core.jar:lib/*" org.docx4j.anon.AnonymizeCli in.docx out.docx [--keep] [--keep-numbers] [--json report.json] [--no-verify] [--no-fonts]
* </pre>
* (docx4j-core and a JAXB runtime such as docx4j-JAXB-ReferenceImpl on the
* classpath; the class was the docx4j-docx-anon jar's Main-Class until the
* anonymiser moved into core in 17.2.1). The input may be a docx or, since
* 17.2.1, a pptx or xlsx (the package decides, not the extension: docm, dotx,
* pptm, ppsx, potx, xlsm and xltx are the same).
* <ul>
* <li>{@code --keep-numbers}: a workbook's numbers keep their digits (by default
* they are randomised; CR-019 decision 3).</li>
* <li>{@code --keep}: KEEP mode - parts the tool cannot make clean stay, and are
* reported; the default is STRICT, which removes them.</li>
* <li>{@code --json file}: write the report there (it is always printed).</li>
* <li>{@code --no-verify}: skip the before/after token check.</li>
* <li>{@code --no-fonts}: do not discover the system's fonts (faster; the
* non-Latin replacement characters are then not checked against the document's
* fonts' glyphs). A pptx has no font mapper, so this makes no difference there.</li>
* </ul>
* A strict (ISO/IEC 29500 Strict) input is written out transitional, because that
* is how docx4j reads one; see {@link Anonymize}.
* <p>
* The output is written whether or not the result is clean (in KEEP mode it
* never is); the exit code is 0 only when {@code result.isClean()}, 1 when not,
* 2 for a usage error, 3 when the document could not be processed.
*
* @since 17.2.0
*/
public class AnonymizeCli {
public static void main(String[] args) throws Exception {
System.exit(run(args));
}
static int run(String[] args) {
String in = null, out = null, json = null;
Anonymize.Mode mode = Anonymize.Mode.STRICT;
boolean verify = true, fonts = true, keepNumbers = false;
for (int i = 0; i < args.length; i++) {
String a = args[i];
if (a.equals("--keep")) {
mode = Anonymize.Mode.KEEP;
} else if (a.equals("--keep-numbers")) {
keepNumbers = true;
} else if (a.equals("--json")) {
if (i + 1 >= args.length) return usage("--json needs a file");
json = args[++i];
} else if (a.equals("--no-verify")) {
verify = false;
} else if (a.equals("--no-fonts")) {
fonts = false;
} else if (a.startsWith("--")) {
return usage("unknown option " + a);
} else if (in == null) {
in = a;
} else if (out == null) {
out = a;
} else {
return usage("too many arguments");
}
}
if (in == null || out == null) return usage(null);
AnonymizeResult result;
try {
// preserve: the output reproduces the document that caused a problem, every
// mc:AlternateContent branch included (CR-051 section 3.2, D5)
OpcPackage pkg = OpcPackage.load(new File(in), McLoadMode.PRESERVE);
if (fonts && pkg instanceof WordprocessingMLPackage) {
((WordprocessingMLPackage) pkg).setFontMapper(new IdentityPlusMapper());
}
Anonymize anon = new Anonymize(pkg, mode);
anon.setVerify(verify);
anon.setKeepNumbers(keepNumbers);
result = anon.go();
try (OutputStream os = new FileOutputStream(out)) {
pkg.save(os);
}
String report = result.toJson();
if (json != null) {
Files.write(new File(json).toPath(), report.getBytes(StandardCharsets.UTF_8));
}
System.out.println(report);
} catch (Exception e) {
System.err.println("docx4j anon: " + e);
e.printStackTrace(System.err);
return 3;
}
System.err.println(result.isClean() ? "clean" : "NOT clean - see the report");
return result.isClean() ? 0 : 1;
}
private static int usage(String problem) {
if (problem != null) System.err.println(problem);
System.err.println("usage: AnonymizeCli in.docx|in.pptx|in.xlsx out [--keep] [--keep-numbers] [--json report.json] [--no-verify] [--no-fonts]");
return 2;
}
}
@@ -0,0 +1,322 @@
package org.docx4j.anon;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.parts.Part;
/**
* What {@link Anonymize#go()} did, and whether the result is clean.
* <p>
* Since 17.2.0 (CR-019) the single answer is {@link #isClean()}: true only when
* every part was scrubbed, replaced or removed, nothing was kept unsafe, and the
* verification (if it ran) found no token of the original surviving. The
* per-part record is {@link #getActions()}, and {@link #toJson()} is the
* machine-readable report the CLI writes.
*/
public class AnonymizeResult {
/** What was done with a part. */
public enum Action {
/** text scrambled, identities and references scrubbed */
SCRUBBED,
/** metadata fields cleared */
CLEARED,
/** image replaced by placeholder pixels */
REPLACED,
/** part removed, with its relationships */
REMOVED,
/** structure only: left as it was */
KEPT,
/** could not be made clean and was kept (KEEP mode, or a part which failed to load): the result is not clean */
KEPT_UNSAFE
}
/** One part's record. */
public static class PartAction {
public final String partName;
public final String partClass;
public final Action action;
public final String reason;
PartAction(String partName, String partClass, Action action, String reason) {
this.partName = partName;
this.partClass = partClass;
this.action = action;
this.reason = reason;
}
@Override
public String toString() {
return partName + ": " + action + (reason == null ? "" : " (" + reason + ")");
}
}
Anonymize.Mode mode;
final List<PartAction> actions = new ArrayList<PartAction>();
final List<String> notes = new ArrayList<String>();
int externalTargetsReplaced = 0;
int authorsRenamed = 0;
Boolean verified = null; // null: verification did not run
final List<Verify.Leak> leaks = new ArrayList<Verify.Leak>();
public boolean hasGreek = false;
public boolean hasCyrillic = false;
public boolean hasHebrew = false;
public boolean hasArabic = false;
public boolean hasHiragana = false;
public boolean hasKatakana = false;
public boolean hasCJK = false;
void record(Part p, Action action, String reason) {
actions.add(new PartAction(p.getPartName().getName(), p.getClass().getSimpleName(), action, reason));
}
void record(String partName, String partClass, Action action, String reason) {
actions.add(new PartAction(partName, partClass, action, reason));
}
public Anonymize.Mode getMode() {
return mode;
}
/** Per part: what was done and why. */
public List<PartAction> getActions() {
return actions;
}
/**
* Element-level removals (w:altChunk, o:OLEObject, w:mailMerge ...), one line
* each, and anything else the report should say about the whole document - the
* conversion of a strict package, for one.
*/
public List<String> getNotes() {
return notes;
}
public int getExternalTargetsReplaced() {
return externalTargetsReplaced;
}
public int getAuthorsRenamed() {
return authorsRenamed;
}
/** The parts kept although the tool could not make them clean. */
public List<PartAction> getKeptUnsafe() {
List<PartAction> result = new ArrayList<PartAction>();
for (PartAction a : actions) {
if (a.action == Action.KEPT_UNSAFE) result.add(a);
}
return result;
}
/** null if verification did not run; else whether it found no surviving token. */
public Boolean getVerified() {
return verified;
}
/** The tokens of the original which survived, where. Empty when clean. */
public List<Verify.Leak> getLeaks() {
return leaks;
}
/**
* The guarantee: no part kept unsafe, no unsafe object, and - when
* verification ran - no token of the original found in the output.
*/
public boolean isClean() {
return getKeptUnsafe().isEmpty()
&& !anyUnsafeObjects
&& (verified == null || verified.booleanValue());
}
/**
* @deprecated since 17.2.0, use {@link #isClean()}
*/
@Deprecated
public boolean isOK() {
return isClean();
}
/** A JSON document: mode, clean, verified, the actions, the notes, the leaks. */
public String toJson() {
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" \"mode\": ").append(json(mode == null ? null : mode.name())).append(",\n");
sb.append(" \"clean\": ").append(isClean()).append(",\n");
sb.append(" \"verified\": ").append(verified == null ? "null" : verified.toString()).append(",\n");
sb.append(" \"externalTargetsReplaced\": ").append(externalTargetsReplaced).append(",\n");
sb.append(" \"authorsRenamed\": ").append(authorsRenamed).append(",\n");
sb.append(" \"scripts\": {");
sb.append("\"greek\": ").append(hasGreek).append(", \"cyrillic\": ").append(hasCyrillic)
.append(", \"hebrew\": ").append(hasHebrew).append(", \"arabic\": ").append(hasArabic)
.append(", \"hiragana\": ").append(hasHiragana).append(", \"katakana\": ").append(hasKatakana)
.append(", \"cjk\": ").append(hasCJK).append("},\n");
sb.append(" \"parts\": [\n");
for (int i = 0; i < actions.size(); i++) {
PartAction a = actions.get(i);
sb.append(" {\"part\": ").append(json(a.partName))
.append(", \"class\": ").append(json(a.partClass))
.append(", \"action\": ").append(json(a.action.name()))
.append(", \"reason\": ").append(json(a.reason)).append("}");
sb.append(i + 1 < actions.size() ? ",\n" : "\n");
}
sb.append(" ],\n");
sb.append(" \"notes\": [");
for (int i = 0; i < notes.size(); i++) {
sb.append(i == 0 ? "\n " : ",\n ").append(json(notes.get(i)));
}
sb.append(notes.isEmpty() ? "],\n" : "\n ],\n");
sb.append(" \"leaks\": [");
for (int i = 0; i < leaks.size(); i++) {
Verify.Leak l = leaks.get(i);
sb.append(i == 0 ? "\n " : ",\n ")
.append("{\"part\": ").append(json(l.partName))
.append(", \"where\": ").append(json(l.where))
.append(", \"token\": ").append(json(l.token)).append("}");
}
sb.append(leaks.isEmpty() ? "]\n" : "\n ]\n");
sb.append("}\n");
return sb.toString();
}
static String json(String s) {
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (c < 0x20) {
sb.append(String.format("\\u%04x", (int) c));
} else {
sb.append(c);
}
}
}
return sb.append('"').toString();
}
// ---- the pre-17.2.0 inventory, still populated
/**
* The parts the tool could not make clean (in STRICT mode they were removed,
* so this is the record of what went; in KEEP mode they are still in the package).
*/
public HashSet<Part> getUnsafeParts() {
return unsafeParts;
}
HashSet<Part> unsafeParts = new HashSet<Part>();
/**
* Objects flagged by the inventory walk, by story part.
*/
public HashMap<Part, Set<Object>> getUnsafeObjectsByPart() {
return unsafeObjectsByPart;
}
HashMap<Part, Set<Object>> unsafeObjectsByPart = new HashMap<Part, Set<Object>>();
boolean anyUnsafeObjects = false;
public boolean hasAnyUnsafeObjects() {
return anyUnsafeObjects;
}
/**
* Misc interesting objects, by story part, for further consideration
*/
public HashMap<Part, Set<Object>> getInventoryObjectsByPart() {
return inventoryObjectsByPart;
}
HashMap<Part, Set<Object>> inventoryObjectsByPart = new HashMap<Part, Set<Object>>();
/**
* Whether this docx contains VML
*/
public boolean containsVML() {
return containsVML;
}
boolean containsVML = false;
HashSet<String> fieldsPresent = new HashSet<String>();
/** The field instructions found (before scrubbing). */
public HashSet<String> getFieldsPresent() {
return fieldsPresent;
}
public String reportUnsafeObjects() {
StringBuilder sb = new StringBuilder();
if (hasAnyUnsafeObjects()) {
sb.append("The following objects may leak info: \n");
for (Entry<Part, Set<Object>> entry : getUnsafeObjectsByPart().entrySet()) {
Part p = entry.getKey();
if (!entry.getValue().isEmpty()) {
sb.append(p.getPartName().getName() + ", of type " + p.getClass().getName() + "\n");
for (Object o : entry.getValue()) {
if (o instanceof String) {
sb.append(o + "\n");
} else {
sb.append(o.getClass().getName());
try {
sb.append(XmlUtils.marshaltoString(o) + "\n");
} catch (Exception e) {
sb.append("\n");
}
}
}
}
}
}
return sb.toString();
}
/** A human-readable summary: clean or not, and why. */
public String summary() {
StringBuilder sb = new StringBuilder();
sb.append(isClean() ? "CLEAN" : "NOT CLEAN").append(" (mode ").append(mode).append(")\n");
for (PartAction a : actions) {
sb.append(" ").append(a).append("\n");
}
for (String n : notes) {
sb.append(" - ").append(n).append("\n");
}
if (externalTargetsReplaced > 0) {
sb.append(" external targets replaced: ").append(externalTargetsReplaced).append("\n");
}
if (authorsRenamed > 0) {
sb.append(" authors renamed: ").append(authorsRenamed).append("\n");
}
if (verified != null) {
sb.append(" verified: ").append(verified).append(leaks.isEmpty() ? "" : ", leaks: " + leaks.size()).append("\n");
for (Verify.Leak l : leaks) {
sb.append(" ").append(l).append("\n");
}
}
sb.append(reportUnsafeObjects());
return sb.toString();
}
}
@@ -0,0 +1,516 @@
package org.docx4j.anon;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBElement;
import org.docx4j.TraversalUtil.CallbackImpl;
import org.docx4j.XmlUtils;
import org.docx4j.dml.CTBlip;
import org.docx4j.dml.CTHyperlink;
import org.docx4j.dml.CTNonVisualDrawingProps;
import org.docx4j.dml.diagram.CTDataModel;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.parts.JaxbXmlPart;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.WordprocessingML.ImageBmpPart;
import org.docx4j.openpackaging.parts.WordprocessingML.ImageGifPart;
import org.docx4j.openpackaging.parts.WordprocessingML.ImageJpegPart;
import org.docx4j.openpackaging.parts.WordprocessingML.ImagePngPart;
import org.docx4j.openpackaging.parts.WordprocessingML.ImageTiffPart;
import org.docx4j.openpackaging.parts.relationships.Namespaces;
import org.docx4j.vml.CTImageData;
import org.docx4j.wml.CTObject;
import org.docx4j.wml.FldChar;
import org.docx4j.wml.Pict;
import org.docx4j.wml.SdtBlock;
import org.docx4j.wml.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This will detect DrawingML or VML which does anything more than
* link to a safe image (ie one we've replaced)
*
* @author jharrop
*
*/
public class DmlVmlAnalyzer extends CallbackImpl {
private static Logger log = LoggerFactory.getLogger(DmlVmlAnalyzer.class);
private JaxbXmlPart sourcePart;
public void setPart(JaxbXmlPart p) {
this.sourcePart = p;
}
/**
* Objects we might not anonymise
*/
HashSet<Object> unsafeObjects = null;
/**
* Objects it is interesting to note are present
*/
HashSet<Object> inventoryObjects = null;
HashSet<String> fieldsPresent = null;
boolean containsVML;
public void reinit() {
unsafeObjects = new HashSet<Object>();
inventoryObjects = new HashSet<Object>();
containsVML = false;
fieldsPresent = new HashSet<String>();
}
@Override
public boolean shouldTraverse(Object o) {
if (o instanceof org.docx4j.math.CTOMathPara) {
// since 17.2.0 (CR-019) the m:t text is scrambled like any other, so math is
// inventory, not unsafe
inventoryObjects.add(o);
return false;
}
return true;
}
@Override
public List<Object> apply(Object o2) {
// System.out.println(o.getClass().getName());
if (o2 instanceof JAXBElement) {
// record field instruction
if (((JAXBElement)o2).getName().getLocalPart().equals("instrText")) {
Text instr = (Text)XmlUtils.unwrap(o2);
fieldsPresent.add(instr.getValue());
}
}
Object o = XmlUtils.unwrap(o2);
if (o instanceof org.docx4j.vml.CTImageData) {
// remove its title
((CTImageData)o).setTitle("foo");
if ( ((CTImageData)o).getRelid()!=null ) {
String rId = ((CTImageData)o).getRelid();
Part embeddedPart = sourcePart.getRelationshipsPart().getPart(rId);
if (embeddedPart instanceof ImagePngPart
|| embeddedPart instanceof ImageGifPart
|| embeddedPart instanceof ImageJpegPart
|| embeddedPart instanceof ImageBmpPart
|| embeddedPart instanceof ImageTiffPart
// Others treated as unsafe
) {
// We've handled this
} else {
// Unsafe, but noted elsewhere
}
}
}
return null;
}
public List<Object> getChildren(Object o2) {
if (o2==null) {
log.warn("null passed to getChildrenImpl");
return null;
}
Object o = XmlUtils.unwrap(o2);
log.debug("getting children of " + o.getClass().getName() );
if (o instanceof org.docx4j.wml.Text) return null;
// Short circuit for common elements
if (o instanceof List) {
// Handy if you have your own list of objects you wish to process
return (List<Object>) o;
} else if (o instanceof org.docx4j.wml.ContentAccessor) {
return ((org.docx4j.wml.ContentAccessor) o).getContent();
} else if (o instanceof org.docx4j.wml.SdtElement) {
return ((org.docx4j.wml.SdtElement) o).getSdtContent().getContent();
} else if (o instanceof org.docx4j.mce.AlternateContent) {
// the walk's mode (ALL, from Anonymize): reflection would find getChoice() alone,
// and a VML Fallback's o:title would never be scrubbed (CR-051 section 10.5)
return org.docx4j.jaxb.McSelection.branches((org.docx4j.mce.AlternateContent) o, getMcMode());
} else if (o instanceof org.docx4j.dml.wordprocessingDrawing.Anchor) {
// Similar to wordprocessingDrawing.Inline below
log.debug( sourcePart.getPartName().getName() + "\n"
+ XmlUtils.marshaltoString(o, true, true, Context.jc,
"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "anchor", o.getClass()));
org.docx4j.dml.wordprocessingDrawing.Anchor anchor = (org.docx4j.dml.wordprocessingDrawing.Anchor) o;
List<Object> artificialList = new ArrayList<Object>();
CTNonVisualDrawingProps drawingProps = anchor.getDocPr();
if (drawingProps != null) {
handleCTNonVisualDrawingProps(drawingProps, artificialList);
}
if (anchor.getGraphic() == null) {
log.warn("TODO: Handle case of no a:graphic: " + XmlUtils.marshaltoString(o, true, true, Context.jc,
"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "anchor", o.getClass()));
} else {
log.debug("found a:graphic");
org.docx4j.dml.Graphic graphic = anchor.getGraphic();
if (graphic.getGraphicData() == null) {
log.warn("TODO: Handle case of no a:graphicData: " + XmlUtils.marshaltoString(o, true, true, Context.jc, "foo", "Inline", o.getClass()));
} else {
List l = handleGraphicData(graphic.getGraphicData());
if (l!=null) {
artificialList.addAll(l);
}
}
}
if (!artificialList.isEmpty())
return artificialList;
} else if (o instanceof org.docx4j.dml.wordprocessingDrawing.Inline) {
// Done
/*
<ns34:Inline distR="0" distL="0" distB="0" distT="0" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:ns21="urn:schemas-microsoft-com:office:powerpoint" xmlns:ns23="http://schemas.microsoft.com/office/2006/coverPageProps" xmlns:dsp="http://schemas.microsoft.com/office/drawing/2008/diagram" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:odx="http://opendope.org/xpaths" xmlns:odgm="http://opendope.org/SmartArt/DataHierarchy" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:dgm="http://schemas.openxmlformats.org/drawingml/2006/diagram" xmlns:ns17="urn:schemas-microsoft-com:office:excel" xmlns:b="http://schemas.openxmlformats.org/officeDocument/2006/bibliography" xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:odi="http://opendope.org/components" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:ns34="foo" xmlns:ns9="http://schemas.openxmlformats.org/schemaLibrary/2006/main" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:ns32="http://schemas.openxmlformats.org/drawingml/2006/compatibility" xmlns:ns33="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:ns12="http://schemas.openxmlformats.org/drawingml/2006/chartDrawing" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:odq="http://opendope.org/questions" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:odc="http://opendope.org/conditions" xmlns:oda="http://opendope.org/answers">
<wp:extent cy="2362200" cx="3238500"/>
<wp:effectExtent b="0" r="0" t="0" l="19050"/>
<wp:docPr descr="C:\Documents and Settings\Jason Harrop\My Documents\tmp-test-docs\pangolin.jpeg" name="Picture 1" id="1"/>
<wp:cNvGraphicFramePr>
<a:graphicFrameLocks noChangeAspect="true"/>
</wp:cNvGraphicFramePr>
<a:graphic>
<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
*/
org.docx4j.dml.wordprocessingDrawing.Inline inline = (org.docx4j.dml.wordprocessingDrawing.Inline) o;
List<Object> artificialList = new ArrayList<Object>();
CTNonVisualDrawingProps drawingProps = inline.getDocPr();
if (drawingProps != null) {
// handle <wp:docPr descr="
handleCTNonVisualDrawingProps(drawingProps, artificialList);
}
if (inline.getGraphic() == null) {
log.warn("TODO: Handle case of no a:graphic: " + XmlUtils.marshaltoString(o, true, true, Context.jc, "foo", "Inline", o.getClass()));
} else {
log.debug("found a:graphic");
org.docx4j.dml.Graphic graphic = inline.getGraphic();
if (graphic.getGraphicData() == null) {
log.warn("TODO: Handle case of no a:graphicData: " + XmlUtils.marshaltoString(o, true, true, Context.jc, "foo", "Inline", o.getClass()));
} else {
List l = handleGraphicData(graphic.getGraphicData());
if (l!=null) {
artificialList.addAll(l);
}
}
return artificialList;
}
if (!artificialList.isEmpty())
return artificialList;
} else if (o instanceof Pict) {
/*
<w:pict>
<v:shapetype >
:
<v:shape
*/
log.debug(XmlUtils.marshaltoString(o));
return ((Pict)o).getAnyAndAny();
} else if (o instanceof org.docx4j.dml.picture.Pic) { // Post 2.7.1; untested
log.warn("TODO: " + XmlUtils.marshaltoString(o));
org.docx4j.dml.picture.Pic dmlPic = ((org.docx4j.dml.picture.Pic)o);
if (dmlPic.getBlipFill()!=null
&& dmlPic.getBlipFill().getBlip()!=null) {
log.debug("found DML Blip");
List<Object> artificialList = new ArrayList<Object>();
artificialList.add(dmlPic.getBlipFill().getBlip());
return artificialList;
} else {
return null;
}
} else if (o instanceof org.docx4j.dml.CTGvmlPicture) { // Post 2.7.1
log.warn("TODO: " + XmlUtils.marshaltoString(o));
org.docx4j.dml.CTGvmlPicture dmlPic = ((org.docx4j.dml.CTGvmlPicture)o);
if (dmlPic.getBlipFill()!=null
&& dmlPic.getBlipFill().getBlip()!=null) {
log.debug("found DML Blip");
List<Object> artificialList = new ArrayList<Object>();
artificialList.add(dmlPic.getBlipFill().getBlip());
return artificialList;
} else {
return null;
}
} else if (o instanceof org.docx4j.vml.CTShapetype ) {
// NB, may not be triggered, depending on parent.
/* eg
<v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t"
path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f">
<v:stroke joinstyle="miter"/>
<v:formulas>
<v:f eqn="if lineDrawn pixelLineWidth 0"/>
<v:f eqn="sum @0 1 0"/>
*/
containsVML = true;
// Generally nothing sensitive here
log.debug( XmlUtils.marshaltoString(o, true, true, Context.jc,
Namespaces.VML, "shapetype", o.getClass()));
inventoryObjects.add(o);
return null;
} else if (o instanceof org.docx4j.vml.CTShape) {
containsVML = true;
log.debug(XmlUtils.marshaltoString(o));
// return ((org.docx4j.vml.CTShape)o).getAny();
List<Object> artificialList = new ArrayList<Object>();
for (JAXBElement<?> j : ((org.docx4j.vml.CTShape)o).getPathOrFormulasOrHandles() ) {
// System.out.println(XmlUtils.unwrap(j).getClass().getName() );
artificialList.add(j);
}
return artificialList;
} else if (o instanceof CTDataModel) {
log.warn("TODO: " + XmlUtils.marshaltoString(o));
CTDataModel dataModel = (CTDataModel)o;
List<Object> artificialList = new ArrayList<Object>();
// We're going to create a list merging two children ..
artificialList.addAll(dataModel.getPtLst().getPt());
artificialList.addAll(dataModel.getCxnLst().getCxn());
return artificialList;
} else if (o instanceof org.docx4j.dml.diagram2008.CTDrawing) {
log.warn("TODO: " + XmlUtils.marshaltoString(o));
return ((org.docx4j.dml.diagram2008.CTDrawing)o).getSpTree().getSpOrGrpSp();
} else if (o instanceof org.docx4j.vml.CTTextbox) {
// We anon inside
/*
<v:textbox style="mso-fit-shape-to-text:t">
<w:txbxContent>
<w:p */
log.debug(XmlUtils.marshaltoString(o, true, true, Context.jc,
Namespaces.VML, "textbox", o.getClass()));
org.docx4j.vml.CTTextbox textBox = ((org.docx4j.vml.CTTextbox)o);
if (textBox.getTxbxContent()==null) {
return null;
} else {
return textBox.getTxbxContent().getContent();
// grandchildren
}
} else if (o instanceof CTObject) {
// w:object is not of itself interesting here
log.debug(XmlUtils.marshaltoString(o, true, true, Context.jc, Namespaces.NS_WORD12, "object", o.getClass()));
CTObject ctObject = (CTObject)o;
List<Object> artificialList = new ArrayList<Object>();
artificialList.addAll(ctObject.getAnyAndAny());
if (ctObject.getControl()!=null) {
artificialList.add(ctObject.getControl() ); // CTControl
}
return artificialList;
} else if (o instanceof org.docx4j.dml.CTGvmlGroupShape) {
log.warn("TODO: " + XmlUtils.marshaltoString(o));
return ((org.docx4j.dml.CTGvmlGroupShape)o).getTxSpOrSpOrCxnSp();
} else if(o instanceof FldChar) {
// Interesting to analyse fields; we record instrText above
FldChar fldChar = ((FldChar)o);
List<Object> artificialList = new ArrayList<Object>();
artificialList.add(fldChar.getFldCharType());
if(fldChar.getFfData() != null) {
artificialList.add(fldChar.getFfData());
}
if(fldChar.getFldData() != null) {
artificialList.add(fldChar.getFldData());
}
if(fldChar.getNumberingChange() != null) {
artificialList.add(fldChar.getNumberingChange());
}
return artificialList;
}
// OK, what is this? Use reflection ..
// This should work for things including w:drawing
log.debug(".. looking for method which returns list " );
try {
Method[] methods = o.getClass().getDeclaredMethods();
for (int i = 0; i<methods.length; i++) {
Method m = methods[i];
if (m.getReturnType().getName().equals("java.util.List") ) {
return (List<Object>)m.invoke(o);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.debug(".. no list member");
return null;
}
private List<Object> handleGraphicData(org.docx4j.dml.GraphicData graphicData) {
/*
<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
<pic:pic>
<pic:nvPicPr>
<pic:cNvPr descr="C:\Documents and Settings\Jason Harrop\My Documents\tmp-test-docs\pangolin.jpeg" name="Picture 1" id="0"/>
<pic:cNvPicPr>
<a:picLocks noChangeArrowheads="true" noChangeAspect="true"/>
</pic:cNvPicPr>
</pic:nvPicPr>
<pic:blipFill>
<a:blip r:embed="rId8" cstate="print"/>
<a:srcRect/>
<a:stretch>
<a:fillRect/>
</a:stretch>
</pic:blipFill> */
List<Object> tmpArtificialList = new ArrayList<Object>();
if (graphicData.getPic() != null) {
//GraphicData can have a hyperlink reference, which can be found this way
CTNonVisualDrawingProps picNonVisual = graphicData.getPic().getNvPicPr().getCNvPr();
if (picNonVisual != null) {
handleCTNonVisualDrawingProps(picNonVisual, tmpArtificialList);
}
}
// Its not graphicData.getAny() we're typically interested in
if (graphicData.getPic() != null && graphicData.getPic().getBlipFill() != null
&& graphicData.getPic().getBlipFill().getBlip() != null) {
CTBlip blip = graphicData.getPic().getBlipFill().getBlip();
if (blip.getLink()!=null) {
// Assume OK. Either its on the public internet, or its inaccessible.
log.debug("blip contained a link .. assumed ok");
} else if (blip.getEmbed()!=null ) {
String rId = blip.getEmbed();
Part embeddedPart = sourcePart.getRelationshipsPart().getPart(rId);
if (embeddedPart instanceof ImagePngPart
|| embeddedPart instanceof ImageGifPart
|| embeddedPart instanceof ImageJpegPart
|| embeddedPart instanceof ImageBmpPart
|| embeddedPart instanceof ImageTiffPart
// Others treated as unsafe
) {
// We've handled this
} else {
// Unsafe, but noted elsewhere
}
}
return null;
} else {
// Charts, shapes, diagrams: since 17.2.0 (CR-019) the anonymiser's walk reaches
// their text and caches, so this is inventory, not unsafe
inventoryObjects.add(graphicData);
return graphicData.getAny();
}
}
private void addUnsafe(Object o,
String uri, String local, Class declaredType) {
// For now, we'll use marshalled content
unsafeObjects.add(XmlUtils.marshaltoString(o, true, true, Context.jc,
uri, local, declaredType));
}
// private void addUnsafe(Object o) {
//
// // For now, we'll use marshalled content
// unsafeObjects.add(XmlUtils.marshaltoString(o));
// }
/**
* There can be hyperlinks references in CTNonVisualDrawingProps.
* @param drawingProps
* @param artificialList
*/
private void handleCTNonVisualDrawingProps(CTNonVisualDrawingProps drawingProps, List<Object> artificialList){
if (drawingProps != null) {
// <wp:docPr descr="C:\Documents and Settings\Jason Harrop\My Documents\tmp-test-docs\pangolin.jpeg"
// name="Picture 1" id="1"/>
if (drawingProps.getDescr()!=null) {
drawingProps.setDescr(null);
}
// Name is probably ok
CTHyperlink docPrHyperLink = drawingProps.getHlinkClick();
if (docPrHyperLink != null)
artificialList.add(docPrHyperLink);
}
}
}
@@ -0,0 +1,244 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Scrubs a field instruction (w:instrText, w:delInstrText, w:fldSimple/@w:instr):
* the field keyword and its switches survive, every argument loses its text.
* <p>
* Rules (CR-019 phase 1, item 2, "the MERGEFIELD pattern, generalised"):
* <ul>
* <li>the keyword is kept;</li>
* <li>a switch ({@code \x}) is kept; the argument of a format switch
* ({@code \*}, {@code \#}, {@code \@}) is a picture, not content, and is kept;</li>
* <li>an argument which names a bookmark (REF, PAGEREF, NOTEREF, ASK, SET and
* SEQ's identifier; HYPERLINK {@code \l}; TOC {@code \b} and {@code \c})
* is renamed through the identifier map, so it still matches the renamed
* bookmark;</li>
* <li>STYLEREF's argument is kept when it is a built-in style name (the
* predicate decides), else scrambled like any other;</li>
* <li>a formula field ({@code = ...}) keeps its operators and functions;
* only tokens the identifier map knows (bookmark names) are renamed;</li>
* <li>form-field instructions (FORMTEXT, FORMCHECKBOX, FORMDROPDOWN) have no
* argument and are untouched;</li>
* <li>every other argument, quoted or bare, has its letters scrambled (digits
* and punctuation stay, so a path keeps its shape and a switch value like
* {@code "1-3"} its meaning).</li>
* </ul>
*
* @since 17.2.0
*/
public class FieldInstructions {
/** Word's field keywords: kept by the scrub, allowed by {@link Verify}. */
public static final Set<String> KEYWORDS = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(
"ADDRESSBLOCK", "ADVANCE", "ASK", "AUTHOR", "AUTONUM", "AUTONUMLGL", "AUTONUMOUT", "AUTOTEXT",
"AUTOTEXTLIST", "BARCODE", "BIBLIOGRAPHY", "BIDIOUTLINE", "CITATION", "COMMENTS", "COMPARE",
"CREATEDATE", "DATABASE", "DATE", "DDE", "DDEAUTO", "DISPLAYBARCODE", "DOCPROPERTY", "DOCVARIABLE",
"EDITTIME", "EMBED", "EQ", "FILENAME", "FILESIZE", "FILLIN", "FORMCHECKBOX", "FORMDROPDOWN",
"FORMTEXT", "GLOSSARY", "GOTOBUTTON", "GREETINGLINE", "HYPERLINK", "IF", "IMPORT", "INCLUDE",
"INCLUDEPICTURE", "INCLUDETEXT", "INDEX", "INFO", "KEYWORDS", "LASTSAVEDBY", "LINK", "LISTNUM",
"MACROBUTTON", "MERGEBARCODE", "MERGEFIELD", "MERGEREC", "MERGESEQ", "NEXT", "NEXTIF", "NOTEREF",
"NUMCHARS", "NUMPAGES", "NUMWORDS", "PAGE", "PAGEREF", "PRINT", "PRINTDATE", "PRIVATE", "QUOTE",
"RD", "REF", "REVNUM", "SAVEDATE", "SECTION", "SECTIONPAGES", "SEQ", "SET", "SHAPE", "SKIPIF",
"STYLEREF", "SUBJECT", "SYMBOL", "TA", "TC", "TEMPLATE", "TIME", "TITLE", "TOA", "TOC",
"USERADDRESS", "USERINITIALS", "USERNAME", "XE",
// format-switch words and formula functions, kept with the switch / the formula
"MERGEFORMAT", "CHARFORMAT", "UPPER", "LOWER", "FIRSTCAP", "CAPS", "ALPHABETIC", "ARABIC",
"ARABICDASH", "CARDTEXT", "DOLLARTEXT", "HEX", "ORDINAL", "ORDTEXT", "ROMAN", "SUM", "AVERAGE",
"ABOVE", "BELOW", "LEFT", "RIGHT", "COUNT", "MAX", "MIN", "PRODUCT", "ROUND", "ABS", "AND",
"OR", "NOT", "DEFINED", "FALSE", "TRUE", "INT", "MOD", "SIGN")));
private static final Set<String> FORMAT_SWITCHES = new HashSet<String>(Arrays.asList("\\*", "\\#", "\\@"));
/** keywords whose first argument is a bookmark or sequence identifier */
private static final Set<String> FIRST_ARG_IS_IDENTIFIER = new HashSet<String>(Arrays.asList(
"REF", "PAGEREF", "NOTEREF", "ASK", "SET", "SEQ", "GOTOBUTTON"));
/** switches whose argument is a bookmark or sequence identifier */
private static final Set<String> SWITCH_ARG_IS_IDENTIFIER = new HashSet<String>(Arrays.asList("\\l", "\\b", "\\c", "\\s"));
private static final Set<String> NO_ARGUMENT = new HashSet<String>(Arrays.asList(
"FORMTEXT", "FORMCHECKBOX", "FORMDROPDOWN"));
private final Function<String, String> scrambler;
private final Function<String, String> identifiers;
private final Predicate<String> safeName;
/**
* @param scrambler replaces the letters of an argument (digits and punctuation kept)
* @param identifiers maps a bookmark or sequence name to its anonymised name
* (returns null for a name it does not know)
* @param safeName true for a name which may survive (a built-in style name for STYLEREF)
*/
public FieldInstructions(Function<String, String> scrambler, Function<String, String> identifiers,
Predicate<String> safeName) {
this.scrambler = scrambler;
this.identifiers = identifiers;
this.safeName = safeName;
}
/** The keyword of an instruction ("=" for a formula), upper-cased, or null. */
public static String keyword(String instr) {
if (instr == null) return null;
List<Token> tokens = tokenize(instr);
return tokens.isEmpty() ? null : tokens.get(0).text.toUpperCase(Locale.ROOT);
}
public String scrub(String instr) {
if (instr == null || instr.trim().isEmpty()) return instr;
List<Token> tokens = tokenize(instr);
if (tokens.isEmpty()) return instr;
String keyword = tokens.get(0).text.toUpperCase(Locale.ROOT);
if (NO_ARGUMENT.contains(keyword)) return instr;
StringBuilder out = new StringBuilder();
int pos = 0;
String pendingSwitch = null; // the switch whose argument the next token is
boolean firstArgSeen = false;
for (int i = 0; i < tokens.size(); i++) {
Token t = tokens.get(i);
out.append(instr, pos, t.start);
pos = t.end;
String replacement;
if (i == 0) {
replacement = t.text; // the keyword
} else if (t.kind == Kind.SWITCH) {
out.append(t.text);
pendingSwitch = t.text;
continue;
} else if (pendingSwitch != null && FORMAT_SWITCHES.contains(pendingSwitch)) {
replacement = t.text; // a picture
} else if (pendingSwitch != null && SWITCH_ARG_IS_IDENTIFIER.contains(pendingSwitch)
&& (keyword.equals("HYPERLINK") || keyword.equals("TOC") || keyword.equals("SEQ"))) {
replacement = identifier(t);
} else if (keyword.equals("=")) {
replacement = formulaToken(t);
} else if (!firstArgSeen && pendingSwitch == null && FIRST_ARG_IS_IDENTIFIER.contains(keyword)) {
replacement = identifier(t);
} else if (!firstArgSeen && pendingSwitch == null && keyword.equals("STYLEREF")
&& safeName.test(unquote(t.text))) {
replacement = t.text;
} else {
replacement = scramble(t);
}
if (i > 0 && pendingSwitch == null) firstArgSeen = true;
pendingSwitch = null;
out.append(replacement);
}
out.append(instr, pos, instr.length());
return out.toString();
}
private String identifier(Token t) {
String name = unquote(t.text);
String mapped = identifiers.apply(name);
if (mapped == null) return scramble(t);
return requote(t.text, mapped);
}
private static final java.util.regex.Pattern PLAIN_IDENTIFIER = java.util.regex.Pattern.compile("[\\p{L}_][\\p{L}\\p{N}_.]*");
/**
* In a formula only bookmark names change: a plain identifier which is not a
* function or keyword; operators, numbers, cell references and functions stay.
*/
private String formulaToken(Token t) {
if (t.kind == Kind.QUOTED) return scramble(t);
if (!PLAIN_IDENTIFIER.matcher(t.text).matches()) return t.text;
if (KEYWORDS.contains(t.text.toUpperCase(Locale.ROOT))) return t.text;
if (t.text.matches("[A-Za-z]{1,3}[0-9]+")) return t.text; // a cell reference
String mapped = identifiers.apply(t.text);
return mapped == null ? t.text : mapped;
}
private String scramble(Token t) {
String inner = unquote(t.text);
return requote(t.text, scrambler.apply(inner));
}
private static String unquote(String s) {
if (s.length() >= 2 && s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"') {
return s.substring(1, s.length() - 1);
}
return s;
}
private static String requote(String original, String inner) {
if (original.length() >= 2 && original.charAt(0) == '"' && original.charAt(original.length() - 1) == '"') {
return "\"" + inner + "\"";
}
return inner;
}
enum Kind { WORD, QUOTED, SWITCH }
static class Token {
final int start, end;
final String text;
final Kind kind;
Token(int start, int end, String text, Kind kind) {
this.start = start; this.end = end; this.text = text; this.kind = kind;
}
}
/** Splits on whitespace, keeping quoted strings (with \" escapes) whole; a switch is a backslash plus one character. */
static List<Token> tokenize(String s) {
List<Token> tokens = new ArrayList<Token>();
int i = 0, n = s.length();
while (i < n) {
char c = s.charAt(i);
if (Character.isWhitespace(c)) { i++; continue; }
int start = i;
if (c == '"') {
i++;
while (i < n) {
char d = s.charAt(i);
if (d == '\\' && i + 1 < n) { i += 2; continue; }
i++;
if (d == '"') break;
}
tokens.add(new Token(start, i, s.substring(start, i), Kind.QUOTED));
} else if (c == '\\' && i + 1 < n && !Character.isWhitespace(s.charAt(i + 1))) {
i += 2;
tokens.add(new Token(start, i, s.substring(start, i), Kind.SWITCH));
} else {
while (i < n && !Character.isWhitespace(s.charAt(i)) && s.charAt(i) != '"') i++;
if (i == start) i++;
tokens.add(new Token(start, i, s.substring(start, i), Kind.WORD));
}
}
return tokens;
}
}
@@ -0,0 +1,304 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import jakarta.xml.bind.JAXBElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Visits every object reachable from a JAXB root through its public getters:
* lists, JAXBElement wrappers, and every generated class (org.docx4j.*,
* org.pptx4j.*, org.xlsx4j.*, org.glox4j.*, org.opendope.*).
* <p>
* The anonymiser uses this rather than {@link org.docx4j.TraversalUtil} because
* the guarantee (CR-019) is "no text from the original in any text-bearing
* part", and TraversalUtil's children rules are written for the content tree
* (paragraphs, runs, tables, the drawings it knows): they do not reach
* paragraph and run properties (where w:rPrChange and w:pPrChange carry
* authors), settings, chart caches, diagram data, or any DrawingML text
* TraversalUtil's handleGraphicData does not list. A reflective walk reaches
* all of it, at the cost of some speed, which the anonymiser can afford.
* <p>
* Pre-order: a visitor sees a parent before its children, and sees each object
* once (an identity set guards against cycles and against the convenience
* getters which return an object also held in a list, such as
* {@code SdtPr.getTag()}). DOM nodes ({@code xs:any} content) are handed to the
* visitor and not descended into; the visitor decides what to do with them.
*
* @since 17.2.0
*/
public class JaxbGraphWalker {
private static final Logger log = LoggerFactory.getLogger(JaxbGraphWalker.class);
/** What the visitor wants done with the object it was just shown. */
public enum Action {
/** visit its children */
CONTINUE,
/** do not visit its children */
SKIP_CHILDREN,
/**
* remove it from its parent: from the list it sits in, or by invoking the
* setter matching the getter it came from with null; its children are not visited
*/
REMOVE,
/**
* replace it in the list it sits in with {@link Visitor#replacement()} (when it
* came from a getter, it is set to null instead); its children are not visited
*/
REPLACE
}
public interface Visitor {
/**
* @param o the object, unwrapped from any JAXBElement
* @param wrapper the JAXBElement it came wrapped in, or null; its name tells
* w:instrText from w:t (both are wml Text)
*/
Action visit(Object o, JAXBElement<?> wrapper);
/** The object to put in place of the one just answered with {@link Action#REPLACE}. */
default Object replacement() {
return null;
}
}
private final Visitor visitor;
private final Set<Object> seen = Collections.newSetFromMap(new IdentityHashMap<Object, Boolean>());
public JaxbGraphWalker(Visitor visitor) {
this.visitor = visitor;
}
/** Walks from root (the root itself is visited too). */
public void walk(Object root) {
if (root == null) return;
Object unwrapped = root;
JAXBElement<?> wrapper = null;
if (root instanceof JAXBElement) {
wrapper = (JAXBElement<?>) root;
unwrapped = wrapper.getValue();
if (unwrapped == null) return;
}
Action a = visitUnseen(unwrapped, wrapper);
if (a == Action.CONTINUE) {
walkChildren(unwrapped);
} else if (a == Action.REMOVE || a == Action.REPLACE) {
log.warn(a + " of a root object is ignored: " + unwrapped.getClass().getName());
}
}
private Action visitUnseen(Object o, JAXBElement<?> wrapper) {
if (!seen.add(o)) return Action.SKIP_CHILDREN;
return visitor.visit(o, wrapper);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void walkChildren(Object parent) {
if (parent instanceof List) {
List list = (List) parent;
// iterate a snapshot: the visitor may ask for removals
for (Object child : new ArrayList<Object>(list)) {
walkListChild(list, child);
}
return;
}
if (!isModelObject(parent)) return;
for (Method getter : accessors(parent.getClass())) {
Object value;
try {
value = getter.invoke(parent);
} catch (Exception e) {
log.debug(getter + " threw " + e);
continue;
}
if (value == null) continue;
if (value instanceof List) {
List list = (List) value;
for (Object child : new ArrayList<Object>(list)) {
walkListChild(list, child);
}
} else {
Object unwrapped = value;
JAXBElement<?> wrapper = null;
if (value instanceof JAXBElement) {
wrapper = (JAXBElement<?>) value;
unwrapped = wrapper.getValue();
if (unwrapped == null) continue;
}
if (!isVisitable(unwrapped)) continue;
Action a = visitUnseen(unwrapped, wrapper);
if (a == Action.CONTINUE) {
walkChildren(unwrapped);
} else if (a == Action.REMOVE || a == Action.REPLACE) {
setNull(parent, getter);
}
}
}
}
@SuppressWarnings({ "rawtypes" })
private void walkListChild(List list, Object child) {
if (child == null) return;
Object unwrapped = child;
JAXBElement<?> wrapper = null;
if (child instanceof JAXBElement) {
wrapper = (JAXBElement<?>) child;
unwrapped = wrapper.getValue();
if (unwrapped == null) return;
}
if (!isVisitable(unwrapped)) return;
Action a = visitUnseen(unwrapped, wrapper);
if (a == Action.CONTINUE) {
walkChildren(unwrapped);
} else if (a == Action.REMOVE) {
removeByIdentity(list, child);
} else if (a == Action.REPLACE) {
Object replacement = visitor.replacement();
if (replacement == null) {
removeByIdentity(list, child);
} else {
replaceByIdentity(list, child, replacement);
seen.add(replacement instanceof JAXBElement ? ((JAXBElement<?>) replacement).getValue() : replacement);
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static void replaceByIdentity(List list, Object child, Object replacement) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == child) {
list.set(i, replacement);
return;
}
}
}
@SuppressWarnings("rawtypes")
private static void removeByIdentity(List list, Object child) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == child) {
list.remove(i);
return;
}
}
}
private static void setNull(Object parent, Method getter) {
String setterName = "set" + getter.getName().substring(3);
try {
Method setter = parent.getClass().getMethod(setterName, getter.getReturnType());
setter.invoke(parent, new Object[] { null });
} catch (Exception e) {
log.warn("cannot null " + getter.getName() + " on " + parent.getClass().getName() + ": " + e);
}
}
/** Objects the visitor is shown: model objects, lists, DOM nodes, strings in mixed content. */
private static boolean isVisitable(Object o) {
return isModelObject(o)
|| o instanceof List
|| o instanceof org.w3c.dom.Node
|| o instanceof String;
}
/** A generated (or hand-written) content-model class: recurse into its getters. */
static boolean isModelObject(Object o) {
if (o == null) return false;
String p = o.getClass().getName();
return (p.startsWith("org.docx4j.")
|| p.startsWith("org.pptx4j.")
|| p.startsWith("org.xlsx4j.")
|| p.startsWith("org.glox4j.")
|| p.startsWith("org.opendope."))
&& !p.startsWith("org.docx4j.openpackaging.")
&& !p.startsWith("org.docx4j.anon.")
&& !p.endsWith("ObjectFactory")
&& !(o instanceof Enum);
}
private static final Map<Class<?>, List<Method>> ACCESSORS = new ConcurrentHashMap<Class<?>, List<Method>>();
/**
* The public no-arg getters of a class which can lead to further model objects
* (anything but scalars), computed once per class.
*/
private static List<Method> accessors(Class<?> c) {
List<Method> cached = ACCESSORS.get(c);
if (cached != null) return cached;
// lists first: a convenience getter (SdtPr.getTag()) returns an object which also
// sits in a list, and a removal must come off the list, not through a setter the
// convenience getter may not have
List<Method> lists = new ArrayList<Method>();
List<Method> singles = new ArrayList<Method>();
for (Method m : c.getMethods()) {
if (m.getParameterCount() != 0) continue;
if (Modifier.isStatic(m.getModifiers())) continue;
if (m.isBridge() || m.isSynthetic()) continue;
if (m.getDeclaringClass() == Object.class) continue;
String name = m.getName();
if (!name.startsWith("get") || name.length() < 4) continue;
if (name.equals("getParent") || name.equals("getClass")) continue;
Class<?> rt = m.getReturnType();
if (isScalar(rt)) continue;
if (List.class.isAssignableFrom(rt)) {
lists.add(m);
} else {
singles.add(m);
}
}
List<Method> result = new ArrayList<Method>(lists);
result.addAll(singles);
ACCESSORS.put(c, result);
return result;
}
private static boolean isScalar(Class<?> rt) {
return rt.isPrimitive()
|| rt == String.class
|| rt.isEnum()
|| Number.class.isAssignableFrom(rt)
|| rt == Boolean.class
|| rt == Character.class
|| rt == byte[].class
|| rt.isArray()
|| javax.xml.datatype.XMLGregorianCalendar.class.isAssignableFrom(rt)
|| javax.xml.datatype.Duration.class.isAssignableFrom(rt)
|| rt == javax.xml.namespace.QName.class
|| rt == java.util.Map.class;
}
}
@@ -0,0 +1,91 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.util.Random;
/**
* The replacement vocabulary: the words of the classic <i>lorem ipsum</i> passage
* (Cicero, <i>De finibus bonorum et malorum</i>, as the printers' filler has carried it
* since the 1500s - public domain), from which {@link ScrambleText} draws the Latin
* text it writes in place of a document's, and against which {@link Verify} tests
* whether a surviving token could be the scrambler's own.
* <p>
* Until 17.2.1 this was com.thedeanda:lorem, the one dependency that kept the
* anonymiser in a module of its own (and a filename-based automatic module under
* JPMS). The scrambler only ever needed a run of pseudo-words with a natural
* length distribution, and the check only ever needed the same list; one array
* serves both, so the list cannot drift from the check.
*
* @since 17.2.1
*/
public final class Lorem {
private Lorem() {}
/** The distinct words of the passage (the filler and its Cicero source), lower case; the same list {@link Verify} allows. */
public static final String[] WORDS = {
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do",
"eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim",
"ad", "minim", "veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi",
"aliquip", "ex", "ea", "commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit",
"voluptate", "velit", "esse", "cillum", "eu", "fugiat", "nulla", "pariatur", "excepteur",
"sint", "occaecat", "cupidatat", "non", "proident", "sunt", "culpa", "qui", "officia",
"deserunt", "mollit", "anim", "id", "est", "laborum", "neque", "porro", "quisquam", "quia",
"dolorem", "quaerat", "voluptatem", "aspernatur", "aut", "odit", "fugit", "consequuntur",
"magni", "dolores", "eos", "ratione", "sequi", "nesciunt", "ipsam", "ipsa", "voluptas",
"aliquam", "numquam", "eius", "modi", "tempora", "incidunt", "magnam", "quam", "nostrum",
"exercitationem", "ullam", "corporis", "suscipit", "laboriosam", "aliquid", "commodi",
"consequatur", "autem", "vel", "eum", "iure", "nihil", "molestiae", "illum", "quo", "at",
"vero", "accusamus", "iusto", "odio", "dignissimos", "ducimus", "blanditiis", "praesentium",
"voluptatum", "deleniti", "atque", "corrupti", "quos", "quas", "molestias", "excepturi",
"obcaecati", "cupiditate", "provident", "similique", "mollitia", "animi", "dolorum", "fuga",
"harum", "quidem", "rerum", "facilis", "expedita", "distinctio", "nam", "libero", "tempore",
"cum", "soluta", "nobis", "eligendi", "optio", "cumque", "impedit", "minus", "quod", "maxime",
"placeat", "facere", "possimus", "omnis", "assumenda", "temporibus", "quibusdam", "officiis",
"debitis", "necessitatibus", "saepe", "eveniet", "voluptates", "repudiandae", "recusandae",
"itaque", "earum", "hic", "tenetur", "sapiente", "delectus", "reiciendis", "maiores", "alias",
"perferendis", "doloribus", "asperiores", "repellat" };
/**
* @param count how many words
* @return that many words drawn at random, separated by single spaces
*/
public static String words(int count, Random random) {
StringBuilder sb = new StringBuilder(count * 7);
for (int i = 0; i < count; i++) {
if (i > 0) sb.append(' ');
sb.append(WORDS[random.nextInt(WORDS.length)]);
}
return sb.toString();
}
private static String joined;
/** true if the token (lower case) is a substring of some word of the list */
public static synchronized boolean isFragment(String token) {
if (joined == null) {
StringBuilder sb = new StringBuilder(" ");
for (String w : WORDS) sb.append(w).append(' ');
joined = sb.toString();
}
return joined.contains(token);
}
}
@@ -0,0 +1,549 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import jakarta.xml.bind.JAXBElement;
import org.docx4j.XmlUtils;
import org.docx4j.anon.JaxbGraphWalker.Action;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.w15.CTPerson;
import org.docx4j.w15.CTPresenceInfo;
import org.docx4j.w16cex.CTCommentExtensible;
import org.docx4j.wml.CTAltChunk;
import org.docx4j.wml.CTBookmark;
import org.docx4j.wml.CTControl;
import org.docx4j.wml.CTDataBinding;
import org.docx4j.wml.CTDocProtect;
import org.docx4j.wml.CTDocVars;
import org.docx4j.wml.CTFFData;
import org.docx4j.wml.CTFFName;
import org.docx4j.wml.CTMailMerge;
import org.docx4j.wml.CTMoveBookmark;
import org.docx4j.wml.CTObject;
import org.docx4j.wml.CTPictureBase;
import org.docx4j.wml.CTRel;
import org.docx4j.wml.CTSdtDate;
import org.docx4j.wml.CTSimpleField;
import org.docx4j.wml.CTTblPrBase;
import org.docx4j.wml.CTTrackChange;
import org.docx4j.wml.CTWriteProtection;
import org.docx4j.wml.Comments;
import org.docx4j.wml.FldChar;
import org.docx4j.wml.FontRel;
import org.docx4j.wml.Lvl;
import org.docx4j.wml.Numbering;
import org.docx4j.wml.P;
import org.docx4j.wml.PPrBase;
import org.docx4j.wml.Pict;
import org.docx4j.wml.RStyle;
import org.docx4j.wml.Style;
import org.docx4j.wml.Tag;
/**
* The second visitor of the anonymiser's walk: identities, references and the
* markup that points at embedded objects.
* <ul>
* <li>Identity: every {@link CTTrackChange} (w:ins, w:del, w:moveFrom,
* w:moveTo, every *Change, w:cellIns/cellDel/cellMerge, w:numberingChange, and
* w:comment) has its author renamed and its date fixed; move bookmarks the same;
* comment initials renamed; people.xml authors and presence; commentsExtensible
* dates.</li>
* <li>References: bookmark and form-field names renamed (consistently with
* the field instructions {@link ScrambleText} scrubs); hyperlink tooltips,
* anchors and document locations; content-control tags and data bindings
* removed, date-picker values fixed; field data blobs removed; custom style ids
* renamed at the definition and at every reference.</li>
* <li>Settings: mail merge, document variables, attached template and printer
* settings relationships removed; protection hashes and salts cleared (the
* protection itself stays, with no password).</li>
* <li>Embedded objects, in STRICT mode: w:altChunk, o:OLEObject, w:control,
* c:externalData, cx:externalData and the font-table embed elements are removed
* with the parts they point at ({@link Anonymize} removes the parts); in KEEP
* mode they stay, and the part is reported as kept unsafe.</li>
* <li>PresentationML (CR-019 phase 2): legacy comment dates fixed and comment
* authors renamed (with their p15 presence info); the modify-verifier (password
* hash) removed; in STRICT mode the embedded-font list, smart tags, ink content
* parts, every media reference (a:videoFile, a:audioFile, a:quickTimeFile,
* a:audioCd, a:wavAudioFile / a:snd, p14:media, the audio and video timing
* nodes, transition sounds), ActiveX controls (p:control) and OLE objects are
* removed - an OLE graphic frame becomes its own preview picture, which
* {@link MediaReplacer} then labels "OLE object removed".</li>
* </ul>
*
* @since 17.2.0
*/
public class MarkupScrubber implements JaxbGraphWalker.Visitor {
private final Names names;
private final boolean strict;
private final Consumer<String> notes;
private String lastPersonAuthor;
private String currentPartName = "";
private Object replacement;
/**
* "partName#relId" of every picture which stood in for a removed OLE object or
* ActiveX control: {@link MediaReplacer} gives those the labelled placeholder
* rather than the plain pixels.
*/
final Set<String> objectPreviews = new HashSet<String>();
/** The part being walked: relationship ids are per part. */
public void setCurrentPart(Part part) {
currentPartName = part == null ? "" : part.getPartName().getName();
}
@Override
public Object replacement() {
return replacement;
}
/**
* @param names the shared renamings
* @param strict remove the markup of embedded objects (their parts go too)
* @param notes receives one line per removal, for the report
*/
public MarkupScrubber(Names names, boolean strict, Consumer<String> notes) {
this.names = names;
this.strict = strict;
this.notes = notes;
}
@Override
public Action visit(Object o, JAXBElement<?> wrapper) {
// ---- identity
if (o instanceof CTTrackChange) {
CTTrackChange tc = (CTTrackChange) o;
tc.setAuthor(names.author(tc.getAuthor()));
if (tc.getDate() != null) tc.setDate(Names.fixedDate());
if (tc.getDateUtc() != null) tc.setDateUtc(null);
if (o instanceof Comments.Comment) {
Comments.Comment c = (Comments.Comment) o;
c.setInitials(names.initials(c.getInitials()));
}
return Action.CONTINUE;
}
if (o instanceof CTMoveBookmark) {
CTMoveBookmark mb = (CTMoveBookmark) o;
mb.setAuthor(names.author(mb.getAuthor()));
if (mb.getDate() != null) mb.setDate(Names.fixedDate());
mb.setName(Names.identifier(mb.getName()));
return Action.CONTINUE;
}
if (o instanceof CTPerson) {
CTPerson p = (CTPerson) o;
p.setAuthor(names.author(p.getAuthor()));
lastPersonAuthor = p.getAuthor();
if (p.getContact() != null) p.setContact(null);
return Action.CONTINUE;
}
if (o instanceof CTPresenceInfo) {
CTPresenceInfo pi = (CTPresenceInfo) o;
pi.setProviderId("None");
// the parent person was visited just before this (pre-order): the user id
// (an email or directory id) becomes that person's anonymised name
if (pi.getUserId() != null) pi.setUserId(lastPersonAuthor != null ? lastPersonAuthor : "Author");
return Action.SKIP_CHILDREN;
}
if (o instanceof CTCommentExtensible) {
CTCommentExtensible ce = (CTCommentExtensible) o;
if (ce.getDateUtc() != null) ce.setDateUtc(Names.fixedDate());
return Action.CONTINUE;
}
if (o instanceof org.pptx4j.pml.CTComment) {
// a legacy PowerPoint comment: the author is an id into the authors part (kept); the
// date goes; the text is ScrambleText's
org.pptx4j.pml.CTComment c = (org.pptx4j.pml.CTComment) o;
if (c.getDt() != null) c.setDt(Names.fixedDate());
return Action.CONTINUE;
}
if (o instanceof org.pptx4j.pml.CTCommentAuthor) {
org.pptx4j.pml.CTCommentAuthor a = (org.pptx4j.pml.CTCommentAuthor) o;
a.setName(names.author(a.getName()));
a.setInitials(names.initials(a.getInitials()));
lastPersonAuthor = a.getName();
return Action.CONTINUE; // its extLst may hold p15:presenceInfo
}
if (o instanceof org.pptx4j.com.microsoft.schemas.office.powerpoint.x2012.main.CTPresenceInfo) {
org.pptx4j.com.microsoft.schemas.office.powerpoint.x2012.main.CTPresenceInfo pi =
(org.pptx4j.com.microsoft.schemas.office.powerpoint.x2012.main.CTPresenceInfo) o;
pi.setProviderId("None");
if (pi.getUserId() != null) pi.setUserId(lastPersonAuthor != null ? lastPersonAuthor : "Author");
return Action.SKIP_CHILDREN;
}
// ---- references
if (o instanceof CTBookmark) {
CTBookmark b = (CTBookmark) o;
b.setName(Names.identifier(b.getName()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTFFName) {
CTFFName n = (CTFFName) o;
n.setVal(Names.identifier(n.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTFFData) {
return Action.CONTINUE; // its name, default, help text, entries are visited
}
if (o instanceof FldChar) {
FldChar fc = (FldChar) o;
if (fc.getFldData() != null) {
fc.setFldData(null);
notes.accept("w:fldData removed");
}
return Action.CONTINUE;
}
if (o instanceof CTSimpleField) {
CTSimpleField f = (CTSimpleField) o;
if (f.getFldData() != null) {
f.setFldData(null);
notes.accept("w:fldData removed");
}
return Action.CONTINUE;
}
if (o instanceof P.Hyperlink) {
P.Hyperlink h = (P.Hyperlink) o;
h.setTooltip(null);
h.setDocLocation(null);
if (h.getAnchor() != null) h.setAnchor(Names.identifier(h.getAnchor()));
return Action.CONTINUE;
}
if (o instanceof Tag || o instanceof CTDataBinding) {
return Action.REMOVE;
}
if (o instanceof CTSdtDate) {
CTSdtDate d = (CTSdtDate) o;
if (d.getFullDate() != null) d.setFullDate(Names.fixedDate());
return Action.CONTINUE;
}
// ---- style ids (the names are ScrambleText's)
if (o instanceof Style) {
Style s = (Style) o;
s.setStyleId(names.styleId(s.getStyleId()));
return Action.CONTINUE;
}
if (o instanceof Style.BasedOn) {
Style.BasedOn r = (Style.BasedOn) o;
r.setVal(names.styleId(r.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof Style.Next) {
Style.Next r = (Style.Next) o;
r.setVal(names.styleId(r.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof Style.Link) {
Style.Link r = (Style.Link) o;
r.setVal(names.styleId(r.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof PPrBase.PStyle) {
PPrBase.PStyle r = (PPrBase.PStyle) o;
r.setVal(names.styleId(r.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof RStyle) {
RStyle r = (RStyle) o;
r.setVal(names.styleId(r.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTTblPrBase.TblStyle) {
CTTblPrBase.TblStyle r = (CTTblPrBase.TblStyle) o;
r.setVal(names.styleId(r.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof Lvl.PStyle) {
Lvl.PStyle r = (Lvl.PStyle) o;
r.setVal(names.styleId(r.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof Numbering.AbstractNum.NumStyleLink) {
Numbering.AbstractNum.NumStyleLink r = (Numbering.AbstractNum.NumStyleLink) o;
r.setVal(names.styleId(r.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof Numbering.AbstractNum.StyleLink) {
Numbering.AbstractNum.StyleLink r = (Numbering.AbstractNum.StyleLink) o;
r.setVal(names.styleId(r.getVal()));
return Action.SKIP_CHILDREN;
}
// ---- settings
if (o instanceof org.docx4j.wml.CTSettings) {
// the document ids fingerprint a document across its copies
org.docx4j.wml.CTSettings settings = (org.docx4j.wml.CTSettings) o;
if (settings.getDocId14() != null) settings.getDocId14().setVal("00000001");
if (settings.getDocId15() != null) settings.getDocId15().setVal("{00000000-0000-0000-0000-000000000001}");
return Action.CONTINUE;
}
if (o instanceof CTMailMerge) {
notes.accept("w:mailMerge removed");
return Action.REMOVE;
}
if (o instanceof CTDocVars) {
notes.accept("w:docVars removed");
return Action.REMOVE;
}
if (o instanceof CTRel) {
// w:attachedTemplate, w:printerSettings, mail-merge sources: relationships to
// outside the package, or to a part STRICT removes
notes.accept("settings relationship removed (attached template / printer settings / data source)");
return Action.REMOVE;
}
if (o instanceof CTDocProtect) {
CTDocProtect p = (CTDocProtect) o;
p.setHash(null);
p.setSalt(null);
p.setCryptProviderType(null);
p.setCryptAlgorithmClass(null);
p.setCryptAlgorithmType(null);
p.setCryptAlgorithmSid(null);
p.setCryptSpinCount(null);
p.setCryptProvider(null);
p.setAlgIdExt(null);
p.setAlgIdExtSource(null);
p.setCryptProviderTypeExt(null);
p.setCryptProviderTypeExtSource(null);
return Action.SKIP_CHILDREN;
}
if (o instanceof org.pptx4j.pml.CTModifyVerifier) {
// p:modifyVerifier: the hash and salt of the password to modify; nothing else in
// it is structure, so the element goes (unlike w:documentProtection, whose
// enforcement flags describe the document)
notes.accept("p:modifyVerifier removed (password hash and salt)");
return Action.REMOVE;
}
if (o instanceof CTWriteProtection) {
CTWriteProtection p = (CTWriteProtection) o;
p.setHash(null);
p.setSalt(null);
p.setCryptProviderType(null);
p.setCryptAlgorithmClass(null);
p.setCryptAlgorithmType(null);
p.setCryptAlgorithmSid(null);
p.setCryptSpinCount(null);
p.setCryptProvider(null);
p.setAlgIdExt(null);
p.setAlgIdExtSource(null);
p.setCryptProviderTypeExt(null);
p.setCryptProviderTypeExtSource(null);
return Action.SKIP_CHILDREN;
}
// ---- embedded objects
if (strict) {
if (o instanceof CTPictureBase) {
// w:object / w:pict: if it holds an OLE object or a control, its VML picture
// is the object's footprint and gets the labelled placeholder
CTPictureBase pict = (CTPictureBase) o;
boolean holdsObject = (o instanceof CTObject && ((CTObject) o).getControl() != null)
|| (o instanceof Pict && ((Pict) o).getControl() != null);
for (Object child : pict.getAnyAndAny()) {
if (XmlUtils.unwrap(child) instanceof org.docx4j.vml.officedrawing.CTOLEObject) holdsObject = true;
}
if (holdsObject) {
for (Object child : pict.getAnyAndAny()) {
Object shape = XmlUtils.unwrap(child);
if (shape instanceof org.docx4j.vml.CTShape) {
for (JAXBElement<?> el : ((org.docx4j.vml.CTShape) shape).getPathOrFormulasOrHandles()) {
if (el.getValue() instanceof org.docx4j.vml.CTImageData) {
org.docx4j.vml.CTImageData data = (org.docx4j.vml.CTImageData) el.getValue();
String relId = data.getId() != null ? data.getId() : data.getRelid();
if (relId != null) objectPreviews.add(currentPartName + "#" + relId);
}
}
}
}
}
return Action.CONTINUE;
}
if (o instanceof CTAltChunk) {
notes.accept("w:altChunk replaced by a marker paragraph");
replacement = Placeholders.altChunkRemoved();
return Action.REPLACE;
}
if (o instanceof org.docx4j.vml.officedrawing.CTOLEObject) {
notes.accept("o:OLEObject removed (its picture stays, as the labelled placeholder)");
return Action.REMOVE;
}
if (o instanceof CTControl) {
notes.accept("w:control removed");
return Action.REMOVE;
}
if (o instanceof FontRel) {
notes.accept("embedded font reference removed");
return Action.REMOVE;
}
String simple = o.getClass().getSimpleName();
if (simple.equals("CTExternalData")) {
notes.accept("chart externalData removed");
return Action.REMOVE;
}
if (simple.equals("CTGeoCache") || simple.equals("CTGeography")) {
notes.accept("chart geography cache removed");
return Action.REMOVE;
}
if (simple.equals("CTPivotSource") || simple.equals("CTPivotFmts")) {
// a pivot chart's pivot table is gone (removed in a workbook, in another file for a
// docx or pptx): the chart keeps its caches and cell references as a plain chart
notes.accept("chart pivotSource removed");
return Action.REMOVE;
}
// ---- PresentationML
if (o instanceof org.pptx4j.pml.CTEmbeddedFontList) {
notes.accept("p:embeddedFontLst removed (the font data parts go with it)");
return Action.REMOVE;
}
if (o instanceof org.pptx4j.pml.CTSmartTags) {
notes.accept("p:smartTags removed");
return Action.REMOVE;
}
if (o instanceof org.pptx4j.pml.CTRel) {
// p:contentPart: ink, in a part the tool cannot read (its mc:Fallback picture stays)
notes.accept("p:contentPart removed (ink)");
return Action.REMOVE;
}
if (o instanceof org.pptx4j.pml.CTControlList) {
// p:controls holds nothing but ActiveX controls (and mc branches of them)
notes.accept("p:controls removed (ActiveX)");
return Action.REMOVE;
}
if (o instanceof org.pptx4j.pml.CTControl) {
notes.accept("p:control removed (ActiveX)");
return Action.REMOVE;
}
if (o instanceof org.docx4j.dml.CTVideoFile
|| o instanceof org.docx4j.dml.CTAudioFile
|| o instanceof org.docx4j.dml.CTQuickTimeFile
|| o instanceof org.docx4j.dml.CTAudioCD
|| o instanceof org.docx4j.dml.CTEmbeddedWAVAudioFile) {
// the media file (embedded: a part the tool cannot read; linked: an external
// target) is gone; the picture the reference sat on stays as a picture
notes.accept("media reference removed (" + o.getClass().getSimpleName().substring(2) + ")");
return Action.REMOVE;
}
if (o instanceof org.pptx4j.pml.CTTransitionSoundAction) {
notes.accept("p:transition sound removed");
return Action.REMOVE;
}
if (o instanceof org.pptx4j.pml.CTTLMediaNodeAudio || o instanceof org.pptx4j.pml.CTTLMediaNodeVideo) {
notes.accept("timing media node removed");
return Action.REMOVE;
}
if (o instanceof org.pptx4j.pml.CTExtension
&& holdsMedia(((org.pptx4j.pml.CTExtension) o).getAny())) {
// p:extLst/p:ext holding p14:media: the whole ext goes (an empty p:ext is not valid)
notes.accept("p14:media removed");
return Action.REMOVE;
}
if (o instanceof org.docx4j.dml.CTOfficeArtExtension
&& holdsMedia(((org.docx4j.dml.CTOfficeArtExtension) o).getAny())) {
notes.accept("p14:media removed");
return Action.REMOVE;
}
if (o instanceof org.pptx4j.pml.CTGraphicalObjectFrame) {
return oleFrame((org.pptx4j.pml.CTGraphicalObjectFrame) o);
}
}
return Action.CONTINUE;
}
private static boolean holdsMedia(Object any) {
return XmlUtils.unwrap(any) instanceof org.pptx4j.com.microsoft.schemas.office.powerpoint.x2010.main.CTMedia;
}
/**
* A p:graphicFrame whose graphic data is a p:oleObj (in any mc branch): the
* embedding part goes, so the frame is replaced by the object's preview picture
* (the p:pic PowerPoint writes inside the mc:Fallback's p:oleObj), given the
* frame's id and position, and the picture's relationship is recorded so
* {@link MediaReplacer} labels it. A frame with no preview is removed.
*/
private Action oleFrame(org.pptx4j.pml.CTGraphicalObjectFrame frame) {
List<org.pptx4j.pml.CTOleObject> oles = new ArrayList<org.pptx4j.pml.CTOleObject>();
if (frame.getGraphic() != null && frame.getGraphic().getGraphicData() != null) {
collectOleObjects(frame.getGraphic().getGraphicData().getAny(), oles);
}
if (oles.isEmpty()) return Action.CONTINUE;
org.pptx4j.pml.Pic pic = null;
for (org.pptx4j.pml.CTOleObject ole : oles) {
if (ole.getPic() != null) pic = ole.getPic(); // the last one: PowerPoint's is in the mc:Fallback
}
if (pic == null) {
notes.accept("p:oleObj removed with its frame (it had no preview picture)");
return Action.REMOVE;
}
org.docx4j.dml.CTNonVisualDrawingProps frameProps =
frame.getNvGraphicFramePr() == null ? null : frame.getNvGraphicFramePr().getCNvPr();
org.docx4j.dml.CTNonVisualDrawingProps props = new org.docx4j.dml.CTNonVisualDrawingProps();
props.setId(frameProps == null ? 0 : frameProps.getId());
props.setName("Object " + props.getId());
if (pic.getNvPicPr() == null) pic.setNvPicPr(new org.pptx4j.pml.Pic.NvPicPr());
pic.getNvPicPr().setCNvPr(props);
if (pic.getNvPicPr().getCNvPicPr() == null) pic.getNvPicPr().setCNvPicPr(new org.docx4j.dml.CTNonVisualPictureProperties());
if (pic.getNvPicPr().getNvPr() == null) pic.getNvPicPr().setNvPr(new org.pptx4j.pml.NvPr());
if (pic.getSpPr() == null) pic.setSpPr(new org.docx4j.dml.CTShapeProperties());
if (pic.getSpPr().getXfrm() == null) pic.getSpPr().setXfrm(frame.getXfrm());
if (pic.getSpPr().getPrstGeom() == null && pic.getSpPr().getCustGeom() == null) {
org.docx4j.dml.CTPresetGeometry2D rect = new org.docx4j.dml.CTPresetGeometry2D();
rect.setPrst(org.docx4j.dml.STShapeType.RECT);
rect.setAvLst(new org.docx4j.dml.CTGeomGuideList());
pic.getSpPr().setPrstGeom(rect);
}
if (pic.getBlipFill() != null && pic.getBlipFill().getBlip() != null
&& pic.getBlipFill().getBlip().getEmbed() != null) {
objectPreviews.add(currentPartName + "#" + pic.getBlipFill().getBlip().getEmbed());
}
for (org.pptx4j.pml.CTOleObject ole : oles) {
ole.setPic(null); // the picture now stands on its own
}
notes.accept("p:oleObj removed; its frame is now its preview picture, as the labelled placeholder");
replacement = pic;
return Action.REPLACE;
}
private static void collectOleObjects(List<Object> any, List<org.pptx4j.pml.CTOleObject> into) {
for (Object o : any) {
Object u = XmlUtils.unwrap(o);
if (u instanceof org.pptx4j.pml.CTOleObject) {
into.add((org.pptx4j.pml.CTOleObject) u);
} else if (u instanceof org.docx4j.mce.AlternateContent) {
org.docx4j.mce.AlternateContent ac = (org.docx4j.mce.AlternateContent) u;
for (org.docx4j.mce.AlternateContent.Choice c : ac.getChoice()) collectOleObjects(c.getAny(), into);
if (ac.getFallback() != null) collectOleObjects(ac.getFallback().getAny(), into);
}
}
}
}
@@ -0,0 +1,318 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.DocumentBuilderFactory;
import org.docx4j.openpackaging.Base;
import org.docx4j.openpackaging.URIHelper;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.contenttype.ContentTypes;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.packages.PresentationMLPackage;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.DefaultXmlPart;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart;
import org.docx4j.openpackaging.parts.WordprocessingML.ImageBmpPart;
import org.docx4j.openpackaging.parts.WordprocessingML.ImageGifPart;
import org.docx4j.openpackaging.parts.WordprocessingML.ImageJpegPart;
import org.docx4j.openpackaging.parts.WordprocessingML.ImagePngPart;
import org.docx4j.openpackaging.parts.WordprocessingML.ImageTiffPart;
import org.docx4j.openpackaging.parts.relationships.RelationshipsPart;
import org.docx4j.openpackaging.parts.relationships.RelationshipsPart.AddPartBehaviour;
import org.docx4j.relationships.Relationship;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Replaces every image with a placeholder: raster parts (png, gif, jpeg, bmp,
* tiff) have their bytes replaced in place with a 2x2 PNG (Word reads the
* bytes, not the extension, and scales the pixels to the drawing's extent);
* every other image class (EMF and WMF, which can carry text as glyph runs -
* see CR-011 - EPS, JPEG XR, WebP) is removed and every relationship which
* pointed at it retargeted to one shared placeholder PNG part, so the drawing
* still shows a picture; an SVG part (XML, so possibly text) becomes a blank
* 2x2 SVG.
*
* @since 17.2.0
*/
public class MediaReplacer {
private static final Logger log = LoggerFactory.getLogger(MediaReplacer.class);
/** a 2x2 PNG */
static final byte[] PNG_IMAGE_DATA = Base64.getDecoder().decode(
"iVBORw0KGgoAAAANSUhEUgAAAAIAAAACAgMAAAAP2OW3AAAADFBMVEUDAP//AAAA/wb//AAD4Tw1AAAACXBIWXMAAAsTAAALEwEAmpwYAAAADElEQVQI12NwYNgAAAF0APHJnpmVAAAAAElFTkSuQmCC");
static final String BLANK_SVG = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"2\" height=\"2\" viewBox=\"0 0 2 2\"/>";
/** the shared placeholder's file name, under the package's media folder ({@link #placeholderPartName(OpcPackage)}) */
public static final String PLACEHOLDER_FILE = "anon-placeholder.png";
/** the labelled image a removed OLE object's or control's picture becomes */
public static final String OBJECT_PLACEHOLDER_FILE = "anon-object-removed.png";
/** the placeholder's part name in a docx */
public static final String PLACEHOLDER_PART_NAME = "/word/media/" + PLACEHOLDER_FILE;
/** the labelled placeholder's part name in a docx */
public static final String OBJECT_PLACEHOLDER_PART_NAME = "/word/media/" + OBJECT_PLACEHOLDER_FILE;
/** /word/media/ for a docx, /ppt/media/ for a pptx, /xl/media/ for an xlsx */
static String mediaFolder(OpcPackage pkg) {
if (pkg instanceof PresentationMLPackage) return "/ppt/media/";
if (pkg instanceof WordprocessingMLPackage) return "/word/media/";
if (pkg instanceof org.docx4j.openpackaging.packages.SpreadsheetMLPackage) return "/xl/media/";
return "/media/";
}
/** @since 17.2.1 */
public static String placeholderPartName(OpcPackage pkg) {
return mediaFolder(pkg) + PLACEHOLDER_FILE;
}
/** @since 17.2.1 */
public static String objectPlaceholderPartName(OpcPackage pkg) {
return mediaFolder(pkg) + OBJECT_PLACEHOLDER_FILE;
}
private final OpcPackage pkg;
private final Set<String> objectPreviews;
private ImagePngPart placeholder;
private ImagePngPart objectPlaceholder;
public MediaReplacer(OpcPackage pkg) {
this(pkg, Collections.<String>emptySet());
}
/**
* @param pkg a docx or, since 17.2.1, a pptx
* @param objectPreviews "partName#relId" of the pictures which stood in for a
* removed OLE object or control: these get the labelled placeholder
*/
public MediaReplacer(OpcPackage pkg, Set<String> objectPreviews) {
this.pkg = pkg;
this.objectPreviews = objectPreviews;
}
/** true if some relationship to this part is a removed object's picture */
private boolean isObjectPreview(Part p) {
if (objectPreviews.isEmpty()) return false;
List<Base> sources = new ArrayList<Base>();
sources.add(pkg);
sources.addAll(pkg.getParts().getParts().values());
for (Base source : sources) {
RelationshipsPart rp = source.getRelationshipsPart();
if (rp == null || rp.getRelationships() == null) continue;
for (Relationship r : rp.getRelationships().getRelationship()) {
if ("External".equals(r.getTargetMode())) continue;
if (isObjectPreview(source, r) && rp.isTarget(p.getPartName(), r)) return true;
}
}
return false;
}
private boolean isObjectPreview(Base source, Relationship r) {
String sourceName = source instanceof Part ? ((Part) source).getPartName().getName() : "";
return objectPreviews.contains(sourceName + "#" + r.getId());
}
/**
* @return a line for the report saying what was done
*/
public String replace(Part p) throws Docx4JException {
if (p instanceof ImagePngPart
|| p instanceof ImageGifPart
|| p instanceof ImageJpegPart
|| p instanceof ImageBmpPart
|| p instanceof ImageTiffPart) {
if (isObjectPreview(p)) {
((BinaryPart) p).setBinaryData(Placeholders.objectRemovedPng());
return "replaced with the labelled placeholder (it was a removed object's picture)";
}
((BinaryPart) p).setBinaryData(PNG_IMAGE_DATA);
return "replaced with 2x2 pixels";
}
if (p instanceof DefaultXmlPart) {
// an SVG
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
((DefaultXmlPart) p).setDocument(
dbf.newDocumentBuilder().parse(new ByteArrayInputStream(BLANK_SVG.getBytes(StandardCharsets.UTF_8))));
} catch (Exception e) {
throw new Docx4JException("blank svg", e);
}
return "replaced with a blank svg";
}
// a metafile, eps, jpeg xr, webp, or an image docx4j could not read:
// point every relationship at the shared placeholder png (the labelled one where
// the picture stood for a removed object) and drop the part
boolean object = retargetToPlaceholder(p);
return "relationships retargeted to " + (object ? objectPlaceholderPartName(pkg) : placeholderPartName(pkg)) + "; part removed";
}
/** @return true if any relationship went to the labelled object placeholder */
private boolean retargetToPlaceholder(Part p) throws Docx4JException {
boolean object = false;
PartName oldName = p.getPartName();
List<Base> sources = new ArrayList<Base>();
sources.add(pkg);
sources.addAll(pkg.getParts().getParts().values());
for (Base source : sources) {
RelationshipsPart rp = source.getRelationshipsPart();
if (rp == null || rp.getRelationships() == null) continue;
// a snapshot: creating a placeholder part adds a relationship to the main document part
for (Relationship r : new ArrayList<Relationship>(rp.getRelationships().getRelationship())) {
if ("External".equals(r.getTargetMode())) continue;
if (rp.isTarget(oldName, r)) {
boolean preview = isObjectPreview(source, r);
ImagePngPart png = preview ? objectPlaceholder() : placeholder();
object |= preview;
r.setTarget(relativize(rp.getSourceURI(), png.getPartName().getURI()));
}
}
}
pkg.getParts().remove(oldName);
pkg.getContentTypeManager().removeOverrideContentType(oldName);
return object;
}
private ImagePngPart placeholder() throws Docx4JException {
if (placeholder == null) placeholder = placeholderPart(placeholderPartName(pkg), PNG_IMAGE_DATA);
return placeholder;
}
private ImagePngPart objectPlaceholder() throws Docx4JException {
if (objectPlaceholder == null) objectPlaceholder = placeholderPart(objectPlaceholderPartName(pkg), Placeholders.objectRemovedPng());
return objectPlaceholder;
}
private ImagePngPart placeholderPart(String name, byte[] bytes) throws Docx4JException {
Part existing = pkg.getParts().get(new PartName(name));
if (existing instanceof ImagePngPart) return (ImagePngPart) existing;
ImagePngPart part = new ImagePngPart(new PartName(name));
part.setBinaryData(bytes);
if (pkg instanceof WordprocessingMLPackage) {
// registers the part, its content type and a relationship from the main document part
((WordprocessingMLPackage) pkg).getMainDocumentPart().addTargetPart(part, AddPartBehaviour.REUSE_EXISTING);
} else {
// a pptx or xlsx: the retargeted relationships (from the slides or drawings) are the
// ones which reach it; the presentation and workbook parts carry no image relationships
part.setPackage(pkg);
pkg.getParts().put(part);
pkg.getContentTypeManager().addDefaultContentType("png", ContentTypes.IMAGE_PNG);
}
return part;
}
static String relativize(URI source, URI target) {
String rel = URIHelper.relativizeURI(source, target).toString();
if (source.getPath().equals("/") && rel.startsWith("/")) {
rel = rel.substring(1);
}
return rel;
}
/**
* Removes a part from the package: every relationship which points at it (from
* the package or any part), its own targets recursively, its content-type
* override, and the part itself.
*
* @return the names of the parts removed (the part and, recursively, its targets)
*/
static List<PartName> removePart(OpcPackage pkg, Part p) {
List<PartName> removed = new ArrayList<PartName>();
PartName name = p.getPartName();
List<Base> sources = new ArrayList<Base>();
sources.add(pkg);
sources.addAll(pkg.getParts().getParts().values());
for (Base source : sources) {
RelationshipsPart rp = source.getRelationshipsPart();
if (rp == null || rp.getRelationships() == null) continue;
List<Relationship> toGo = new ArrayList<Relationship>();
for (Relationship r : rp.getRelationships().getRelationship()) {
if ("External".equals(r.getTargetMode())) continue;
try {
if (rp.isTarget(name, r)) toGo.add(r);
} catch (Exception e) {
log.debug("cannot resolve " + r.getTarget() + ": " + e);
}
}
for (Relationship r : toGo) {
rp.removeRelationship(r);
}
}
// the part's own targets go with it (an embedded package's, an ActiveX part's binary)
if (p.getRelationshipsPart() != null && p.getRelationshipsPart().getRelationships() != null) {
for (Relationship r : new ArrayList<Relationship>(p.getRelationshipsPart().getRelationships().getRelationship())) {
if ("External".equals(r.getTargetMode())) continue;
Part target = p.getRelationshipsPart().getPart(r);
if (target != null && target != p && stillReferencedElsewhere(pkg, target, p) == false) {
removed.addAll(removePart(pkg, target));
}
}
}
pkg.getParts().remove(name);
pkg.getContentTypeManager().removeOverrideContentType(name);
removed.add(name);
return removed;
}
/** true if some part other than {@code except} (or the package) has a relationship to {@code target} */
private static boolean stillReferencedElsewhere(OpcPackage pkg, Part target, Part except) {
List<Base> sources = new ArrayList<Base>();
sources.add(pkg);
sources.addAll(pkg.getParts().getParts().values());
for (Base source : sources) {
if (source == except) continue;
RelationshipsPart rp = source.getRelationshipsPart();
if (rp == null || rp.getRelationships() == null) continue;
for (Relationship r : rp.getRelationships().getRelationship()) {
if ("External".equals(r.getTargetMode())) continue;
try {
if (rp.isTarget(target.getPartName(), r)) return true;
} catch (Exception e) {
// ignore
}
}
}
return false;
}
}
@@ -0,0 +1,145 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.util.ArrayList;
import java.util.List;
import org.docx4j.docProps.core.CoreProperties;
import org.docx4j.docProps.core.dc.elements.SimpleLiteral;
import org.docx4j.docProps.coverPageProps.CoverPageProperties;
import org.docx4j.docProps.extended.Properties;
import org.docx4j.openpackaging.Base;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.parts.DocPropsCoverPagePart;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.relationships.RelationshipsPart;
import org.docx4j.relationships.Relationship;
/**
* The package-level metadata: docProps core and app, the cover-page properties,
* and every relationship which points outside the package.
*
* @since 17.2.0
*/
public class MetadataScrubber {
/** what an external target becomes; RFC 6761 reserves .invalid, so it resolves nowhere */
public static final String EXTERNAL_PLACEHOLDER = "http://example.invalid/";
private final OpcPackage pkg;
private int externals = 0;
public MetadataScrubber(OpcPackage pkg) {
this.pkg = pkg;
}
/**
* docProps/core.xml: every descriptive property and identity cleared, the dates
* fixed, the revision reset; docProps/app.xml: company, manager, template, the
* heading and part titles (which are the document's headings), the hyperlink
* list and base, the signature; the cover-page part's company details.
*/
public void scrubDocProps() throws Docx4JException {
if (pkg.getDocPropsCorePart() != null && pkg.getDocPropsCorePart().getContents() != null) {
CoreProperties core = pkg.getDocPropsCorePart().getContents();
core.setCategory(null);
core.setContentStatus(null);
core.setCreator(null);
core.setDescription(null);
core.setIdentifier(null);
core.setKeywords(null);
core.setSubject(null);
core.setTitle(null);
core.setLastModifiedBy(null);
core.setLastPrinted(null);
core.setVersion(null);
if (core.getRevision() != null) core.setRevision("1");
if (core.getCreated() != null) core.setCreated(fixedDateLiteral(core.getCreated()));
if (core.getModified() != null) core.setModified(fixedDateLiteral(core.getModified()));
}
if (pkg.getDocPropsExtendedPart() != null && pkg.getDocPropsExtendedPart().getContents() != null) {
Properties app = pkg.getDocPropsExtendedPart().getContents();
app.setCompany(null);
app.setManager(null);
app.setTemplate(null);
app.setHeadingPairs(null);
app.setTitlesOfParts(null);
app.setHyperlinkBase(null);
app.setHLinks(null);
app.setDigSig(null);
app.setTotalTime(null);
app.setPresentationFormat(null); // pptx: "Widescreen", "On-screen Show (4:3)" - words which would survive the check
}
for (Part p : new ArrayList<Part>(pkg.getParts().getParts().values())) {
if (p instanceof DocPropsCoverPagePart) {
CoverPageProperties cpp = ((DocPropsCoverPagePart) p).getContents();
if (cpp != null) {
cpp.setAbstract(null);
cpp.setCompanyAddress(null);
cpp.setCompanyEmail(null);
cpp.setCompanyFax(null);
cpp.setCompanyPhone(null);
cpp.setPublishDate(null);
}
}
}
}
/** the same literal (it carries xsi:type="dcterms:W3CDTF"), with the fixed date as its content */
private static SimpleLiteral fixedDateLiteral(SimpleLiteral existing) {
existing.getContent().clear();
existing.getContent().add(Names.FIXED_DATE.toXMLFormat());
return existing;
}
/**
* Every relationship of {@code TargetMode="External"}, in the package's own
* relationships and in every part's (hyperlinks, linked images, linked OLE,
* the attached template, mail-merge sources), gets a placeholder target,
* numbered so distinct targets stay distinct.
*
* @return how many were replaced
*/
public int scrubExternalTargets() {
externals = 0;
scrubExternalTargets(pkg);
for (Part p : new ArrayList<Part>(pkg.getParts().getParts().values())) {
scrubExternalTargets(p);
}
return externals;
}
private void scrubExternalTargets(Base base) {
RelationshipsPart rp = base.getRelationshipsPart();
if (rp == null || rp.getRelationships() == null) return;
List<Relationship> rels = rp.getRelationships().getRelationship();
for (Relationship r : rels) {
if ("External".equals(r.getTargetMode())) {
externals++;
r.setTarget(EXTERNAL_PLACEHOLDER + externals);
}
}
}
}
@@ -0,0 +1,112 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* The 2018 comments docx4j does not bind, scrubbed as DOM in place:
* <ul>
* <li>PowerPoint's ([MS-PPTX] 2.3, namespace
* {@code http://schemas.microsoft.com/office/powerpoint/2018/8/main}, prefix
* p188): {@code /ppt/authors.xml} ({@code p188:authorLst}) and
* {@code /ppt/comments/modernComment_*.xml} ({@code p188:cmLst}) - an author's
* {@code name} and {@code initials} through {@link Names} (the same
* {@code Author n} as everywhere else), its {@code userId} (a directory id or
* email) replaced by that name and its {@code providerId} by {@code None}; every
* {@code created}, {@code startDate} and {@code dueDate} fixed; the text of every
* {@code a:t} scrambled. Comment ids, author ids, positions and the anchors
* ({@code ac:txMkLst}) are structure and stay.</li>
* <li>Excel's threaded comments ([MS-XLSX], namespace
* {@code http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments}):
* {@code /xl/persons/person.xml} ({@code personList/person}: {@code displayName}
* through {@link Names}, {@code userId} → the name, {@code providerId} → None)
* and {@code /xl/threadedComments/threadedComment*.xml}
* ({@code threadedComment}: {@code dT} fixed, the {@code text} scrambled; the
* cell reference, ids, parent ids, mentions and done flags stay).</li>
* </ul>
* Anything else with text is left for {@link Verify} to find.
*
* @since 17.2.1
*/
public class ModernCommentsScrubber {
private final Names names;
private final ScrambleText scrambler;
public ModernCommentsScrubber(Names names, ScrambleText scrambler) {
this.names = names;
this.scrambler = scrambler;
}
public void scrub(Node n) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
String mappedAuthor = null;
NamedNodeMap attrs = el.getAttributes();
// the name first, so the user id can take the mapped name
Attr name = attribute(attrs, local(el).equals("person") ? "displayName" : "name");
if (name != null && (local(el).equals("author") || local(el).equals("person"))) {
mappedAuthor = names.author(name.getValue());
name.setValue(mappedAuthor);
}
for (int i = 0; attrs != null && i < attrs.getLength(); i++) {
Attr a = (Attr) attrs.item(i);
String ln = local(a);
if (ln.equals("initials")) {
a.setValue(names.initials(a.getValue()));
} else if (ln.equals("userId")) {
a.setValue(mappedAuthor != null ? mappedAuthor : "Author");
} else if (ln.equals("providerId")) {
a.setValue("None");
} else if (ln.equals("created") || ln.equals("startDate") || ln.equals("dueDate") || ln.equals("dT")) {
a.setValue(Names.FIXED_DATE.toXMLFormat());
}
}
}
NodeList children = n.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node c = children.item(i);
if (c.getNodeType() == Node.TEXT_NODE || c.getNodeType() == Node.CDATA_SECTION_NODE) {
if (local(n).equals("t") || local(n).equals("text")) {
c.setNodeValue(scrambler.scramble(c.getNodeValue()));
}
} else {
scrub(c);
}
}
}
private static Attr attribute(NamedNodeMap attrs, String localName) {
for (int i = 0; attrs != null && i < attrs.getLength(); i++) {
Attr a = (Attr) attrs.item(i);
if (local(a).equals(localName)) return a;
}
return null;
}
private static String local(Node n) {
return n.getLocalName() == null ? n.getNodeName() : n.getLocalName();
}
}
@@ -0,0 +1,204 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.packages.SpreadsheetMLPackage;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart;
import org.docx4j.wml.Style;
import org.docx4j.wml.Styles;
/**
* The consistent renamings the anonymiser applies, shared by its visitors:
* <ul>
* <li>authors become {@code Author 1}, {@code Author 2}... in order of first
* appearance, the same name wherever it occurs (comments, tracked changes,
* people.xml), so who-replied-to-whom and which changes are one reviewer's
* survive (CR-019 decision 2); initials become {@code A1}, {@code A2}...;</li>
* <li>a bookmark, form-field or sequence name becomes {@code bm} plus a hash
* of the name: no pre-pass is needed for a REF in a header to still point at
* a bookmark in the body;</li>
* <li>a custom style id becomes {@code s} plus a hash; built-in styles (a name
* Word knows: KnownStyles.xml plus the document's own latent-style list) keep
* their names and ids, because Word identifies them by name;</li>
* <li>every date becomes {@link #FIXED_DATE};</li>
* <li>in a workbook (CR-019 phase 3), sheets become {@code Sheet1}, {@code Sheet2}...
* in workbook order (read up front, so a formula in any part maps the same way)
* and a defined name becomes {@code n_} plus a hash - an underscore keeps it from
* ever reading as a cell reference; the {@code _xlnm.} built-ins keep their names.</li>
* </ul>
*
* @since 17.2.0
*/
public class Names {
/** what every w:date, dateUtc and docProps date becomes */
public static final XMLGregorianCalendar FIXED_DATE;
static {
try {
FIXED_DATE = DatatypeFactory.newInstance().newXMLGregorianCalendar("2000-01-01T00:00:00Z");
} catch (DatatypeConfigurationException e) {
throw new IllegalStateException(e);
}
}
public static XMLGregorianCalendar fixedDate() {
return (XMLGregorianCalendar) FIXED_DATE.clone();
}
private final Map<String, String> authors = new LinkedHashMap<String, String>();
private final Map<String, String> initials = new LinkedHashMap<String, String>();
private final Set<String> builtInStyleNames = new HashSet<String>();
private final Set<String> builtInStyleIds = new HashSet<String>();
/** sheet name (lower-cased: Excel matches them case-insensitively) to Sheet<n> */
private final Map<String, String> sheets = new LinkedHashMap<String, String>();
/**
* @param pkg a docx (its own latent-style names join the built-in list) or, since
* 17.2.1, a pptx (no styles part: KnownStyles.xml alone)
*/
public Names(OpcPackage pkg) {
for (Style s : StyleDefinitionsPart.getKnownStyles().values()) {
if (s.getName() != null) builtInStyleNames.add(key(s.getName().getVal()));
builtInStyleIds.add(s.getStyleId());
}
if (pkg instanceof WordprocessingMLPackage
&& ((WordprocessingMLPackage) pkg).getMainDocumentPart() != null
&& ((WordprocessingMLPackage) pkg).getMainDocumentPart().getStyleDefinitionsPart() != null) {
try {
Styles styles = ((WordprocessingMLPackage) pkg).getMainDocumentPart().getStyleDefinitionsPart().getContents();
if (styles != null && styles.getLatentStyles() != null) {
for (Styles.LatentStyles.LsdException e : styles.getLatentStyles().getLsdException()) {
builtInStyleNames.add(key(e.getName()));
}
}
if (styles != null) {
for (Style s : styles.getStyle()) {
if (s.getName() != null && isBuiltInStyleName(s.getName().getVal())) {
builtInStyleIds.add(s.getStyleId());
}
}
}
} catch (Exception e) {
// no styles part contents: only KnownStyles then
}
}
if (pkg instanceof SpreadsheetMLPackage && ((SpreadsheetMLPackage) pkg).getWorkbookPart() != null) {
try {
org.xlsx4j.sml.Workbook wb = ((SpreadsheetMLPackage) pkg).getWorkbookPart().getContents();
if (wb != null && wb.getSheets() != null) {
int n = 0;
for (org.xlsx4j.sml.Sheet sheet : wb.getSheets().getSheet()) {
n++;
if (sheet.getName() != null) sheets.put(key(sheet.getName()), "Sheet" + n);
}
}
} catch (Exception e) {
// no workbook contents: sheet names are then scrambled like any other text
}
}
}
/** Sheet<n> for a sheet of the workbook (by name, case-insensitively); null for an unknown name. */
public String sheet(String name) {
if (name == null) return null;
return sheets.get(key(name));
}
/** true if the workbook has a sheet of this name */
public boolean isSheet(String name) {
return name != null && sheets.containsKey(key(name));
}
/** The anonymised defined name: the _xlnm. built-ins as they are, else n_ + hash. */
public static String definedName(String name) {
if (name == null) return null;
if (name.startsWith("_xlnm.") || name.startsWith("_xlfn.")) return name;
return "n_" + hash(name);
}
private static String key(String name) {
return name == null ? "" : name.trim().toLowerCase(Locale.ROOT);
}
/** A style name Word ships (heading 1, Table Grid, ...): kept, since Word identifies built-in styles by name. */
public boolean isBuiltInStyleName(String name) {
return name != null && builtInStyleNames.contains(key(name));
}
/** The id of a built-in style in this document: kept. */
public boolean isBuiltInStyleId(String styleId) {
return styleId != null && builtInStyleIds.contains(styleId);
}
/** The anonymised id of a style: itself for a built-in, else s + hash. */
public String styleId(String styleId) {
if (styleId == null || isBuiltInStyleId(styleId)) return styleId;
return "s" + hash(styleId);
}
/** The anonymised name of a bookmark, form field or sequence: bm + hash, stable across parts. */
public static String identifier(String name) {
if (name == null) return null;
return "bm" + hash(name);
}
/** Author n, allotted in order of first appearance. */
public String author(String author) {
if (author == null) return null;
String mapped = authors.get(author);
if (mapped == null) {
mapped = "Author " + (authors.size() + 1);
authors.put(author, mapped);
}
return mapped;
}
/** An, allotted in order of first appearance. */
public String initials(String value) {
if (value == null) return null;
String mapped = initials.get(value);
if (mapped == null) {
mapped = "A" + (initials.size() + 1);
initials.put(value, mapped);
}
return mapped;
}
/** How many distinct authors were renamed. */
public int authorCount() {
return authors.size();
}
static String hash(String s) {
return Integer.toUnsignedString(s.hashCode());
}
}
@@ -0,0 +1,239 @@
package org.docx4j.anon;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import org.docx4j.openpackaging.contenttype.ContentTypes;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.parts.DefaultXmlPart;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.PartName;
/**
* The table the anonymiser consults for every part: what class of thing it is,
* and so what the walk does with it (CR-019: "PartsAnalyzer's classification
* becomes the table the walk consults: per part class, one of scramble / clear /
* replace / remove / keep-unsafe").
* <p>
* Anything not named here is {@link Treatment#UNSCRUBBABLE}: a part the tool
* cannot make clean is removed (STRICT) or kept and reported (KEEP), never
* silently passed through.
*/
public class PartsAnalyzer {
public enum Treatment {
/** structure only, nothing to do (a theme's colours, a chart style) */
SAFE,
/** a JAXB part the walk scrambles and scrubs */
SCRUB,
/** docProps and the like: cleared field by field */
METADATA,
/** an image: placeholder pixels of the same class */
REPLACE_IMAGE,
/** removed in either mode: custom XML, glossary, custom properties, thumbnails, signatures, labels */
REMOVE,
/** cannot be made clean (OLE, altChunk, VBA, embedded fonts, audio and video, unknown parts): removed in STRICT, kept and reported in KEEP */
UNSCRUBBABLE
}
public static Treatment classify(Part p) {
String name = p.getPartName().getName();
// ---- removed whatever the mode (the module has always removed these)
if (p instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePart
|| p instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePropertiesPart
|| p instanceof org.docx4j.openpackaging.parts.opendope.JaxbCustomXmlDataStoragePart
|| p instanceof org.docx4j.openpackaging.parts.opendope.ComponentsPart
|| p instanceof org.docx4j.openpackaging.parts.opendope.ConditionsPart
|| p instanceof org.docx4j.openpackaging.parts.opendope.QuestionsPart
|| p instanceof org.docx4j.openpackaging.parts.opendope.StandardisedAnswersPart
|| p instanceof org.docx4j.openpackaging.parts.opendope.XPathsPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.BibliographyPart // b:Sources: names and titles
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.GlossaryDocumentPart
|| p instanceof org.docx4j.openpackaging.parts.DocPropsCustomPart
|| name.startsWith("/word/glossary")
|| name.startsWith("/docProps/thumbnail.")
|| name.startsWith("/_xmlsignatures/") // a signature over the original content, naming the signer
|| name.startsWith("/docMetadata/") // sensitivity label: tenant and label ids
|| name.equals("/word/stylesWithEffects.xml")) {
return Treatment.REMOVE;
}
// ---- metadata, cleared field by field
if (p instanceof org.docx4j.openpackaging.parts.DocPropsCorePart
|| p instanceof org.docx4j.openpackaging.parts.DocPropsExtendedPart
|| p instanceof org.docx4j.openpackaging.parts.DocPropsCoverPagePart) {
return Treatment.METADATA;
}
// ---- images: placeholder pixels
if (p instanceof org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.MetafilePart) {
return Treatment.REPLACE_IMAGE;
}
if (p instanceof DefaultXmlPart && isSvg(p)) {
return Treatment.REPLACE_IMAGE;
}
// ---- the 2018 PowerPoint comments and their authors, and Excel's threaded comments and
// persons: not bound, so a DefaultXmlPart, scrubbed as DOM (ModernCommentsScrubber)
if (p instanceof DefaultXmlPart && isModernComments(p)) {
return Treatment.SCRUB;
}
// ---- SpreadsheetML (CR-019 phase 3): removed whatever the mode - a pivot cache is a copy
// of its source data, and a pivot table, slicer or timeline without its cache is a
// repair prompt, so they go together (the pivot's cells stay as values); the data
// model is data; an add-in's custom data and a survey are text
if (p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.PivotCacheDefinition
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.PivotCacheRecords
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.PivotTable
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.SlicerCachePart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.SlicersPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.TimelineCachePart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.TimelinesPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.DataModelPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.CustomDataPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.CustomDataPropertiesPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.SurveyPart) {
return Treatment.REMOVE;
}
// ---- structure
if (p instanceof org.docx4j.openpackaging.parts.DrawingML.ChartStylePart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.ChartColorStylePart
|| p instanceof org.docx4j.openpackaging.parts.relationships.RelationshipsPart) {
return Treatment.SAFE;
}
// ---- JAXB parts the walk covers
if (p instanceof org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.FooterPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.FootnotesPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.EndnotesPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.CommentsPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.CommentsExtendedPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.CommentsIdsPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.CommentsExtensiblePart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.PeoplePart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.DocumentSettingsPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.WebSettingsPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.NumberingDefinitionsPart
|| p instanceof org.docx4j.openpackaging.parts.WordprocessingML.FontTablePart
|| p instanceof org.docx4j.openpackaging.parts.ThemePart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.ThemeOverridePart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.Chart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.ChartExSpacePart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.ChartShapePart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.DiagramDataPart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.DiagramDrawingPart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.DiagramLayoutPart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.DiagramLayoutHeaderPart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.DiagramColorsPart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.DiagramStylePart
|| p instanceof org.docx4j.openpackaging.parts.DrawingML.Drawing) {
return Treatment.SCRUB;
}
// ---- PresentationML (CR-019 phase 2): the slides and their masters, layouts and
// notes (a:t in every a:p), the presentation (section names, custom shows, the
// modify verifier, the embedded-font list), legacy comments and their authors, tags,
// table styles (names)
if (p instanceof org.docx4j.openpackaging.parts.PresentationML.MainPresentationPart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.SlidePart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.SlideLayoutPart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.SlideMasterPart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.NotesSlidePart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.NotesMasterPart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.HandoutMasterPart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.CommentsPart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.CommentAuthorsPart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.TagsPart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.TableStylesPart) {
return Treatment.SCRUB;
}
// structure, but walked (presProps carries the HTML publish target and the show's custom-show id)
if (p instanceof org.docx4j.openpackaging.parts.PresentationML.PresentationPropertiesPart
|| p instanceof org.docx4j.openpackaging.parts.PresentationML.ViewPropertiesPart) {
return Treatment.SAFE;
}
// ---- SpreadsheetML: the workbook (sheet and defined names, protection, file sharing),
// the sheets (cells, formulas, headers, validations, filters), shared strings, styles
// (custom style names), tables, comments and their authors, connections and query
// tables (connection strings, commands, URLs), external links (cached values, sheet
// names), form-control properties (linked-cell formulas, list items); VML (comment
// and control shapes)
if (p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.WorkbookPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.WorksheetPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.ChartsheetPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.SharedStrings
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.Styles
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.TablePart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.CommentsPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.ConnectionsPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.QueryTablePart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.ExternalLinkPart
|| p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.ControlPropertiesPart
|| p instanceof org.docx4j.openpackaging.parts.VMLPart) {
return Treatment.SCRUB;
}
if (p instanceof org.docx4j.openpackaging.parts.SpreadsheetML.CalcChain) {
return Treatment.SAFE; // cell references only
}
// ---- everything else: OLE and embedded packages, altChunk, VBA, embedded fonts
// (FontDataPart included), printer settings, ActiveX, ink, web extensions, audio and
// video, unknown XML and binaries (a workbook's metadata and rich-value parts among them)
return Treatment.UNSCRUBBABLE;
}
/**
* The 2018 comments part (p188:cmLst) or its authors part (p188:authorLst), or Excel's
* threaded comments or persons part, by content type
*/
static boolean isModernComments(Part p) {
try {
String ct = p.getContentType();
return ContentTypes.PRESENTATIONML_MODERN_COMMENTS.equals(ct)
|| ContentTypes.PRESENTATIONML_MODERN_COMMENT_AUTHORS.equals(ct)
|| ContentTypes.SPREADSHEETML_THREADED_COMMENTS.equals(ct)
|| ContentTypes.SPREADSHEETML_PERSONS.equals(ct);
} catch (Exception e) {
return false;
}
}
static boolean isSvg(Part p) {
try {
String ct = p.getContentType();
if (ct != null) return ct.equals(ContentTypes.IMAGE_SVG);
} catch (Exception e) {
// fall through
}
return p.getPartName().getName().toLowerCase().endsWith(".svg");
}
/**
* The parts the tool cannot make clean.
*
* @deprecated since 17.2.0: {@link Anonymize} consults {@link #classify(Part)}; this
* remains for callers of the older API and no longer touches the cover page part
*/
@Deprecated
public static HashSet<Part> identifyUnsafeParts(Set<Entry<PartName, Part>> parts) throws Docx4JException {
HashSet<Part> unsafeParts = new HashSet<Part>();
for (Entry<PartName, Part> entry : parts) {
if (classify(entry.getValue()) == Treatment.UNSCRUBBABLE) {
unsafeParts.add(entry.getValue());
}
}
return unsafeParts;
}
}
@@ -0,0 +1,109 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* What stands in for a removed object. An object's footprint survives, because
* page flow is what the anonymised document is for, but the footprint says
* what it was: an OLE object or ActiveX control leaves its picture, and the
* picture is a generated image labelled "OLE object removed by
* docx4j anon"; an altChunk, which has no footprint of its own, leaves a
* marker paragraph. The words of the markers are in {@link Verify}'s allowed
* vocabulary.
*
* @since 17.2.0
*/
class Placeholders {
private static final Logger log = LoggerFactory.getLogger(Placeholders.class);
static final String OBJECT_REMOVED = "OLE object removed";
static final String ALTCHUNK_REMOVED = "[altChunk removed by docx4j anon]";
static final String BY = "by docx4j anon";
private static byte[] objectRemovedPng;
/**
* A 480x240 PNG, light grey with a border, labelled {@link #OBJECT_REMOVED} /
* {@link #BY}; Word scales it to the object's extent. Falls back to the 2x2
* pixels if the image cannot be drawn (no java.desktop at run time).
*/
static synchronized byte[] objectRemovedPng() {
if (objectRemovedPng != null) return objectRemovedPng;
try {
int w = 480, h = 240;
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setColor(new Color(0xEE, 0xEE, 0xEE));
g.fillRect(0, 0, w, h);
g.setColor(new Color(0x88, 0x88, 0x88));
g.setStroke(new BasicStroke(4));
g.drawRect(2, 2, w - 4, h - 4);
g.setColor(new Color(0x33, 0x33, 0x33));
centred(g, OBJECT_REMOVED, new Font(Font.SANS_SERIF, Font.BOLD, 36), w, h / 2 - 12);
centred(g, BY, new Font(Font.SANS_SERIF, Font.PLAIN, 24), w, h / 2 + 36);
g.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
objectRemovedPng = baos.toByteArray();
} catch (Throwable t) {
log.warn("cannot draw the placeholder image (" + t + "); using the 2x2 pixels");
objectRemovedPng = MediaReplacer.PNG_IMAGE_DATA;
}
return objectRemovedPng;
}
private static void centred(Graphics2D g, String text, Font font, int width, int baseline) {
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
g.drawString(text, (width - fm.stringWidth(text)) / 2, baseline);
}
/** The paragraph an altChunk becomes. */
static P altChunkRemoved() {
ObjectFactory f = new ObjectFactory();
P p = f.createP();
R r = f.createR();
Text t = f.createText();
t.setValue(ALTCHUNK_REMOVED);
r.getContent().add(f.createRT(t));
p.getContent().add(r);
return p;
}
}
@@ -0,0 +1,80 @@
package org.docx4j.anon;
import org.docx4j.fonts.RunFontSelector;
import org.docx4j.fonts.RunFontSelector.RunFontCharacterVisitor;
import org.w3c.dom.Document;
public class RunFontCharVisitorMinimal implements RunFontCharacterVisitor {
StringBuilder sb = new StringBuilder(1024);
@Override
public void setDocument(Document document) {}
public void addCharacterToCurrent(char c) {
sb.append(c);
}
@Override
public void addCodePointToCurrent(int cp) {
sb.append(
new String(Character.toChars(cp)));
}
@Override
public Object getResult() {
return sb.toString();
}
private RunFontSelector runFontSelector;
@Override
public void setRunFontSelector(RunFontSelector runFontSelector) {
this.runFontSelector = runFontSelector;
}
@Override
public void setFallbackFont(String fontname) {}
@Override
public void finishPrevious() {
}
@Override
public void createNew() {
sb = new StringBuilder(1024);
fontname = null;
}
@Override
public void setMustCreateNewFlag(boolean val) {
// TODO Auto-generated method stub
}
@Override
public boolean isReusable() {
// TODO Auto-generated method stub
return false;
}
String fontname;
public String getFontname() {
return fontname;
}
@Override
public void fontAction(String fontname) {
this.fontname = fontname;
}
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,232 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.util.regex.Pattern;
/**
* Scrubs a spreadsheet formula (a cell's {@code f}, a defined name, a chart's
* {@code c:f}, a conditional format's or validation's formula, an
* {@code xm:f}) so that it still computes over the anonymised workbook:
* <ul>
* <li>string literals ({@code "..."}) are scrambled;</li>
* <li>numeric constants have their digits randomised ({@link ScrambleText#number}),
* unless numbers are kept; a row range ({@code 1:1}) is a reference, not a
* constant, and stays;</li>
* <li>sheet names ({@code 'My Sheet'!A1}, {@code Sales!A1}) become the
* workbook's {@code Sheet<n>} ({@link Names#sheet}); a sheet of an external
* workbook ({@code '[1]Sheet'!A1}) is scrambled consistently with the external
* link part;</li>
* <li>defined names become {@code n_<hash>} ({@link Names#definedName});</li>
* <li>structured references ({@code Sales[Amount]}, {@code Sales[[#This Row],[Amount]]})
* keep their keywords and have the table and column names scrambled
* consistently with the table part and the header cells;</li>
* <li>cell and range references, function names, operators, the {@code _xlfn.}
* prefixes, {@code TRUE}/{@code FALSE} and error literals stay.</li>
* </ul>
*
* @since 17.2.1
*/
public class SmlFormulas {
private final ScrambleText scrambler;
private final Names names;
/** A1-style reference: an optional column (with optional $) and row; also column-only and row-only when next to a colon */
private static final Pattern CELL_REF = Pattern.compile("^\\$?[A-Za-z]{1,3}\\$?[0-9]+$");
private static final Pattern COLUMN_REF = Pattern.compile("^\\$?[A-Za-z]{1,3}$");
private static final Pattern R1C1 = Pattern.compile("^([Rr](\\[-?[0-9]+\\]|[0-9]+)?[Cc](\\[-?[0-9]+\\]|[0-9]+)?|[Rr]|[Cc])$");
public SmlFormulas(ScrambleText scrambler, Names names) {
this.scrambler = scrambler;
this.names = names;
}
public String scrub(String formula) {
if (formula == null || formula.isEmpty()) return formula;
StringBuilder out = new StringBuilder();
int i = 0, n = formula.length();
while (i < n) {
char c = formula.charAt(i);
if (c == '"') {
// a string literal, "" escaping a quote
int j = i + 1;
StringBuilder lit = new StringBuilder();
while (j < n) {
if (formula.charAt(j) == '"') {
if (j + 1 < n && formula.charAt(j + 1) == '"') {
lit.append('"');
j += 2;
continue;
}
break;
}
lit.append(formula.charAt(j));
j++;
}
out.append('"').append(scrambler.scramble(lit.toString()).replace("\"", "\"\"")).append('"');
i = Math.min(j + 1, n);
} else if (c == '\'') {
// a quoted sheet name (or '[n]Sheet' of an external book), '' escaping a quote
int j = i + 1;
StringBuilder name = new StringBuilder();
while (j < n) {
if (formula.charAt(j) == '\'') {
if (j + 1 < n && formula.charAt(j + 1) == '\'') {
name.append('\'');
j += 2;
continue;
}
break;
}
name.append(formula.charAt(j));
j++;
}
out.append('\'').append(sheetName(name.toString()).replace("'", "''")).append('\'');
i = Math.min(j + 1, n);
} else if (c == '[') {
// a structured reference's brackets, or an external book number [1] before a sheet
int j = matchingBracket(formula, i);
String inner = formula.substring(i + 1, j);
if (inner.matches("-?[0-9]+")) { // [1] before an external sheet, [-1] of R1C1
out.append('[').append(inner).append(']');
} else {
out.append('[').append(structured(inner)).append(']');
}
i = j + 1;
} else if (c == '#') {
// an error literal: #REF!, #N/A, #DIV/0!, #NAME?, #GETTING_DATA
int j = i + 1;
while (j < n && (Character.isLetterOrDigit(formula.charAt(j)) || "/_!?".indexOf(formula.charAt(j)) >= 0)) j++;
out.append(formula, i, j);
i = j;
} else if (Character.isDigit(c) || (c == '.' && i + 1 < n && Character.isDigit(formula.charAt(i + 1)))) {
int j = i;
while (j < n && (Character.isDigit(formula.charAt(j)) || formula.charAt(j) == '.')) j++;
if (j < n && (formula.charAt(j) == 'E' || formula.charAt(j) == 'e')) {
int k = j + 1;
if (k < n && (formula.charAt(k) == '+' || formula.charAt(k) == '-')) k++;
if (k < n && Character.isDigit(formula.charAt(k))) {
while (k < n && Character.isDigit(formula.charAt(k))) k++;
j = k;
}
}
String number = formula.substring(i, j);
boolean rowRange = (i > 0 && formula.charAt(i - 1) == ':') || (j < n && formula.charAt(j) == ':');
out.append(rowRange ? number : scrambler.number(number));
i = j;
} else if (Character.isLetter(c) || c == '_' || c == '$' || c == '\\') {
// an identifier: function, cell reference, sheet name, table name, defined name
int j = i;
while (j < n && (Character.isLetterOrDigit(formula.charAt(j)) || "_.$\\".indexOf(formula.charAt(j)) >= 0)) j++;
String ident = formula.substring(i, j);
int k = j;
while (k < n && formula.charAt(k) == ' ') k++;
char next = k < n ? formula.charAt(k) : 0;
out.append(identifier(ident, next, i > 0 ? formula.charAt(i - 1) : 0));
i = j;
} else {
out.append(c);
i++;
}
}
return out.toString();
}
private String identifier(String ident, char next, char previous) {
if (next == '(') return ident; // a function
if (R1C1.matcher(ident).matches()) return ident; // R1C1: R[-1]C, RC[1], R2C3 (Excel reserves R and C, so never a name)
if (next == '!') return previous == ']' ? scrambler.consistent(ident) : sheetName(ident); // [1]Sheet1! is an external book's sheet
if (next == '[') return scrambler.consistentIdentifier(ident); // a table's display name, as the table part maps it
if (CELL_REF.matcher(ident).matches()) return ident;
if (COLUMN_REF.matcher(ident).matches() && (next == ':' || previous == ':')) return ident;
String upper = ident.toUpperCase(java.util.Locale.ROOT);
if (upper.equals("TRUE") || upper.equals("FALSE")) return ident;
if (ident.startsWith("_xlfn.") || ident.startsWith("_xlws.") || ident.startsWith("_xlpm.")) return ident;
return Names.definedName(ident);
}
/** a sheet name, with an optional [n] external-book prefix */
private String sheetName(String name) {
String prefix = "";
String rest = name;
if (name.startsWith("[")) {
int close = name.indexOf(']');
if (close > 0) {
prefix = name.substring(0, close + 1);
rest = name.substring(close + 1);
}
}
if (prefix.isEmpty() && names.isSheet(rest)) return names.sheet(rest);
if (prefix.isEmpty()) return scrambler.consistent(rest); // a sheet the workbook does not list
// an external workbook's sheet: the same mapping as its external link part's sheetNames
return prefix + scrambler.consistent(rest);
}
/** the inside of a structured reference's brackets: keywords kept, column names scrambled consistently */
private String structured(String inner) {
String trimmed = inner.trim();
if (trimmed.isEmpty()) return inner;
if (trimmed.startsWith("#")) return inner; // [#Headers], [#This Row], [#All], [#Data], [#Totals]
if (trimmed.startsWith("@")) return "@" + structured(trimmed.substring(1));
if (trimmed.startsWith("[")) {
// [[#This Row],[Amount]] or [[Col A]:[Col B]]
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < trimmed.length()) {
char c = trimmed.charAt(i);
if (c == '[') {
int j = matchingBracket(trimmed, i);
sb.append('[').append(structured(trimmed.substring(i + 1, j))).append(']');
i = j + 1;
} else {
sb.append(c);
i++;
}
}
return sb.toString();
}
return scrambler.consistent(inner);
}
private static int matchingBracket(String s, int open) {
int depth = 0;
for (int i = open; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\'' && i + 1 < s.length()) {
i++; // an escaped special character inside a structured reference
continue;
}
if (c == '[') depth++;
if (c == ']') {
depth--;
if (depth == 0) return i;
}
}
return s.length() - 1;
}
}
@@ -0,0 +1,658 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.util.List;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import jakarta.xml.bind.JAXBElement;
import org.docx4j.XmlUtils;
import org.docx4j.anon.JaxbGraphWalker.Action;
import org.xlsx4j.sml.CTAuthors;
import org.xlsx4j.sml.CTCellFormula;
import org.xlsx4j.sml.CTCellSmartTagPr;
import org.xlsx4j.sml.CTCellStyle;
import org.xlsx4j.sml.CTCfRule;
import org.xlsx4j.sml.CTConnection;
import org.xlsx4j.sml.CTControls;
import org.xlsx4j.sml.CTCustomFilter;
import org.xlsx4j.sml.CTCustomWorkbookView;
import org.xlsx4j.sml.CTDataRef;
import org.xlsx4j.sml.CTDataValidation;
import org.xlsx4j.sml.CTDbPr;
import org.xlsx4j.sml.CTDdeItem;
import org.xlsx4j.sml.CTDdeLink;
import org.xlsx4j.sml.CTDefinedName;
import org.xlsx4j.sml.CTExternalCell;
import org.xlsx4j.sml.CTExternalDefinedName;
import org.xlsx4j.sml.CTExternalSheetName;
import org.xlsx4j.sml.CTFileSharing;
import org.xlsx4j.sml.CTFilter;
import org.xlsx4j.sml.CTFunctionGroup;
import org.xlsx4j.sml.CTHeaderFooter;
import org.xlsx4j.sml.CTHyperlink;
import org.xlsx4j.sml.CTInputCells;
import org.xlsx4j.sml.CTMap;
import org.xlsx4j.sml.CTOleItem;
import org.xlsx4j.sml.CTOleObjects;
import org.xlsx4j.sml.CTParameter;
import org.xlsx4j.sml.CTPhoneticRun;
import org.xlsx4j.sml.CTPivotCaches;
import org.xlsx4j.sml.CTQueryTable;
import org.xlsx4j.sml.CTQueryTableField;
import org.xlsx4j.sml.CTRElt;
import org.xlsx4j.sml.CTRst;
import org.xlsx4j.sml.CTSheetProtection;
import org.xlsx4j.sml.CTSmartTagType;
import org.xlsx4j.sml.CTTable;
import org.xlsx4j.sml.CTTableColumn;
import org.xlsx4j.sml.CTTableFormula;
import org.xlsx4j.sml.CTTableStyle;
import org.xlsx4j.sml.CTTableStyleInfo;
import org.xlsx4j.sml.CTTextPr;
import org.xlsx4j.sml.CTWebPr;
import org.xlsx4j.sml.CTWebPublishItem;
import org.xlsx4j.sml.CTWorkbookProtection;
import org.xlsx4j.sml.CTXstringWhitespace;
import org.xlsx4j.sml.Cell;
import org.xlsx4j.sml.STCellType;
import org.xlsx4j.sml.Sheet;
/**
* The third visitor of the anonymiser's walk, for a workbook (CR-019 phase 3):
* everything SpreadsheetML-typed that carries text, numbers, names or
* identities. The DrawingML and chart classes a workbook shares with the other
* formats are {@link ScrambleText}'s and {@link MarkupScrubber}'s.
* <ul>
* <li>Text: shared and inline strings (the same string always to the same
* output, so a table column's name still equals its header cell), formula
* string results, comments and their authors, headers and footers (codes
* kept), hyperlink display text, data-validation prompts and errors,
* conditional-format text, filter values, defined-name comments, custom cell
* style names, table and query-table names, connection names and descriptions.</li>
* <li>Numbers: cell values and formula constants have their digits randomised
* ({@link ScrambleText#number}; decision 3 - kept with
* {@link ScrambleText#setKeepNumbers}); booleans and errors stay.</li>
* <li>Formulas ({@link SmlFormulas}): cells, defined names, tables' calculated
* columns, validations, conditional formats, sparklines, form controls, chart
* references; sheet names become {@code Sheet<n>} everywhere.</li>
* <li>Identities and references: the file-sharing user name, comment authors,
* every password hash and salt (sheet, workbook, file sharing); connection
* strings, commands, source files and URLs; DDE and OLE link names.</li>
* <li>STRICT: the pivot-cache list, the slicer, timeline and data-model
* extensions, OLE objects and ActiveX controls, and a cell's rich-value
* metadata indexes go (their parts are removed).</li>
* </ul>
*
* @since 17.2.1
*/
public class SpreadsheetScrubber implements JaxbGraphWalker.Visitor {
private final ScrambleText scrambler;
private final SmlFormulas formulas;
private final Names names;
private final boolean strict;
private final Consumer<String> notes;
/** "partName#relId" of the pictures which stood for a removed OLE object: MediaReplacer labels them */
private final java.util.Set<String> objectPreviews;
private String currentPartName = "";
/** Excel's built-in table and pivot style names, which name nothing */
private static final Pattern BUILT_IN_TABLE_STYLE = Pattern.compile("^(TableStyle|PivotStyle)(Light|Medium|Dark)[0-9]+$");
public SpreadsheetScrubber(ScrambleText scrambler, Names names, boolean strict, Consumer<String> notes,
java.util.Set<String> objectPreviews) {
this.scrambler = scrambler;
this.formulas = new SmlFormulas(scrambler, names);
this.names = names;
this.strict = strict;
this.notes = notes;
this.objectPreviews = objectPreviews;
}
/** The part being walked: relationship ids are per part. */
public void setCurrentPart(org.docx4j.openpackaging.parts.Part part) {
currentPartName = part == null ? "" : part.getPartName().getName();
}
public SmlFormulas formulas() {
return formulas;
}
@Override
public Action visit(Object o, JAXBElement<?> wrapper) {
// ---- text
if (o instanceof CTRst) {
richText((CTRst) o);
return Action.SKIP_CHILDREN;
}
if (o instanceof Cell) {
Cell c = (Cell) o;
cellValue(c.getT(), c.getV(), v -> c.setV(v));
if (strict && (c.getCm() != 0 || c.getVm() != 0)) {
// rich-value and cell metadata indexes into parts the tool removes
c.setCm(null);
c.setVm(null);
}
return Action.CONTINUE; // its f and is
}
if (o instanceof CTExternalCell) {
CTExternalCell c = (CTExternalCell) o;
cellValue(c.getT(), c.getV(), v -> c.setV(v));
c.setVm(null);
return Action.SKIP_CHILDREN;
}
if (o instanceof CTCellFormula) {
CTCellFormula f = (CTCellFormula) o;
f.setValue(formulas.scrub(f.getValue()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTTableFormula) {
CTTableFormula f = (CTTableFormula) o;
f.setValue(formulas.scrub(f.getValue()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTHeaderFooter) {
CTHeaderFooter hf = (CTHeaderFooter) o;
hf.setOddHeader(scrambler.headerFooter(hf.getOddHeader()));
hf.setOddFooter(scrambler.headerFooter(hf.getOddFooter()));
hf.setEvenHeader(scrambler.headerFooter(hf.getEvenHeader()));
hf.setEvenFooter(scrambler.headerFooter(hf.getEvenFooter()));
hf.setFirstHeader(scrambler.headerFooter(hf.getFirstHeader()));
hf.setFirstFooter(scrambler.headerFooter(hf.getFirstFooter()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTHyperlink) {
CTHyperlink h = (CTHyperlink) o;
h.setDisplay(scrambler.scramble(h.getDisplay()));
h.setTooltip(null);
h.setLocation(formulas.scrub(h.getLocation())); // Sheet2!A1, or a defined name
return Action.SKIP_CHILDREN;
}
if (o instanceof CTDataValidation) {
CTDataValidation dv = (CTDataValidation) o;
dv.setFormula1(formulas.scrub(dv.getFormula1()));
dv.setFormula2(formulas.scrub(dv.getFormula2()));
dv.setPrompt(scrambler.scramble(dv.getPrompt()));
dv.setPromptTitle(scrambler.scramble(dv.getPromptTitle()));
dv.setError(scrambler.scramble(dv.getError()));
dv.setErrorTitle(scrambler.scramble(dv.getErrorTitle()));
return Action.SKIP_CHILDREN;
}
if (o instanceof org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTDataValidation) {
org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTDataValidation dv =
(org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTDataValidation) o;
if (dv.getFormula1() != null) dv.getFormula1().setF(formulas.scrub(dv.getFormula1().getF()));
if (dv.getFormula2() != null) dv.getFormula2().setF(formulas.scrub(dv.getFormula2().getF()));
dv.setPrompt(scrambler.scramble(dv.getPrompt()));
dv.setPromptTitle(scrambler.scramble(dv.getPromptTitle()));
dv.setError(scrambler.scramble(dv.getError()));
dv.setErrorTitle(scrambler.scramble(dv.getErrorTitle()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTCfRule) {
CTCfRule rule = (CTCfRule) o;
List<String> fs = rule.getFormula();
for (int i = 0; i < fs.size(); i++) fs.set(i, formulas.scrub(fs.get(i)));
rule.setText(scrambler.scramble(rule.getText()));
return Action.CONTINUE; // its extLst (x14 rules with xm:f)
}
if (o instanceof CTCustomFilter) {
CTCustomFilter f = (CTCustomFilter) o;
f.setVal(scrambler.scramble(f.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTFilter) {
CTFilter f = (CTFilter) o;
f.setVal(scrambler.scramble(f.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTInputCells) {
CTInputCells ic = (CTInputCells) o;
ic.setVal(scrambler.number(ic.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTCellSmartTagPr) {
CTCellSmartTagPr pr = (CTCellSmartTagPr) o;
pr.setKey(scrambler.scrambleLetters(pr.getKey()));
pr.setVal(scrambler.scramble(pr.getVal()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTSmartTagType) {
CTSmartTagType st = (CTSmartTagType) o;
st.setName(scrambler.scrambleLetters(st.getName()));
st.setUrl(MetadataScrubber.EXTERNAL_PLACEHOLDER);
return Action.SKIP_CHILDREN;
}
if (o instanceof org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTListItem) {
org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTListItem li =
(org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTListItem) o;
li.setVal(scrambler.scramble(li.getVal()));
return Action.SKIP_CHILDREN;
}
// ---- names
if (o instanceof Sheet) {
Sheet sheet = (Sheet) o;
String mapped = names.sheet(sheet.getName());
sheet.setName(mapped != null ? mapped : scrambler.consistent(sheet.getName()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTDefinedName) {
CTDefinedName dn = (CTDefinedName) o;
dn.setName(Names.definedName(dn.getName()));
dn.setValue(formulas.scrub(dn.getValue()));
dn.setComment(scrambler.scramble(dn.getComment()));
dn.setDescription(scrambler.scramble(dn.getDescription()));
dn.setHelp(scrambler.scramble(dn.getHelp()));
dn.setStatusBar(scrambler.scramble(dn.getStatusBar()));
dn.setCustomMenu(scrambler.scramble(dn.getCustomMenu()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTExternalDefinedName) {
CTExternalDefinedName dn = (CTExternalDefinedName) o;
dn.setName(Names.definedName(dn.getName()));
dn.setRefersTo(formulas.scrub(dn.getRefersTo()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTExternalSheetName) {
CTExternalSheetName sn = (CTExternalSheetName) o;
sn.setVal(scrambler.consistent(sn.getVal())); // as the formulas' '[1]Sheet'! map it
return Action.SKIP_CHILDREN;
}
if (o instanceof CTTable) {
CTTable t = (CTTable) o;
t.setName(scrambler.consistentIdentifier(t.getName()));
t.setDisplayName(scrambler.consistentIdentifier(t.getDisplayName())); // as structured references map it; no spaces
t.setComment(scrambler.scramble(t.getComment()));
return Action.CONTINUE;
}
if (o instanceof CTTableColumn) {
CTTableColumn col = (CTTableColumn) o;
col.setName(scrambler.consistent(col.getName())); // must equal the header cell's text
col.setTotalsRowLabel(scrambler.consistent(col.getTotalsRowLabel()));
col.setUniqueName(scrambler.consistent(col.getUniqueName()));
return Action.CONTINUE; // its formulas
}
if (o instanceof CTTableStyleInfo) {
CTTableStyleInfo info = (CTTableStyleInfo) o;
if (info.getName() != null && !BUILT_IN_TABLE_STYLE.matcher(info.getName()).matches()) {
info.setName(scrambler.consistent(info.getName()));
}
return Action.SKIP_CHILDREN;
}
if (o instanceof CTTableStyle) {
CTTableStyle ts = (CTTableStyle) o;
if (ts.getName() != null && !BUILT_IN_TABLE_STYLE.matcher(ts.getName()).matches()) {
ts.setName(scrambler.consistent(ts.getName()));
}
return Action.CONTINUE;
}
if (o instanceof CTCellStyle) {
CTCellStyle cs = (CTCellStyle) o;
if (cs.getBuiltinId() == null) cs.setName(scrambler.scrambleLetters(cs.getName()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTQueryTable) {
CTQueryTable qt = (CTQueryTable) o;
qt.setName(scrambler.consistentIdentifier(qt.getName()));
return Action.CONTINUE;
}
if (o instanceof CTQueryTableField) {
CTQueryTableField f = (CTQueryTableField) o;
f.setName(scrambler.consistent(f.getName())); // as the table column of the same name
return Action.CONTINUE;
}
if (o instanceof CTDataRef) {
CTDataRef ref = (CTDataRef) o;
if (ref.getSheet() != null) {
String mapped = names.sheet(ref.getSheet());
ref.setSheet(mapped != null ? mapped : scrambler.consistent(ref.getSheet()));
}
if (ref.getName() != null) ref.setName(Names.definedName(ref.getName()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTCustomWorkbookView) {
CTCustomWorkbookView v = (CTCustomWorkbookView) o;
v.setName(scrambler.scramble(v.getName()));
return Action.CONTINUE;
}
if (o instanceof CTFunctionGroup) {
CTFunctionGroup g = (CTFunctionGroup) o;
g.setName(scrambler.scramble(g.getName()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTWebPublishItem) {
CTWebPublishItem item = (CTWebPublishItem) o;
item.setTitle(scrambler.scramble(item.getTitle()));
item.setDestinationFile(null);
item.setDivId(scrambler.scrambleLetters(item.getDivId()));
item.setSourceObject(scrambler.scrambleLetters(item.getSourceObject()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTMap) {
CTMap map = (CTMap) o;
map.setName(scrambler.scrambleLetters(map.getName()));
map.setRootElement(scrambler.scrambleLetters(map.getRootElement()));
map.setSchemaID(scrambler.scrambleLetters(map.getSchemaID()));
return Action.CONTINUE;
}
// ---- identities and secrets
if (o instanceof CTAuthors) {
List<String> authors = ((CTAuthors) o).getAuthor();
for (int i = 0; i < authors.size(); i++) authors.set(i, names.author(authors.get(i)));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTFileSharing) {
CTFileSharing fs = (CTFileSharing) o;
fs.setUserName(names.author(fs.getUserName()));
fs.setReservationPassword(null);
fs.setHashValue(null);
fs.setSaltValue(null);
fs.setAlgorithmName(null);
fs.setSpinCount(null);
return Action.SKIP_CHILDREN;
}
if (o instanceof CTSheetProtection) {
CTSheetProtection p = (CTSheetProtection) o;
p.setPassword(null);
p.setHashValue(null);
p.setSaltValue(null);
p.setAlgorithmName(null);
p.setSpinCount(null);
return Action.SKIP_CHILDREN;
}
if (o instanceof CTWorkbookProtection) {
CTWorkbookProtection p = (CTWorkbookProtection) o;
p.setWorkbookPassword(null);
p.setRevisionsPassword(null);
p.setWorkbookHashValue(null);
p.setWorkbookSaltValue(null);
p.setWorkbookAlgorithmName(null);
p.setWorkbookSpinCount(null);
p.setRevisionsHashValue(null);
p.setRevisionsSaltValue(null);
p.setRevisionsAlgorithmName(null);
p.setRevisionsSpinCount(null);
return Action.SKIP_CHILDREN;
}
// ---- connections and links
if (o instanceof CTConnection) {
CTConnection c = (CTConnection) o;
if (isModelOrQueryConnection(c)) {
// the data model (xl/model/item.data) and the Power Query mashup (customXml) are
// removed whatever the mode; a connection to either would be a repair prompt
notes.accept("connection removed (data model or Power Query): " + c.getName());
return Action.REMOVE;
}
c.setName(scrambler.scrambleLetters(c.getName()));
c.setDescription(scrambler.scramble(c.getDescription()));
c.setSourceFile(null);
c.setOdcFile(null);
c.setSingleSignOnId(null);
if (c.getOlapPr() != null) c.getOlapPr().setLocalConnection(null);
return Action.CONTINUE;
}
if (o instanceof CTDbPr) {
CTDbPr db = (CTDbPr) o;
db.setConnection("Provider=None");
db.setCommand(scrambler.scramble(db.getCommand()));
db.setServerCommand(scrambler.scramble(db.getServerCommand()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTWebPr) {
CTWebPr web = (CTWebPr) o;
if (web.getUrl() != null) web.setUrl(MetadataScrubber.EXTERNAL_PLACEHOLDER);
web.setPost(null);
web.setEditPage(null);
return Action.CONTINUE;
}
if (o instanceof CTTextPr) {
((CTTextPr) o).setSourceFile(null);
return Action.CONTINUE;
}
if (o instanceof CTParameter) {
CTParameter p = (CTParameter) o;
p.setName(scrambler.scrambleLetters(p.getName()));
p.setPrompt(scrambler.scramble(p.getPrompt()));
p.setString(scrambler.scramble(p.getString()));
p.setCell(formulas.scrub(p.getCell()));
return Action.SKIP_CHILDREN;
}
if (o instanceof org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2010.x11.main.CTOledbPr) {
org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2010.x11.main.CTOledbPr pr =
(org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2010.x11.main.CTOledbPr) o;
pr.setConnection("Provider=None");
if (pr.getDbCommand() != null) pr.getDbCommand().setText(scrambler.scramble(pr.getDbCommand().getText()));
return Action.CONTINUE; // its dbTables
}
if (o instanceof org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2010.x11.main.CTDataFeedPr) {
((org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2010.x11.main.CTDataFeedPr) o).setConnection(null);
return Action.CONTINUE;
}
if (o instanceof org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2010.x11.main.CTDbTable) {
org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2010.x11.main.CTDbTable t =
(org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2010.x11.main.CTDbTable) o;
t.setName(scrambler.scramble(t.getName()));
return Action.SKIP_CHILDREN;
}
if (o instanceof CTDdeLink) {
CTDdeLink dde = (CTDdeLink) o;
dde.setDdeService(scrambler.scrambleLetters(dde.getDdeService()));
dde.setDdeTopic(scrambler.scrambleLetters(dde.getDdeTopic()));
return Action.CONTINUE;
}
if (o instanceof CTDdeItem) {
CTDdeItem item = (CTDdeItem) o;
item.setName(scrambler.scrambleLetters(item.getName()));
return Action.CONTINUE;
}
if (o instanceof CTOleItem) {
CTOleItem item = (CTOleItem) o;
item.setName(scrambler.scrambleLetters(item.getName()));
return Action.SKIP_CHILDREN;
}
if (o instanceof org.xlsx4j.sml.CTObjectPr) {
// an OLE object's properties (KEEP: the object stays)
org.xlsx4j.sml.CTObjectPr pr = (org.xlsx4j.sml.CTObjectPr) o;
pr.setAltText(scrambler.scramble(pr.getAltText()));
pr.setMacro(null);
return Action.CONTINUE;
}
if (o instanceof org.xlsx4j.sml.CTControlPr) {
// an ActiveX control's properties (KEEP: the control stays)
org.xlsx4j.sml.CTControlPr pr = (org.xlsx4j.sml.CTControlPr) o;
pr.setAltText(scrambler.scramble(pr.getAltText()));
pr.setMacro(null);
pr.setLinkedCell(formulas.scrub(pr.getLinkedCell()));
pr.setListFillRange(formulas.scrub(pr.getListFillRange()));
return Action.CONTINUE;
}
// ---- sparklines and form controls (x14)
if (o instanceof org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTSparklineGroup) {
org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTSparklineGroup g =
(org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTSparklineGroup) o;
g.setF(formulas.scrub(g.getF()));
return Action.CONTINUE;
}
if (o instanceof org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTSparkline) {
org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTSparkline sp =
(org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTSparkline) o;
sp.setF(formulas.scrub(sp.getF()));
return Action.SKIP_CHILDREN;
}
if (o instanceof org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTFormControlPr) {
org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTFormControlPr pr =
(org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2009.x9.main.CTFormControlPr) o;
pr.setFmlaLink(formulas.scrub(pr.getFmlaLink()));
pr.setFmlaRange(formulas.scrub(pr.getFmlaRange()));
pr.setFmlaTxbx(formulas.scrub(pr.getFmlaTxbx()));
pr.setFmlaGroup(formulas.scrub(pr.getFmlaGroup()));
return Action.CONTINUE; // its list items
}
// ---- STRICT: what goes with the parts the tool removes
if (strict) {
if (o instanceof CTPivotCaches) {
notes.accept("pivotCaches removed (the pivot tables and caches go; their cells stay as values)");
return Action.REMOVE;
}
if (o instanceof CTOleObjects) {
// the objects' preview pictures (objectPr r:id, the same image the VML shape shows)
// become the labelled placeholder
for (org.xlsx4j.sml.CTOleObject ole : ((CTOleObjects) o).getOleObject()) {
if (ole.getObjectPr() != null && ole.getObjectPr().getId() != null) {
objectPreviews.add(currentPartName + "#" + ole.getObjectPr().getId());
}
}
notes.accept("oleObjects removed (their pictures stay, as the labelled placeholder)");
return Action.REMOVE;
}
if (o instanceof CTControls) {
notes.accept("controls removed (ActiveX)");
return Action.REMOVE;
}
if (o instanceof org.xlsx4j.sml.CTExtension) {
Object any = XmlUtils.unwrap(((org.xlsx4j.sml.CTExtension) o).getAny());
if (any != null && REMOVED_EXTENSIONS.contains(any.getClass().getSimpleName())) {
notes.accept(any.getClass().getSimpleName().substring(2) + " extension removed");
return Action.REMOVE;
}
}
if (o instanceof org.docx4j.dml.spreadsheetdrawing.CTTwoCellAnchor
&& holdsSlicerOrTimeline((org.docx4j.dml.spreadsheetdrawing.CTTwoCellAnchor) o)) {
notes.accept("slicer or timeline drawing removed");
return Action.REMOVE;
}
}
return Action.CONTINUE;
}
/**
* A connection into the data model (x15:connection model="1", or type 102: a worksheet
* range fed to the model) or a Power Query connection (type 100, whose mashup lives in
* the customXml the tool removes): removed with them. Classic ODBC, OLEDB, web and text
* connections stay, scrubbed.
*/
private static boolean isModelOrQueryConnection(CTConnection c) {
if (c.getType() != null && (c.getType() == 100 || c.getType() == 102)) return true;
if (c.getExtLst() != null) {
for (org.xlsx4j.sml.CTExtension ext : c.getExtLst().getExt()) {
Object any = XmlUtils.unwrap(ext.getAny());
if (any instanceof org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2010.x11.main.CTConnection
&& Boolean.TRUE.equals(((org.xlsx4j.com.microsoft.schemas.office.spreadsheetml.x2010.x11.main.CTConnection) any).isModel())) {
return true;
}
}
}
return false;
}
/** the x14/x15 workbook and sheet extensions which point at removed parts: pivot caches, slicers, timelines, the data model */
private static final java.util.Set<String> REMOVED_EXTENSIONS = new java.util.HashSet<String>(java.util.Arrays.asList(
"CTPivotCaches", "CTSlicerCaches", "CTSlicerRefs", "CTTimelineCacheRefs", "CTTimelineRefs", "CTDataModel"));
private static boolean holdsSlicerOrTimeline(org.docx4j.dml.spreadsheetdrawing.CTTwoCellAnchor anchor) {
return holdsSlicerOrTimeline(anchor.getGraphicFrame()) || holdsSlicerOrTimeline(anchor.getAlternateContent());
}
private static boolean holdsSlicerOrTimeline(Object o) {
if (o == null) return false;
Object u = XmlUtils.unwrap(o);
if (u instanceof org.docx4j.mce.AlternateContent) {
org.docx4j.mce.AlternateContent ac = (org.docx4j.mce.AlternateContent) u;
for (org.docx4j.mce.AlternateContent.Choice c : ac.getChoice()) {
for (Object x : c.getAny()) if (holdsSlicerOrTimeline(x)) return true;
}
return false;
}
if (u instanceof org.docx4j.dml.spreadsheetdrawing.CTGraphicalObjectFrame) {
org.docx4j.dml.spreadsheetdrawing.CTGraphicalObjectFrame frame = (org.docx4j.dml.spreadsheetdrawing.CTGraphicalObjectFrame) u;
if (frame.getGraphic() != null && frame.getGraphic().getGraphicData() != null) {
String uri = frame.getGraphic().getGraphicData().getUri();
return uri != null && (uri.endsWith("/slicer") || uri.endsWith("/timeslicer"));
}
}
if (u instanceof org.w3c.dom.Element) {
// an xdr:graphicFrame the mc:Choice left as DOM: look for its graphicData
org.w3c.dom.Element el = (org.w3c.dom.Element) u;
org.w3c.dom.NodeList datas = el.getElementsByTagNameNS("http://schemas.openxmlformats.org/drawingml/2006/main", "graphicData");
for (int i = 0; i < datas.getLength(); i++) {
String uri = ((org.w3c.dom.Element) datas.item(i)).getAttribute("uri");
if (uri.endsWith("/slicer") || uri.endsWith("/timeslicer")) return true;
}
}
return false;
}
/** a cell value by type: strings scrambled, numbers randomised, booleans and errors kept, dates fixed */
private void cellValue(STCellType type, String v, Consumer<String> set) {
if (v == null) return;
if (type == null || type == STCellType.N) {
set.accept(scrambler.number(v));
} else if (type == STCellType.STR) {
set.accept(scrambler.consistent(v));
}
// S: an index into the shared strings; B and E: nothing to hide; INLINE_STR: the is child;
// a strict workbook's t="d" date cell is a serial number by the time it is loaded
// (xlsx-preprocessor.xslt, StrictCellDates)
}
/**
* A rich text string: scrambled as one string ({@link ScrambleText#consistent}),
* then dealt back to its runs by length, so a word split across runs stays one
* word and the same text always gives the same output.
*/
private void richText(CTRst rst) {
StringBuilder full = new StringBuilder();
if (rst.getT() != null && rst.getT().getValue() != null) full.append(rst.getT().getValue());
for (CTRElt r : rst.getR()) {
if (r.getT() != null && r.getT().getValue() != null) full.append(r.getT().getValue());
}
String out = scrambler.consistent(full.toString());
int at = 0;
if (rst.getT() != null && rst.getT().getValue() != null) {
at = deal(rst.getT(), out, at);
}
for (CTRElt r : rst.getR()) {
if (r.getT() != null && r.getT().getValue() != null) at = deal(r.getT(), out, at);
}
for (CTPhoneticRun ph : rst.getRPh()) {
if (ph.getT() != null) ph.getT().setValue(scrambler.scramble(ph.getT().getValue()));
}
}
private int deal(CTXstringWhitespace t, String out, int at) {
int len = t.getValue().length();
int end = Math.min(at + len, out.length());
String piece = out.substring(Math.min(at, out.length()), end);
if (piece.length() < len) piece = piece + scrambler.scramble(t.getValue().substring(piece.length()));
t.setValue(piece);
return at + len;
}
}
@@ -0,0 +1,437 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.docx4j.anon;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.Base;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.parts.JaxbXmlPart;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart;
import org.docx4j.openpackaging.parts.XmlPart;
import org.docx4j.openpackaging.parts.relationships.RelationshipsPart;
import org.docx4j.relationships.Relationship;
import org.docx4j.wml.Style;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Proves the guarantee on one document: no token of the original survives in
* the anonymised output.
* <p>
* A token is a run of three or more letters (any script), lower-cased. The
* extraction takes, from every XML part, every text node, the values of the
* attributes known to carry names, descriptions, instructions and identities
* (see {@link #ATTRIBUTES}), and every external relationship target. A token of
* the output which is also a token of the original is a leak unless it is in
* the vocabulary the anonymiser itself writes:
* <ul>
* <li>a substring of a lorem ipsum word (the Latin scramble maps letters
* positionally onto lorem text, so an output word is always a fragment of one
* lorem word) - the blind spot is an original word which is itself such a
* fragment ({@code sit}, {@code amet}, {@code class}); such a word is in the
* lorem vocabulary and carries nothing;</li>
* <li>a field keyword or format-switch word ({@link FieldInstructions#KEYWORDS});</li>
* <li>a date or number picture ({@code yyyy}, {@code MMMM});</li>
* <li>a word of a built-in style name (KnownStyles.xml and the document's own
* latent-style list), which Word identifies built-in styles by;</li>
* <li>the fixed words the tool writes: Author, Sheet, example, invalid,
* http, None, General, true, false, app.xml's "Microsoft Office Word" (or
* PowerPoint), the altChunk marker's "altChunk removed by docx4j anon", the
* "Object n" name of the picture a removed OLE frame becomes, and the colour
* names a number format code can carry ({@code [Red]}).</li>
* </ul>
* Digits are not tokens: they are randomised, and a 4-digit run would collide
* by chance often enough to make the check useless. GUIDs (table style ids,
* creation ids) are skipped: their hex runs are not words. In a formula (a
* cell's f, a defined name, a chart's c:f, ...) only the string literals and the
* names are tokens ({@link #formulaTokens}): function names, references and
* error literals are the language; a header or footer's &amp; codes likewise.
*
* @since 17.2.0
*/
public class Verify {
private static final Logger log = LoggerFactory.getLogger(Verify.class);
/** A token of the original found in the output. */
public static class Leak {
public final String partName;
public final String where;
public final String token;
Leak(String partName, String where, String token) {
this.partName = partName;
this.where = where;
this.token = token;
}
@Override
public String toString() {
return partName + " " + where + ": \"" + token + "\"";
}
}
/** (element local name, attribute local name) pairs whose values are extracted. "*" matches any element. */
public static final Set<String> ATTRIBUTES = new HashSet<String>(Arrays.asList(
"*/author", "*/initials", "*/contact", "*/userId",
"alias/val", "tag/val",
"hyperlink/tooltip", "hyperlink/docLocation", "hlinkClick/tooltip", "hlinkHover/tooltip",
"docVar/name", "docVar/val",
"fldSimple/instr",
"docPr/name", "docPr/descr", "docPr/title",
"cNvPr/name", "cNvPr/descr", "cNvPr/title",
"imagedata/title", "shape/alt", "shape/title", "shape/href", "textpath/string",
"listItem/displayText", "listItem/value",
"name/val", "aliases/val", "docPart/val",
"attr/val", "attr/name",
"lvlText/val",
"prSet/phldrT",
"bookmarkStart/name", "moveFromRangeStart/name", "moveToRangeStart/name",
"default/val", "listEntry/val", "helpText/val", "statusText/val",
"placeholder/val",
"connectString/val", "query/val", "mailSubject/val", "addressFieldName/val",
"theme/name", "clrScheme/name", "fontScheme/name", "fmtScheme/name",
"pivotSource/name", "strDim/name", "numDim/name", "lvl/name",
// PresentationML (CR-019 phase 2): comment authors (legacy and 2018), tags, section and
// custom-show names, layout names, sound file names, object names, table style names
"cmAuthor/name", "author/name", "tag/name", "section/name", "custShow/name", "cSld/name",
"snd/name", "oleObj/name", "control/name", "tblStyle/styleName",
"hlinkClick/invalidUrl", "hlinkHover/invalidUrl",
// SpreadsheetML (CR-019 phase 3): defined names, tables and columns, sheet names, hyperlink
// text, validation messages, connections and query tables, filters, links, persons
"definedName/name", "definedName/comment", "definedName/description", "definedName/help",
"definedName/statusBar", "definedName/customMenu", "externalDefinedName/name",
"table/name", "table/displayName", "table/comment",
"tableColumn/name", "tableColumn/totalsRowLabel", "tableColumn/uniqueName",
"tableStyleInfo/name", "tableStyle/name", "cellStyle/name",
"sheet/name", "sheetName/val", "dataRef/sheet", "dataRef/name",
"hyperlink/display",
"dataValidation/prompt", "dataValidation/promptTitle", "dataValidation/error", "dataValidation/errorTitle",
"cfRule/text", "customFilter/val", "filter/val", "listItem/val",
"connection/name", "connection/description", "connection/sourceFile", "connection/odcFile",
"dbPr/connection", "dbPr/command", "dbPr/serverCommand", "webPr/url", "webPr/post", "textPr/sourceFile",
"oledbPr/connection", "dataFeedPr/connection", "dbTable/name", "olapPr/localConnection",
"parameter/name", "parameter/prompt", "parameter/string",
"queryTable/name", "queryTableField/name",
"fileSharing/userName", "ddeLink/ddeService", "ddeLink/ddeTopic", "ddeItem/name", "oleItem/name",
"person/displayName", "cellSmartTagPr/key", "cellSmartTagPr/val", "smartTagType/name", "smartTagType/url",
"webPublishItem/title", "webPublishItem/destinationFile", "customWorkbookView/name", "functionGroup/name",
"map/name", "map/rootElement", "map/schemaID",
"Relationship/Target"));
/** attributes whose value is a formula: only its literals and names are tokens */
static final Set<String> FORMULA_ATTRIBUTES = new HashSet<String>(Arrays.asList(
"externalDefinedName/refersTo", "hyperlink/location", "parameter/cell",
"formControlPr/fmlaLink", "formControlPr/fmlaRange", "formControlPr/fmlaTxbx", "formControlPr/fmlaGroup"));
/** elements whose text is a formula */
static final Set<String> FORMULA_ELEMENTS = new HashSet<String>(Arrays.asList(
"f", "formula", "formula1", "formula2", "definedName", "calculatedColumnFormula", "totalsRowFormula",
"FmlaLink", "FmlaRange", "FmlaTxbx", "FmlaGroup", "FmlaMacro"));
/** elements whose text is a spreadsheet header or footer, with &amp; codes */
static final Set<String> HEADER_FOOTER_ELEMENTS = new HashSet<String>(Arrays.asList(
"oddHeader", "oddFooter", "evenHeader", "evenFooter", "firstHeader", "firstFooter"));
private static final Pattern PICTURE = Pattern.compile("^(d+|m+|y+|h+|s+)$");
private static final Set<String> FIXED_WORDS = new HashSet<String>(Arrays.asList(
"author", "sheet", "example", "invalid", "http", "none", "general", "true", "false",
"microsoft", "office", "word", "powerpoint", "excel", "macintosh", // app.xml Application
"provider", // the connection string a data connection becomes (Provider=None)
// the altChunk marker paragraph (Placeholders.ALTCHUNK_REMOVED)
"altchunk", "removed", "docx", "anon",
// the picture a removed OLE graphic frame becomes in a pptx ("Object n")
"object",
// the colour names of a number format code ([Red]-#,##0), chart and cell formats
"black", "blue", "cyan", "green", "magenta", "red", "white", "yellow"));
/** a GUID, braced or not: structure (table style ids, creation ids), never text */
private static final Pattern GUID = Pattern.compile(
"\\{?[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\}?");
/** The tokens of one package: per part, token to the first place it was seen. */
public static class Extraction {
public final Map<String, Map<String, String>> byPart = new LinkedHashMap<String, Map<String, String>>();
/** words of the document's own latent-style names: built-in, allowed */
public final Set<String> styleWords = new HashSet<String>();
public Set<String> allTokens() {
Set<String> all = new HashSet<String>();
for (Map<String, String> m : byPart.values()) all.addAll(m.keySet());
return all;
}
void add(String partName, String token, String where) {
Map<String, String> m = byPart.get(partName);
if (m == null) {
m = new HashMap<String, String>();
byPart.put(partName, m);
}
String existing = m.get(token);
// prefer a place where a built-in style word is not allowed, so the check is not
// disarmed by the same word turning up in a style name first
if (existing == null || (STYLE_NAME_PLACES.contains(existing) && !STYLE_NAME_PLACES.contains(where))) {
m.put(token, where);
}
}
}
/**
* The check: extract both, compare.
*/
public static List<Leak> noOriginalText(OpcPackage original, OpcPackage anonymised) {
return compare(extract(original), extract(anonymised));
}
/**
* The tokens of the anonymised package which the original also had, less the
* anonymiser's own vocabulary.
*/
public static List<Leak> compare(Extraction original, Extraction anonymised) {
Set<String> originalTokens = original.allTokens();
Set<String> allowedStyleWords = new HashSet<String>(anonymised.styleWords);
allowedStyleWords.addAll(knownStyleWords());
List<Leak> leaks = new ArrayList<Leak>();
for (Map.Entry<String, Map<String, String>> part : anonymised.byPart.entrySet()) {
for (Map.Entry<String, String> e : part.getValue().entrySet()) {
String token = e.getKey();
if (!originalTokens.contains(token)) continue;
if (isAllowed(token, e.getValue(), allowedStyleWords)) continue;
leaks.add(new Leak(part.getKey(), e.getValue(), token));
}
}
return leaks;
}
/** the places a built-in style name legitimately appears */
private static final Set<String> STYLE_NAME_PLACES = new HashSet<String>(Arrays.asList(
"name/@val", "aliases/@val", "instrText/text()", "delInstrText/text()", "fldSimple/@instr"));
static boolean isAllowed(String token, String where, Set<String> styleWords) {
if (FIXED_WORDS.contains(token)) return true;
if (FieldInstructions.KEYWORDS.contains(token.toUpperCase(Locale.ROOT))) return true;
if (PICTURE.matcher(token).matches()) return true;
if (STYLE_NAME_PLACES.contains(where) && styleWords.contains(token)) return true;
return isLoremFragment(token);
}
/** true if the token is a substring of a word of {@link Lorem#WORDS} */
static boolean isLoremFragment(String token) {
return Lorem.isFragment(token);
}
private static Set<String> knownStyleWords;
static synchronized Set<String> knownStyleWords() {
if (knownStyleWords == null) {
Set<String> words = new HashSet<String>();
for (Style s : StyleDefinitionsPart.getKnownStyles().values()) {
if (s.getName() != null) words.addAll(tokens(s.getName().getVal()));
}
knownStyleWords = words;
}
return knownStyleWords;
}
/** Every XML part's text nodes and named attributes, and every external target. */
public static Extraction extract(OpcPackage pkg) {
Extraction x = new Extraction();
externalTargets(pkg, x);
for (Part p : new ArrayList<Part>(pkg.getParts().getParts().values())) {
externalTargets(p, x);
Document doc = null;
try {
if (p instanceof JaxbXmlPart) {
JaxbXmlPart<?> jp = (JaxbXmlPart<?>) p;
Object contents = jp.getContents();
if (contents == null) continue;
doc = XmlUtils.marshaltoW3CDomDocument(contents, jp.getJAXBContext());
} else if (p instanceof XmlPart) {
doc = ((XmlPart) p).getDocument();
}
} catch (Exception e) {
log.warn("cannot extract " + p.getPartName().getName() + ": " + e);
x.add(p.getPartName().getName(), "unreadable", "part");
}
if (doc == null) continue;
extract(p.getPartName().getName(), doc.getDocumentElement(), x);
}
return x;
}
private static void externalTargets(Base base, Extraction x) {
RelationshipsPart rp = base.getRelationshipsPart();
if (rp == null || rp.getRelationships() == null) return;
String partName = rp.getPartName() == null ? "_rels/.rels" : rp.getPartName().getName();
for (Relationship r : rp.getRelationships().getRelationship()) {
if ("External".equals(r.getTargetMode())) {
for (String t : tokens(r.getTarget())) {
x.add(partName, t, "Relationship/@Target");
}
}
}
}
private static void extract(String partName, Node n, Extraction x) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
String eln = local(el);
NamedNodeMap attrs = el.getAttributes();
for (int i = 0; attrs != null && i < attrs.getLength(); i++) {
Attr a = (Attr) attrs.item(i);
String an = local(a);
if (eln.equals("lsdException") && an.equals("name")) {
x.styleWords.addAll(tokens(a.getValue()));
continue;
}
if (an.equals("name") && a.getValue() != null && BUILT_IN_TABLE_STYLE.matcher(a.getValue()).matches()) {
continue; // TableStyleMedium2: Excel's, kept
}
if (eln.equals("cellStyle") && el.hasAttribute("builtinId")) {
continue; // Normal, Currency, Percent: Excel's, kept
}
if (eln.equals("name") && an.equals("val") && n.getParentNode() != null && local(n.getParentNode()).equals("font")) {
continue; // a font's name in a workbook's styles: structure, like w:rFonts
}
if (FORMULA_ATTRIBUTES.contains(eln + "/" + an)) {
for (String t : formulaTokens(a.getValue())) {
x.add(partName, t, eln + "/@" + an);
}
} else if (ATTRIBUTES.contains(eln + "/" + an) || ATTRIBUTES.contains("*/" + an)) {
if (a.getValue() != null && a.getValue().startsWith("_xlnm.")) continue; // a built-in defined name
for (String t : tokens(a.getValue())) {
x.add(partName, t, eln + "/@" + an);
}
}
}
// a cell (or an external link's cell) holding an error or a boolean: nothing to hide
if ((eln.equals("c") || eln.equals("cell")) && ("e".equals(el.getAttribute("t")) || "b".equals(el.getAttribute("t")))) {
return;
}
// a VML control's or comment's x:ClientData: its values (Center, Note, Checkbox) are the
// schema's words; only its formulas can carry the document's
if ("urn:schemas-microsoft-com:office:excel".equals(el.getNamespaceURI()) && !eln.startsWith("Fmla")
&& !eln.equals("ClientData")) {
return;
}
}
NodeList children = n.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node c = children.item(i);
if (c.getNodeType() == Node.TEXT_NODE || c.getNodeType() == Node.CDATA_SECTION_NODE) {
String eln = local(n);
String where = eln + "/text()";
List<String> found = FORMULA_ELEMENTS.contains(eln) ? formulaTokens(c.getNodeValue())
: HEADER_FOOTER_ELEMENTS.contains(eln) ? headerFooterTokens(c.getNodeValue())
: tokens(c.getNodeValue());
for (String t : found) {
x.add(partName, t, where);
}
} else if (c.getNodeType() == Node.ELEMENT_NODE) {
extract(partName, c, x);
}
}
}
private static final Pattern BUILT_IN_TABLE_STYLE = Pattern.compile("^(TableStyle|PivotStyle)(Light|Medium|Dark)[0-9]+$");
private static final Pattern STRING_LITERAL = Pattern.compile("\"((?:[^\"]|\"\")*)\"");
private static final Pattern HF_CODE = Pattern.compile("&(\"[^\"]*\"|K[0-9A-Fa-f]{6}|[0-9]+|&|[A-Za-z])");
/**
* The tokens of a formula which could carry the document's words: its string
* literals, and its names (sheets, defined names, tables and columns). Function
* names, cell and range references, error literals and the structured-reference
* keywords are the formula language, not the document.
*/
public static List<String> formulaTokens(String f) {
List<String> result = new ArrayList<String>();
if (f == null) return result;
java.util.regex.Matcher m = STRING_LITERAL.matcher(f);
StringBuffer rest = new StringBuffer();
while (m.find()) {
result.addAll(tokens(m.group(1)));
m.appendReplacement(rest, " ");
}
m.appendTail(rest);
String r = rest.toString()
.replaceAll("\\[#[^\\]]*\\]", " ") // [#This Row], [#Headers]
.replaceAll("#[A-Za-z0-9/_!?]+", " ") // #N/A, #DIV/0!, #REF!
.replaceAll("\\b[A-Za-z_][A-Za-z0-9_.]*\\s*\\(", " ") // a function call
.replaceAll("\\$?[A-Za-z]{1,3}\\$?[0-9]+", " ") // a cell reference
.replaceAll("\\$?[A-Za-z]{1,3}:\\$?[A-Za-z]{1,3}", " ") // a column range
.replaceAll("\\b[Rr](\\[-?[0-9]+\\]|[0-9]+)?[Cc](\\[-?[0-9]+\\]|[0-9]+)?\\b", " "); // R1C1
result.addAll(tokens(r));
return result;
}
/** the tokens of a header or footer: its text, not its &amp;"Arial,Bold" and &amp;K colour codes */
static List<String> headerFooterTokens(String text) {
if (text == null) return new ArrayList<String>();
return tokens(HF_CODE.matcher(text).replaceAll(" "));
}
private static String local(Node n) {
return n.getLocalName() == null ? n.getNodeName() : n.getLocalName();
}
/** Runs of three or more letters, lower-cased; GUIDs are skipped (their hex runs are not words). */
public static List<String> tokens(String s) {
List<String> result = new ArrayList<String>();
if (s == null) return result;
if (s.indexOf('-') >= 0) s = GUID.matcher(s).replaceAll(" ");
int i = 0, n = s.length();
while (i < n) {
int cp = s.codePointAt(i);
if (Character.isLetter(cp)) {
int start = i;
int letters = 0;
while (i < n && Character.isLetter(cp = s.codePointAt(i))) {
i += Character.charCount(cp);
letters++;
}
if (letters >= 3) result.add(s.substring(start, i).toLowerCase(Locale.ROOT));
} else {
i += Character.charCount(cp);
}
}
return result;
}
}
@@ -0,0 +1,179 @@
package org.docx4j.bibliography;
import java.util.List;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlElementRefs;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import org.docx4j.copy.CopyUtils;
import org.docx4j.copy.Copyable;
import org.docx4j.list.ArrayListDocx4j;
import org.jvnet.jaxb.lang.Child;
/**
* &lt;p&gt;Java class for CT_AuthorType complex type&lt;/p&gt;.
*
* &lt;p&gt;The following schema fragment specifies the expected content contained within this class.&lt;/p&gt;
*
* &lt;pre&gt;{&#064;code
* &lt;complexType name="CT_AuthorType"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;choice maxOccurs="unbounded" minOccurs="0"&gt;
* &lt;element name="Artist" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Author" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameOrCorporateType"/&gt;
* &lt;element name="BookAuthor" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Compiler" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Composer" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Conductor" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Counsel" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Director" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Editor" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Interviewee" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Interviewer" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Inventor" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Performer" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameOrCorporateType"/&gt;
* &lt;element name="ProducerName" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Translator" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;element name="Writer" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameType"/&gt;
* &lt;/choice&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* }&lt;/pre&gt;
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CT_AuthorType", propOrder = {
"artistOrAuthorOrBookAuthor"
})
public class CTAuthorType implements Copyable, Child
{
@XmlElementRefs({
@XmlElementRef(name = "Artist", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Author", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "BookAuthor", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Compiler", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Composer", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Conductor", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Counsel", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Director", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Editor", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Interviewee", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Interviewer", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Inventor", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Performer", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ProducerName", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Translator", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Writer", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false)
})
protected List<JAXBElement<?>> artistOrAuthorOrBookAuthor = new ArrayListDocx4j<>(this);
@XmlTransient
private Object parent;
/**
* Gets the value of the artistOrAuthorOrBookAuthor property.
*
* <p>This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the Jakarta XML Binding object.
* This is why there is not a {@code set} method for the artistOrAuthorOrBookAuthor property.</p>
*
* <p>
* For example, to add a new item, do as follows:
* </p>
* <pre>
* getArtistOrAuthorOrBookAuthor().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link CTNameOrCorporateType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameOrCorporateType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* {@link JAXBElement }{@code <}{@link CTNameType }{@code >}
* </p>
*
*
* @return
* The value of the artistOrAuthorOrBookAuthor property.
*/
public List<JAXBElement<?>> getArtistOrAuthorOrBookAuthor() {
if (artistOrAuthorOrBookAuthor == null) {
artistOrAuthorOrBookAuthor = new ArrayListDocx4j<>(this);
}
return this.artistOrAuthorOrBookAuthor;
}
/**
* Gets the parent object in the object tree representing the unmarshalled xml document.
*
* @return
* The parent object.
*/
public Object getParent() {
return this.parent;
}
public void setParent(Object parent) {
this.parent = parent;
}
/**
* This method is invoked by the JAXB implementation on each instance when unmarshalling completes.
*
* @param parent
* The parent object in the object tree.
* @param unmarshaller
* The unmarshaller that generated the instance.
*/
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
setParent(parent);
}
@Override
public Object copyTo(Object target) {
if (target == null) {
target = new CTAuthorType();
}
CTAuthorType typedTarget = ((CTAuthorType) target);
if (this.artistOrAuthorOrBookAuthor!= null) {
for (JAXBElement item: this.artistOrAuthorOrBookAuthor) {
JAXBElement copiedItem;
copiedItem = ((JAXBElement) CopyUtils.copyObjectAndSetParent(item, typedTarget));
typedTarget.getArtistOrAuthorOrBookAuthor().add(copiedItem);
}
}
return typedTarget;
}
@Override
public Object copy() {
CTAuthorType copy = new CTAuthorType();
return copyTo(copy);
}
}
@@ -0,0 +1,134 @@
package org.docx4j.bibliography;
import java.util.List;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import org.docx4j.copy.Copyable;
import org.docx4j.list.ArrayListDocx4j;
import org.jvnet.jaxb.lang.Child;
/**
* &lt;p&gt;Java class for CT_NameListType complex type&lt;/p&gt;.
*
* &lt;p&gt;The following schema fragment specifies the expected content contained within this class.&lt;/p&gt;
*
* &lt;pre&gt;{&#064;code
* &lt;complexType name="CT_NameListType"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="Person" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_PersonType" maxOccurs="unbounded"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* }&lt;/pre&gt;
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CT_NameListType", propOrder = {
"person"
})
public class CTNameListType implements Copyable, Child
{
/**
* Person
*
*/
@XmlElement(name = "Person", required = true)
protected List<CTPersonType> person = new ArrayListDocx4j<>(this);
@XmlTransient
private Object parent;
/**
* Person
*
* Gets the value of the person property.
*
* <p>This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the Jakarta XML Binding object.
* This is why there is not a {@code set} method for the person property.</p>
*
* <p>
* For example, to add a new item, do as follows:
* </p>
* <pre>
* getPerson().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CTPersonType }
* </p>
*
*
* @return
* The value of the person property.
*/
public List<CTPersonType> getPerson() {
if (person == null) {
person = new ArrayListDocx4j<>(this);
}
return this.person;
}
/**
* Gets the parent object in the object tree representing the unmarshalled xml document.
*
* @return
* The parent object.
*/
public Object getParent() {
return this.parent;
}
public void setParent(Object parent) {
this.parent = parent;
}
/**
* This method is invoked by the JAXB implementation on each instance when unmarshalling completes.
*
* @param parent
* The parent object in the object tree.
* @param unmarshaller
* The unmarshaller that generated the instance.
*/
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
setParent(parent);
}
@Override
public Object copyTo(Object target) {
if (target == null) {
target = new CTNameListType();
}
CTNameListType typedTarget = ((CTNameListType) target);
if (this.person!= null) {
for (CTPersonType item: this.person) {
CTPersonType copiedItem;
copiedItem = ((CTPersonType) item.copy());
copiedItem.setParent(typedTarget);
typedTarget.getPerson().add(copiedItem);
}
}
return typedTarget;
}
@Override
public Object copy() {
CTNameListType copy = new CTNameListType();
return copyTo(copy);
}
}
@@ -0,0 +1,158 @@
package org.docx4j.bibliography;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import org.docx4j.copy.Copyable;
import org.jvnet.jaxb.lang.Child;
/**
* &lt;p&gt;Java class for CT_NameOrCorporateType complex type&lt;/p&gt;.
*
* &lt;p&gt;The following schema fragment specifies the expected content contained within this class.&lt;/p&gt;
*
* &lt;pre&gt;{&#064;code
* &lt;complexType name="CT_NameOrCorporateType"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;choice minOccurs="0"&gt;
* &lt;element name="NameList" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameListType"/&gt;
* &lt;element name="Corporate" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;/choice&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* }&lt;/pre&gt;
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CT_NameOrCorporateType", propOrder = {
"nameList",
"corporate"
})
public class CTNameOrCorporateType implements Copyable, Child
{
@XmlElement(name = "NameList")
protected CTNameListType nameList;
/**
* Corporate Author
*
*/
@XmlElement(name = "Corporate")
protected String corporate;
@XmlTransient
private Object parent;
/**
* Gets the value of the nameList property.
*
* @return
* possible object is
* {@link CTNameListType }
*
*/
public CTNameListType getNameList() {
return nameList;
}
/**
* Sets the value of the nameList property.
*
* @param value
* allowed object is
* {@link CTNameListType }
*
*/
public void setNameList(CTNameListType value) {
this.nameList = value;
}
/**
* Corporate Author
*
* @return
* possible object is
* {@link String }
*
*/
public String getCorporate() {
return corporate;
}
/**
* Sets the value of the corporate property.
*
* @param value
* allowed object is
* {@link String }
*
* @see #getCorporate()
*/
public void setCorporate(String value) {
this.corporate = value;
}
/**
* Gets the parent object in the object tree representing the unmarshalled xml document.
*
* @return
* The parent object.
*/
public Object getParent() {
return this.parent;
}
public void setParent(Object parent) {
this.parent = parent;
}
/**
* This method is invoked by the JAXB implementation on each instance when unmarshalling completes.
*
* @param parent
* The parent object in the object tree.
* @param unmarshaller
* The unmarshaller that generated the instance.
*/
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
setParent(parent);
}
@Override
public Object copyTo(Object target) {
if (target == null) {
target = new CTNameOrCorporateType();
}
CTNameOrCorporateType typedTarget = ((CTNameOrCorporateType) target);
if (this.nameList!= null) {
CTNameListType objToCopy = this.nameList;
CTNameListType copiedObj;
copiedObj = ((CTNameListType) objToCopy.copy());
copiedObj.setParent(typedTarget);
typedTarget.nameList = copiedObj;
}
if (this.corporate!= null) {
String objToCopy = this.corporate;
String copiedObj;
copiedObj = objToCopy;
typedTarget.corporate = copiedObj;
}
return typedTarget;
}
@Override
public Object copy() {
CTNameOrCorporateType copy = new CTNameOrCorporateType();
return copyTo(copy);
}
}
@@ -0,0 +1,122 @@
package org.docx4j.bibliography;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import org.docx4j.copy.Copyable;
import org.jvnet.jaxb.lang.Child;
/**
* &lt;p&gt;Java class for CT_NameType complex type&lt;/p&gt;.
*
* &lt;p&gt;The following schema fragment specifies the expected content contained within this class.&lt;/p&gt;
*
* &lt;pre&gt;{&#064;code
* &lt;complexType name="CT_NameType"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="NameList" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_NameListType"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* }&lt;/pre&gt;
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CT_NameType", propOrder = {
"nameList"
})
public class CTNameType implements Copyable, Child
{
/**
* Name List
*
*/
@XmlElement(name = "NameList", required = true)
protected CTNameListType nameList;
@XmlTransient
private Object parent;
/**
* Name List
*
* @return
* possible object is
* {@link CTNameListType }
*
*/
public CTNameListType getNameList() {
return nameList;
}
/**
* Sets the value of the nameList property.
*
* @param value
* allowed object is
* {@link CTNameListType }
*
* @see #getNameList()
*/
public void setNameList(CTNameListType value) {
this.nameList = value;
}
/**
* Gets the parent object in the object tree representing the unmarshalled xml document.
*
* @return
* The parent object.
*/
public Object getParent() {
return this.parent;
}
public void setParent(Object parent) {
this.parent = parent;
}
/**
* This method is invoked by the JAXB implementation on each instance when unmarshalling completes.
*
* @param parent
* The parent object in the object tree.
* @param unmarshaller
* The unmarshaller that generated the instance.
*/
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
setParent(parent);
}
@Override
public Object copyTo(Object target) {
if (target == null) {
target = new CTNameType();
}
CTNameType typedTarget = ((CTNameType) target);
if (this.nameList!= null) {
CTNameListType objToCopy = this.nameList;
CTNameListType copiedObj;
copiedObj = ((CTNameListType) objToCopy.copy());
copiedObj.setParent(typedTarget);
typedTarget.nameList = copiedObj;
}
return typedTarget;
}
@Override
public Object copy() {
CTNameType copy = new CTNameType();
return copyTo(copy);
}
}
@@ -0,0 +1,231 @@
package org.docx4j.bibliography;
import java.util.List;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import org.docx4j.copy.Copyable;
import org.docx4j.list.ArrayListDocx4j;
import org.jvnet.jaxb.lang.Child;
/**
* &lt;p&gt;Java class for CT_PersonType complex type&lt;/p&gt;.
*
* &lt;p&gt;The following schema fragment specifies the expected content contained within this class.&lt;/p&gt;
*
* &lt;pre&gt;{&#064;code
* &lt;complexType name="CT_PersonType"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="Last" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String" maxOccurs="unbounded" minOccurs="0"/&gt;
* &lt;element name="First" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String" maxOccurs="unbounded" minOccurs="0"/&gt;
* &lt;element name="Middle" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String" maxOccurs="unbounded" minOccurs="0"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* }&lt;/pre&gt;
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CT_PersonType", propOrder = {
"last",
"first",
"middle"
})
public class CTPersonType implements Copyable, Child
{
/**
* Person's Last, or Family, Name
*
*/
@XmlElement(name = "Last")
protected List<String> last = new ArrayListDocx4j<>(this);
/**
* Person's First, or Given, Name
*
*/
@XmlElement(name = "First")
protected List<String> first = new ArrayListDocx4j<>(this);
/**
* Person's Middle, or Other, Name
*
*/
@XmlElement(name = "Middle")
protected List<String> middle = new ArrayListDocx4j<>(this);
@XmlTransient
private Object parent;
/**
* Person's Last, or Family, Name
*
* Gets the value of the last property.
*
* <p>This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the Jakarta XML Binding object.
* This is why there is not a {@code set} method for the last property.</p>
*
* <p>
* For example, to add a new item, do as follows:
* </p>
* <pre>
* getLast().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
* </p>
*
*
* @return
* The value of the last property.
*/
public List<String> getLast() {
if (last == null) {
last = new ArrayListDocx4j<>(this);
}
return this.last;
}
/**
* Person's First, or Given, Name
*
* Gets the value of the first property.
*
* <p>This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the Jakarta XML Binding object.
* This is why there is not a {@code set} method for the first property.</p>
*
* <p>
* For example, to add a new item, do as follows:
* </p>
* <pre>
* getFirst().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
* </p>
*
*
* @return
* The value of the first property.
*/
public List<String> getFirst() {
if (first == null) {
first = new ArrayListDocx4j<>(this);
}
return this.first;
}
/**
* Person's Middle, or Other, Name
*
* Gets the value of the middle property.
*
* <p>This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the Jakarta XML Binding object.
* This is why there is not a {@code set} method for the middle property.</p>
*
* <p>
* For example, to add a new item, do as follows:
* </p>
* <pre>
* getMiddle().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
* </p>
*
*
* @return
* The value of the middle property.
*/
public List<String> getMiddle() {
if (middle == null) {
middle = new ArrayListDocx4j<>(this);
}
return this.middle;
}
/**
* Gets the parent object in the object tree representing the unmarshalled xml document.
*
* @return
* The parent object.
*/
public Object getParent() {
return this.parent;
}
public void setParent(Object parent) {
this.parent = parent;
}
/**
* This method is invoked by the JAXB implementation on each instance when unmarshalling completes.
*
* @param parent
* The parent object in the object tree.
* @param unmarshaller
* The unmarshaller that generated the instance.
*/
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
setParent(parent);
}
@Override
public Object copyTo(Object target) {
if (target == null) {
target = new CTPersonType();
}
CTPersonType typedTarget = ((CTPersonType) target);
if (this.last!= null) {
for (String item: this.last) {
String copiedItem;
copiedItem = item;
typedTarget.getLast().add(copiedItem);
}
}
if (this.first!= null) {
for (String item: this.first) {
String copiedItem;
copiedItem = item;
typedTarget.getFirst().add(copiedItem);
}
}
if (this.middle!= null) {
for (String item: this.middle) {
String copiedItem;
copiedItem = item;
typedTarget.getMiddle().add(copiedItem);
}
}
return typedTarget;
}
@Override
public Object copy() {
CTPersonType copy = new CTPersonType();
return copyTo(copy);
}
}
@@ -0,0 +1,287 @@
package org.docx4j.bibliography;
import java.util.List;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlElementRefs;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import org.docx4j.copy.CopyUtils;
import org.docx4j.copy.Copyable;
import org.docx4j.list.ArrayListDocx4j;
import org.jvnet.jaxb.lang.Child;
/**
* &lt;p&gt;Java class for CT_SourceType complex type&lt;/p&gt;.
*
* &lt;p&gt;The following schema fragment specifies the expected content contained within this class.&lt;/p&gt;
*
* &lt;pre&gt;{&#064;code
* &lt;complexType name="CT_SourceType"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;choice maxOccurs="unbounded" minOccurs="0"&gt;
* &lt;element name="AbbreviatedCaseNumber" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="AlbumTitle" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Author" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_AuthorType"/&gt;
* &lt;element name="BookTitle" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Broadcaster" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="BroadcastTitle" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="CaseNumber" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="ChapterNumber" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="City" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Comments" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="ConferenceName" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="CountryRegion" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Court" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Day" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="DayAccessed" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Department" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Distributor" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Edition" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Guid" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Institution" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="InternetSiteTitle" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Issue" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="JournalName" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="LCID" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_Lang"/&gt;
* &lt;element name="Medium" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Month" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="MonthAccessed" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="NumberVolumes" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Pages" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="PatentNumber" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="PeriodicalTitle" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="ProductionCompany" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="PublicationTitle" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Publisher" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="RecordingNumber" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="RefOrder" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Reporter" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="SourceType" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}ST_SourceType"/&gt;
* &lt;element name="ShortTitle" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="StandardNumber" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="StateProvince" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Station" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Tag" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Theater" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="ThesisType" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Title" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Type" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="URL" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Version" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Volume" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="Year" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;element name="YearAccessed" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"/&gt;
* &lt;/choice&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* }&lt;/pre&gt;
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CT_SourceType", propOrder = {
"abbreviatedCaseNumberOrAlbumTitleOrAuthor"
})
public class CTSourceType implements Copyable, Child
{
@XmlElementRefs({
@XmlElementRef(name = "AbbreviatedCaseNumber", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "AlbumTitle", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Author", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "BookTitle", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Broadcaster", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "BroadcastTitle", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "CaseNumber", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ChapterNumber", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "City", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Comments", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ConferenceName", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "CountryRegion", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Court", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Day", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "DayAccessed", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Department", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Distributor", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Edition", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Guid", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Institution", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "InternetSiteTitle", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Issue", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "JournalName", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "LCID", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Medium", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Month", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "MonthAccessed", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "NumberVolumes", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Pages", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "PatentNumber", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "PeriodicalTitle", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ProductionCompany", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "PublicationTitle", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Publisher", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "RecordingNumber", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "RefOrder", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Reporter", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "SourceType", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ShortTitle", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "StandardNumber", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "StateProvince", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Station", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Tag", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Theater", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ThesisType", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Title", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Type", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "URL", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Version", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Volume", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Year", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false),
@XmlElementRef(name = "YearAccessed", namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", type = JAXBElement.class, required = false)
})
protected List<JAXBElement<?>> abbreviatedCaseNumberOrAlbumTitleOrAuthor = new ArrayListDocx4j<>(this);
@XmlTransient
private Object parent;
/**
* Gets the value of the abbreviatedCaseNumberOrAlbumTitleOrAuthor property.
*
* <p>This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the Jakarta XML Binding object.
* This is why there is not a {@code set} method for the abbreviatedCaseNumberOrAlbumTitleOrAuthor property.</p>
*
* <p>
* For example, to add a new item, do as follows:
* </p>
* <pre>
* getAbbreviatedCaseNumberOrAlbumTitleOrAuthor().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link CTAuthorType }{@code >}
* {@link JAXBElement }{@code <}{@link STSourceType }{@code >}
* </p>
*
*
* @return
* The value of the abbreviatedCaseNumberOrAlbumTitleOrAuthor property.
*/
public List<JAXBElement<?>> getAbbreviatedCaseNumberOrAlbumTitleOrAuthor() {
if (abbreviatedCaseNumberOrAlbumTitleOrAuthor == null) {
abbreviatedCaseNumberOrAlbumTitleOrAuthor = new ArrayListDocx4j<>(this);
}
return this.abbreviatedCaseNumberOrAlbumTitleOrAuthor;
}
/**
* Gets the parent object in the object tree representing the unmarshalled xml document.
*
* @return
* The parent object.
*/
public Object getParent() {
return this.parent;
}
public void setParent(Object parent) {
this.parent = parent;
}
/**
* This method is invoked by the JAXB implementation on each instance when unmarshalling completes.
*
* @param parent
* The parent object in the object tree.
* @param unmarshaller
* The unmarshaller that generated the instance.
*/
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
setParent(parent);
}
@Override
public Object copyTo(Object target) {
if (target == null) {
target = new CTSourceType();
}
CTSourceType typedTarget = ((CTSourceType) target);
if (this.abbreviatedCaseNumberOrAlbumTitleOrAuthor!= null) {
for (JAXBElement item: this.abbreviatedCaseNumberOrAlbumTitleOrAuthor) {
JAXBElement copiedItem;
copiedItem = ((JAXBElement) CopyUtils.copyObjectAndSetParent(item, typedTarget));
typedTarget.getAbbreviatedCaseNumberOrAlbumTitleOrAuthor().add(copiedItem);
}
}
return typedTarget;
}
@Override
public Object copy() {
CTSourceType copy = new CTSourceType();
return copyTo(copy);
}
}
@@ -0,0 +1,287 @@
package org.docx4j.bibliography;
import java.util.List;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import org.docx4j.copy.Copyable;
import org.docx4j.list.ArrayListDocx4j;
import org.jvnet.jaxb.lang.Child;
/**
* &lt;p&gt;Java class for CT_Sources complex type&lt;/p&gt;.
*
* &lt;p&gt;The following schema fragment specifies the expected content contained within this class.&lt;/p&gt;
*
* &lt;pre&gt;{&#064;code
* &lt;complexType name="CT_Sources"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="Source" type="{http://schemas.openxmlformats.org/officeDocument/2006/bibliography}CT_SourceType" maxOccurs="unbounded" minOccurs="0"/&gt;
* &lt;/sequence&gt;
* &lt;attribute name="SelectedStyle" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String" /&gt;
* &lt;attribute name="StyleName" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String" /&gt;
* &lt;attribute name="URI" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String" /&gt;
* &lt;attribute name="Version" type="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String" /&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* }&lt;/pre&gt;
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CT_Sources", propOrder = {
"source"
})
public class CTSources implements Copyable, Child
{
/**
* Source
*
*/
@XmlElement(name = "Source")
protected List<CTSourceType> source = new ArrayListDocx4j<>(this);
/**
* Selected Style
*
*/
@XmlAttribute(name = "SelectedStyle")
protected String selectedStyle;
/**
* Documentation Style Name
*
*/
@XmlAttribute(name = "StyleName")
protected String styleName;
/**
* Uniform Resource Identifier
*
*/
@XmlAttribute(name = "URI")
protected String uri;
/**
* Bibliography version, as Word writes it (not in the standard)
*
*/
@XmlAttribute(name = "Version")
protected String version;
@XmlTransient
private Object parent;
/**
* Source
*
* Gets the value of the source property.
*
* <p>This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the Jakarta XML Binding object.
* This is why there is not a {@code set} method for the source property.</p>
*
* <p>
* For example, to add a new item, do as follows:
* </p>
* <pre>
* getSource().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CTSourceType }
* </p>
*
*
* @return
* The value of the source property.
*/
public List<CTSourceType> getSource() {
if (source == null) {
source = new ArrayListDocx4j<>(this);
}
return this.source;
}
/**
* Selected Style
*
* @return
* possible object is
* {@link String }
*
*/
public String getSelectedStyle() {
return selectedStyle;
}
/**
* Sets the value of the selectedStyle property.
*
* @param value
* allowed object is
* {@link String }
*
* @see #getSelectedStyle()
*/
public void setSelectedStyle(String value) {
this.selectedStyle = value;
}
/**
* Documentation Style Name
*
* @return
* possible object is
* {@link String }
*
*/
public String getStyleName() {
return styleName;
}
/**
* Sets the value of the styleName property.
*
* @param value
* allowed object is
* {@link String }
*
* @see #getStyleName()
*/
public void setStyleName(String value) {
this.styleName = value;
}
/**
* Uniform Resource Identifier
*
* @return
* possible object is
* {@link String }
*
*/
public String getURI() {
return uri;
}
/**
* Sets the value of the uri property.
*
* @param value
* allowed object is
* {@link String }
*
* @see #getURI()
*/
public void setURI(String value) {
this.uri = value;
}
/**
* Bibliography version, as Word writes it (not in the standard)
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
* @see #getVersion()
*/
public void setVersion(String value) {
this.version = value;
}
/**
* Gets the parent object in the object tree representing the unmarshalled xml document.
*
* @return
* The parent object.
*/
public Object getParent() {
return this.parent;
}
public void setParent(Object parent) {
this.parent = parent;
}
/**
* This method is invoked by the JAXB implementation on each instance when unmarshalling completes.
*
* @param parent
* The parent object in the object tree.
* @param unmarshaller
* The unmarshaller that generated the instance.
*/
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
setParent(parent);
}
@Override
public Object copyTo(Object target) {
if (target == null) {
target = new CTSources();
}
CTSources typedTarget = ((CTSources) target);
if (this.source!= null) {
for (CTSourceType item: this.source) {
CTSourceType copiedItem;
copiedItem = ((CTSourceType) item.copy());
copiedItem.setParent(typedTarget);
typedTarget.getSource().add(copiedItem);
}
}
if (this.selectedStyle!= null) {
String objToCopy = this.selectedStyle;
String copiedObj;
copiedObj = objToCopy;
typedTarget.selectedStyle = copiedObj;
}
if (this.styleName!= null) {
String objToCopy = this.styleName;
String copiedObj;
copiedObj = objToCopy;
typedTarget.styleName = copiedObj;
}
if (this.uri!= null) {
String objToCopy = this.uri;
String copiedObj;
copiedObj = objToCopy;
typedTarget.uri = copiedObj;
}
if (this.version!= null) {
String objToCopy = this.version;
String copiedObj;
copiedObj = objToCopy;
typedTarget.version = copiedObj;
}
return typedTarget;
}
@Override
public Object copy() {
CTSources copy = new CTSources();
return copyTo(copy);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,198 @@
package org.docx4j.bibliography;
import jakarta.xml.bind.annotation.XmlEnum;
import jakarta.xml.bind.annotation.XmlEnumValue;
import jakarta.xml.bind.annotation.XmlType;
/**
* Bibliographic Data Source Types
*
* &lt;p&gt;Java class for ST_SourceType&lt;/p&gt;.
*
* &lt;p&gt;The following schema fragment specifies the expected content contained within this class.&lt;/p&gt;
* &lt;pre&gt;{&#064;code
* &lt;simpleType name="ST_SourceType"&gt;
* &lt;restriction base="{http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes}ST_String"&gt;
* &lt;enumeration value="ArticleInAPeriodical"/&gt;
* &lt;enumeration value="Book"/&gt;
* &lt;enumeration value="BookSection"/&gt;
* &lt;enumeration value="JournalArticle"/&gt;
* &lt;enumeration value="ConferenceProceedings"/&gt;
* &lt;enumeration value="Report"/&gt;
* &lt;enumeration value="SoundRecording"/&gt;
* &lt;enumeration value="Performance"/&gt;
* &lt;enumeration value="Art"/&gt;
* &lt;enumeration value="DocumentFromInternetSite"/&gt;
* &lt;enumeration value="InternetSite"/&gt;
* &lt;enumeration value="Film"/&gt;
* &lt;enumeration value="Interview"/&gt;
* &lt;enumeration value="Patent"/&gt;
* &lt;enumeration value="ElectronicSource"/&gt;
* &lt;enumeration value="Case"/&gt;
* &lt;enumeration value="Misc"/&gt;
* &lt;/restriction&gt;
* &lt;/simpleType&gt;
* }&lt;/pre&gt;
*
*/
@XmlType(name = "ST_SourceType")
@XmlEnum
public enum STSourceType {
/**
* Article in a Periodical
*
*/
@XmlEnumValue("ArticleInAPeriodical")
ARTICLE_IN_A_PERIODICAL("ArticleInAPeriodical"),
/**
* Book
*
*/
@XmlEnumValue("Book")
BOOK("Book"),
/**
* Book Section
*
*/
@XmlEnumValue("BookSection")
BOOK_SECTION("BookSection"),
/**
* Journal Article
*
*/
@XmlEnumValue("JournalArticle")
JOURNAL_ARTICLE("JournalArticle"),
/**
* Conference Proceedings
*
*/
@XmlEnumValue("ConferenceProceedings")
CONFERENCE_PROCEEDINGS("ConferenceProceedings"),
/**
* Reporter
*
*/
@XmlEnumValue("Report")
REPORT("Report"),
/**
* Sound Recording
*
*/
@XmlEnumValue("SoundRecording")
SOUND_RECORDING("SoundRecording"),
/**
* Performance
*
*/
@XmlEnumValue("Performance")
PERFORMANCE("Performance"),
/**
* Art
*
*/
@XmlEnumValue("Art")
ART("Art"),
/**
* Document from Internet Site
*
*/
@XmlEnumValue("DocumentFromInternetSite")
DOCUMENT_FROM_INTERNET_SITE("DocumentFromInternetSite"),
/**
* Internet Site
*
*/
@XmlEnumValue("InternetSite")
INTERNET_SITE("InternetSite"),
/**
* Film
*
*/
@XmlEnumValue("Film")
FILM("Film"),
/**
* Interview
*
*/
@XmlEnumValue("Interview")
INTERVIEW("Interview"),
/**
* Patent
*
*/
@XmlEnumValue("Patent")
PATENT("Patent"),
/**
* Electronic Source
*
*/
@XmlEnumValue("ElectronicSource")
ELECTRONIC_SOURCE("ElectronicSource"),
/**
* Case
*
*/
@XmlEnumValue("Case")
CASE("Case"),
/**
* Miscellaneous
*
*/
@XmlEnumValue("Misc")
MISC("Misc");
private final String value;
STSourceType(String v) {
value = v;
}
/**
* Gets the value associated to the enum constant.
*
* @return
* The value linked to the enum.
*/
public String value() {
return value;
}
/**
* Gets the enum associated to the value passed as parameter.
*
* @param v
* The value to get the enum from.
* @return
* The enum which corresponds to the value, if it exists.
* @throws IllegalArgumentException
* If no value matches in the enum declaration.
*/
public static STSourceType fromValue(String v) {
for (STSourceType c: STSourceType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
@@ -0,0 +1,2 @@
@jakarta.xml.bind.annotation.XmlSchema(namespace = "http://schemas.openxmlformats.org/officeDocument/2006/bibliography", elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.docx4j.bibliography;
@@ -0,0 +1,156 @@
package org.docx4j.cei;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlSchemaType;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlType;
import org.docx4j.copy.Copyable;
import org.docx4j.w16.CTExtensionList;
import org.jvnet.jaxb.lang.Child;
/**
* &lt;p&gt;Java class for CT_CommentEntityInfo complex type&lt;/p&gt;.
*
* &lt;p&gt;The following schema fragment specifies the expected content contained within this class.&lt;/p&gt;
*
* &lt;pre&gt;{&#064;code
* &lt;complexType name="CT_CommentEntityInfo"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="extLst" type="{http://schemas.microsoft.com/office/word/2018/wordml}CT_ExtensionList" minOccurs="0"/&gt;
* &lt;/sequence&gt;
* &lt;attribute name="entityType" type="{http://www.w3.org/2001/XMLSchema}unsignedInt" default="0" /&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* }&lt;/pre&gt;
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CT_CommentEntityInfo", propOrder = {
"extLst"
})
public class CTCommentEntityInfo implements Copyable, Child
{
protected CTExtensionList extLst;
@XmlAttribute(name = "entityType", namespace = "http://schemas.microsoft.com/office/word/2026/wordml/cei")
@XmlSchemaType(name = "unsignedInt")
protected Long entityType;
@XmlTransient
private Object parent;
/**
* Gets the value of the extLst property.
*
* @return
* possible object is
* {@link CTExtensionList }
*
*/
public CTExtensionList getExtLst() {
return extLst;
}
/**
* Sets the value of the extLst property.
*
* @param value
* allowed object is
* {@link CTExtensionList }
*
*/
public void setExtLst(CTExtensionList value) {
this.extLst = value;
}
/**
* Gets the value of the entityType property.
*
* @return
* possible object is
* {@link Long }
*
*/
public long getEntityType() {
if (entityType == null) {
return 0L;
} else {
return entityType;
}
}
/**
* Sets the value of the entityType property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setEntityType(Long value) {
this.entityType = value;
}
/**
* Gets the parent object in the object tree representing the unmarshalled xml document.
*
* @return
* The parent object.
*/
public Object getParent() {
return this.parent;
}
public void setParent(Object parent) {
this.parent = parent;
}
/**
* This method is invoked by the JAXB implementation on each instance when unmarshalling completes.
*
* @param parent
* The parent object in the object tree.
* @param unmarshaller
* The unmarshaller that generated the instance.
*/
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
setParent(parent);
}
@Override
public Object copyTo(Object target) {
if (target == null) {
target = new CTCommentEntityInfo();
}
CTCommentEntityInfo typedTarget = ((CTCommentEntityInfo) target);
if (this.extLst!= null) {
CTExtensionList objToCopy = this.extLst;
CTExtensionList copiedObj;
copiedObj = ((CTExtensionList) objToCopy.copy());
copiedObj.setParent(typedTarget);
typedTarget.extLst = copiedObj;
}
if (this.entityType!= null) {
Long objToCopy = this.entityType;
Long copiedObj;
copiedObj = objToCopy;
typedTarget.entityType = copiedObj;
}
return typedTarget;
}
@Override
public Object copy() {
CTCommentEntityInfo copy = new CTCommentEntityInfo();
return copyTo(copy);
}
}
@@ -0,0 +1,59 @@
package org.docx4j.cei;
import javax.xml.namespace.QName;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.annotation.XmlElementDecl;
import jakarta.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the org.docx4j.cei package.
* <p>An ObjectFactory allows you to programmatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private static final QName _CommentEntityInfo_QNAME = new QName("http://schemas.microsoft.com/office/word/2026/wordml/cei", "commentEntityInfo");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.docx4j.cei
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link CTCommentEntityInfo }
*
* @return
* the new instance of {@link CTCommentEntityInfo }
*/
public CTCommentEntityInfo createCTCommentEntityInfo() {
return new CTCommentEntityInfo();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link CTCommentEntityInfo }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link CTCommentEntityInfo }{@code >}
*/
@XmlElementDecl(namespace = "http://schemas.microsoft.com/office/word/2026/wordml/cei", name = "commentEntityInfo")
public JAXBElement<CTCommentEntityInfo> createCommentEntityInfo(CTCommentEntityInfo value) {
return new JAXBElement<>(_CommentEntityInfo_QNAME, CTCommentEntityInfo.class, null, value);
}
}
@@ -0,0 +1,2 @@
@jakarta.xml.bind.annotation.XmlSchema(namespace = "http://schemas.microsoft.com/office/word/2026/wordml/cei", elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.docx4j.cei;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,209 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.chart.render;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import org.docx4j.chart.render.api.Drawing;
import org.docx4j.chart.render.api.SvgWriter;
import org.docx4j.dml.CTShapeProperties;
import org.docx4j.dml.chart.CTChartSpace;
import org.docx4j.dml.chart.CTLayout;
import org.docx4j.model.chart.ChartAxis;
import org.docx4j.model.chart.ChartDataLabels;
import org.docx4j.model.chart.ChartFill;
import org.docx4j.model.chart.ChartFonts;
import org.docx4j.model.chart.ChartGroup;
import org.docx4j.model.chart.ChartModel;
import org.docx4j.model.chart.ChartRenderCheck;
import org.docx4j.model.chart.ChartRenderer;
import org.docx4j.model.chart.ChartSeries;
import org.docx4j.model.color.ThemeColors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
/**
* docx4j's renderer of the classic chart types (CR-037): the chart laid out as Office lays it out
* ({@link ChartLayout}), painted onto a {@code Graphics2D}, Batik's SVG generator's for SVG.
*
* <p>Draws the column and bar charts (clustered, stacked, 100%), line and area charts over
* categories or dates, scatter charts (markers, straight or smoothed lines), pies and doughnuts,
* with their data labels, axis titles, manual layouts, axis options, fills (solid, gradients,
* patterns), lines (dashed) and shadows and glows; refuses (its box stays empty) the other kinds,
* combinations, secondary axes and 3-D (CR-037 section 4.6), and draws simplified (saying so) a
* picture fill, inner and preset shadows, reflections and soft edges.</p>
*
* @since 17.3.3 (CR-037)
*/
public class ClassicChartRenderer implements ChartRenderer {
private static final Logger log = LoggerFactory.getLogger(ClassicChartRenderer.class);
/** {@link SvgWriter#TEXT_AS_SHAPES} (CR-037 D6), named here as before CR-039 */
public static final String TEXT_AS_SHAPES = SvgWriter.TEXT_AS_SHAPES;
public ClassicChartRenderer() {
}
@Override
public ChartRenderCheck check(ChartModel chart, ThemeColors theme) {
List<String> refused = new ArrayList<>();
List<String> simplified = new ArrayList<>();
if (chart == null) {
refused.add("no chart");
return new ChartRenderCheck(refused, simplified);
}
if (chart.getGroups().size() != 1) refused.add(chart.getGroups().size() + " chart groups (a combination)");
for (ChartGroup g : chart.getGroups()) {
switch (g.getKind()) {
case BAR:
case LINE:
case AREA:
case PIE:
case DOUGHNUT:
case SCATTER:
break;
default:
refused.add("a " + g.getKind().value() + " chart");
}
for (ChartSeries s : g.getShownSeries()) {
fill(s.getFill(), "a series' fill", simplified);
}
}
int value = 0, category = 0;
for (ChartAxis a : chart.getAxes()) {
if (a.getKind() == ChartAxis.Kind.VALUE) value++;
else if (a.getKind() == ChartAxis.Kind.CATEGORY || a.getKind() == ChartAxis.Kind.DATE) category++;
else refused.add("a " + a.getKind() + " axis");
if ("r".equals(a.getPosition()) || "t".equals(a.getPosition())) refused.add("an axis at the " + a.getPosition());
}
// a scatter chart's two axes are both value axes
boolean scatter = chart.getGroups().stream().anyMatch(g -> g.getKind() == ChartGroup.Kind.SCATTER);
if (scatter ? value > 2 || category > 0 : value > 1 || category > 1) refused.add("a secondary axis");
CTChartSpace cs = chart.getSource();
if (cs.getChart() != null) {
if (cs.getChart().getView3D() != null && chart.getGroups().stream().anyMatch(g -> g.getKind().value().endsWith("3D"))) {
refused.add("3-D");
}
}
effects(cs.getSpPr(), "the chart area", simplified);
for (ChartGroup g : chart.getGroups()) {
for (ChartSeries s : g.getShownSeries()) {
Object sp = null;
try {
sp = s.getSource().getClass().getMethod("getSpPr").invoke(s.getSource());
} catch (ReflectiveOperationException e) {
// none
}
if (sp instanceof CTShapeProperties) effects((CTShapeProperties) sp, "a series", simplified);
}
}
return new ChartRenderCheck(dedupe(refused), dedupe(simplified));
}
private static boolean shown(ChartDataLabels l) {
if (l == null || Boolean.TRUE.equals(l.getDeleted())) return false;
return Boolean.TRUE.equals(l.getShowValue()) || Boolean.TRUE.equals(l.getShowCategoryName())
|| Boolean.TRUE.equals(l.getShowSeriesName()) || Boolean.TRUE.equals(l.getShowPercent())
|| Boolean.TRUE.equals(l.getShowBubbleSize());
}
private static boolean manual(CTLayout l) {
return l != null && l.getManualLayout() != null;
}
private static void fill(ChartFill f, String what, List<String> simplified) {
if (f == null) return;
switch (f.getKind()) {
case PICTURE:
simplified.add(what + ": a picture drawn as grey");
break;
default:
}
}
/** Effects drawn simplified or not at all (outer shadows and glows are drawn, as pictures, as Office's PDFs have them) */
private static void effects(CTShapeProperties sp, String what, List<String> simplified) {
if (sp == null || sp.getEffectLst() == null) return;
org.docx4j.dml.CTEffectList e = sp.getEffectLst();
if (e.getInnerShdw() != null) simplified.add(what + ": its inner shadow not drawn");
if (e.getPrstShdw() != null) simplified.add(what + ": its preset shadow not drawn");
if (e.getReflection() != null) simplified.add(what + ": its reflection not drawn");
if (e.getSoftEdge() != null) simplified.add(what + ": its soft edges not drawn");
}
private static List<String> dedupe(List<String> l) {
List<String> out = new ArrayList<>();
for (String s : l) if (!out.contains(s)) out.add(s);
return out;
}
/** The chart laid out (for the gate, which compares it with Office's layout) */
Drawing layout(ChartModel chart, ThemeColors theme, ChartFonts fonts, double width, double height) {
return ChartLayout.layout(chart, theme, fonts, width, height);
}
@Override
public void draw(ChartModel chart, ThemeColors theme, ChartFonts fonts, double width, double height, Graphics2D g) {
draw(chart, theme, fonts, width, height, g, false);
}
private void draw(ChartModel chart, ThemeColors theme, ChartFonts fonts, double width, double height, Graphics2D g, boolean raster) {
if (!check(chart, theme).isDrawn()) return;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
layout(chart, theme, fonts, width, height).paint(g, raster);
}
/** The chart as a picture, its rectangles' edges on whole pixels as Excel's pictures have them */
@Override
public BufferedImage toImage(ChartModel chart, ThemeColors theme, ChartFonts fonts, double width, double height, double dpi) {
if (!check(chart, theme).isDrawn()) return null;
double scale = dpi / 72.0;
BufferedImage image = new BufferedImage((int) Math.max(1, Math.ceil(width * scale)), (int) Math.max(1, Math.ceil(height * scale)),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
try {
g.setColor(java.awt.Color.WHITE);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.scale(scale, scale);
draw(chart, theme, fonts, width, height, g, true);
} finally {
g.dispose();
}
return image;
}
@Override
public Document toSvg(ChartModel chart, ThemeColors theme, ChartFonts fonts, double width, double height) {
if (!check(chart, theme).isDrawn()) return null;
try {
return SvgWriter.toSvg(layout(chart, theme, fonts, width, height));
} catch (RuntimeException e) {
log.warn("Could not draw the chart as SVG: " + e, e);
return null;
}
}
}
@@ -0,0 +1,255 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.chart.render.api;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* A value axis's bounds and major unit as Excel computes them where the file leaves them
* automatic (CR-037 §11, findings 5 and 9; probes R2 and R11):
* <ul>
* <li>the minimum is zero where the data's range is more than a sixth of its maximum (all
* positive), else the data's minimum less half its range, down to the unit; the maximum is
* the data's plus a twentieth of the range from that minimum, up to the unit (KB 214075, which
* has the data's range); data of either sign is padded a twentieth at both ends; all
* negative is mirrored; all zeros is 0 to 1 (on 137 column probes, R1 to R12, none apart);</li>
* <li>the unit is the finest of 1, 2 and 5 times a power of ten that gives at most ten
* intervals, each a label's line, within the axis's length less {@link #RESERVE}
* (n lines &lt;= length - reserve); where none does, the coarsest that gives one interval;</li>
* <li>a log axis runs from the power of its base below the data to the power above, by the base;</li>
* <li>a 100% axis runs from the data's least share to its greatest, each out to the unit and no
* further than -100% and 100%, unpadded (r14-stacked-100-negative: -36% to 77% is -40% to 80%;
* all positive, 0 to 100%);</li>
* <li>a scatter chart's x axis, its data not from zero, is padded a twentieth of their range at
* both ends, not the half range below (p6-scatter-dates: 46023 to 46026 is 46022.5 to 46026.5
* by 0.5).</li>
* </ul>
* A bound or unit the file sets is kept. The length is the plot's height with one line of
* category labels (Excel chooses the unit before it wraps or turns them). A horizontal value axis
* (a bar chart's, a scatter chart's x axis) has its own test of whether its labels fit
* ({@link Fits}).
*
* @since 17.3.3 (CR-039: from docx4j-chart-render's internals, CR-037)
*/
public final class AxisScale {
/**
* What a vertical axis's length keeps back from its intervals' lines: 8.93 to 9.89pt, the same at
* 7 to 16pt (463 tests: R1 to R13 and r14-sweep-column-h's 182 heights). Phase 1's
* (n + 1) lines within the length and 4.87pt fitted R11 alone, whose 14pt probes set it
*/
public static final double RESERVE = 9.41;
/** At most this many intervals (R2, R11) */
public static final int MAX_INTERVALS = 10;
private final double min;
private final double max;
private final double unit;
private final boolean log;
private AxisScale(double min, double max, double unit, boolean log) {
this.min = min;
this.max = max;
this.unit = unit;
this.log = log;
}
/** The axis's least value */
public double getMin() {
return min;
}
/** The axis's greatest value */
public double getMax() {
return max;
}
/** The major unit: a log axis's base */
public double getUnit() {
return unit;
}
/** Whether the axis is logarithmic */
public boolean isLog() {
return log;
}
/** The values labelled, min to max */
public List<Double> values() {
List<Double> v = new ArrayList<>();
if (log) {
for (double x = min; x <= max * (1 + 1e-9); x *= unit) v.add(x);
return v;
}
BigDecimal lo = BigDecimal.valueOf(min), u = BigDecimal.valueOf(unit);
// (a doubled unit can stop short of the maximum: 0 to 60000 by 40000)
int n = (int) Math.floor((max - min) / unit + 1e-9);
for (int k = 0; k <= n; k++) v.add(lo.add(u.multiply(BigDecimal.valueOf(k))).doubleValue());
return v;
}
/** Where a value falls between min (0) and max (1) */
public double fraction(double v) {
if (log) return (Math.log(v) - Math.log(min)) / (Math.log(max) - Math.log(min));
return (v - min) / (max - min);
}
/**
* The unit doubled, the bounds kept: a horizontal axis's labels that overlap at the unit its
* length gives (r14-sweep-bar-x10000: 0 to 60000 by 40000)
*/
public AxisScale doubled() {
return new AxisScale(min, max, unit * 2, log);
}
public static int intervals(double lo, double hi, double u) {
return (int) Math.round((hi - lo) / u);
}
/** Whether an axis's labels fit at a unit: its bounds, the unit, the intervals */
public interface Fits {
boolean fits(double min, double max, double unit, int intervals);
}
/**
* @param dataMin, dataMax the values plotted
* @param setMin, setMax, setUnit what the file states (null: automatic)
* @param logBase a log axis's base, or null
* @param length the axis's length in points (see the class's note)
* @param line the height of a label's line
*/
public static AxisScale of(double dataMin, double dataMax, Double setMin, Double setMax, Double setUnit, Double logBase,
double length, double line) {
return of(dataMin, dataMax, setMin, setMax, setUnit, logBase, (lo, hi, u, n) -> n * line <= length - RESERVE, Bounds.VALUE);
}
/** How an axis's automatic bounds are found (see the class's note) */
public enum Bounds {
/** a value axis's */
VALUE,
/** a 100% chart's */
PERCENT,
/** a scatter chart's x axis's */
X
}
/** An axis's scale, its bounds found so, its length and line as {@link #of(double, double, Double, Double, Double, Double, double, double)}'s */
public static AxisScale of(double dataMin, double dataMax, Double setMin, Double setMax, Double setUnit, Double logBase,
double length, double line, Bounds kind) {
return of(dataMin, dataMax, setMin, setMax, setUnit, logBase, (lo, hi, u, n) -> n * line <= length - RESERVE, kind);
}
/**
* @param fits whether the labels fit at a unit (a vertical axis: n lines within its length less
* {@link #RESERVE})
*/
public static AxisScale of(double dataMin, double dataMax, Double setMin, Double setMax, Double setUnit, Double logBase, Fits fits) {
return of(dataMin, dataMax, setMin, setMax, setUnit, logBase, fits, Bounds.VALUE);
}
/** @param kind how the bounds are found (see the class's note) */
public static AxisScale of(double dataMin, double dataMax, Double setMin, Double setMax, Double setUnit, Double logBase, Fits fits,
Bounds kind) {
if (logBase != null && logBase > 1 && dataMin > 0) {
double b = logBase;
double lo = setMin != null ? setMin : Math.pow(b, Math.floor(Math.log(dataMin) / Math.log(b) + 1e-9));
double hi = setMax != null ? setMax : Math.pow(b, Math.ceil(Math.log(dataMax) / Math.log(b) - 1e-9));
if (hi <= lo) hi = lo * b;
return new AxisScale(lo, hi, b, true);
}
boolean zeros = dataMin == 0 && dataMax == 0;
if (setUnit != null && setUnit > 0) {
double[] b = bounds(dataMin, dataMax, setUnit, setMin, setMax, zeros, kind);
return new AxisScale(b[0], b[1], setUnit, false);
}
double[] oneInterval = null;
double oneUnit = 0;
for (double u : units()) {
double[] b = bounds(dataMin, dataMax, u, setMin, setMax, zeros, kind);
int n = intervals(b[0], b[1], u);
if (n < 1) continue;
if (n <= MAX_INTERVALS && fits.fits(b[0], b[1], u, n)) return new AxisScale(b[0], b[1], u, false);
if (n == 1 && oneInterval == null) {
oneInterval = b;
oneUnit = u;
}
}
if (oneInterval != null) return new AxisScale(oneInterval[0], oneInterval[1], oneUnit, false);
double[] b = bounds(dataMin, dataMax, 1, setMin, setMax, zeros, kind);
return new AxisScale(b[0], b[1], Math.max(1e-12, b[1] - b[0]), false);
}
/** 1, 2 and 5 times the powers of ten, ascending */
private static List<Double> units() {
List<Double> l = new ArrayList<>();
for (int e = -9; e <= 15; e++) {
for (int m : new int[] { 1, 2, 5 }) l.add(BigDecimal.valueOf(m).scaleByPowerOfTen(e).doubleValue());
}
return l;
}
private static double down(double v, double u) {
return Math.floor(v / u + 1e-9) * u;
}
private static double up(double v, double u) {
return Math.ceil(v / u - 1e-9) * u;
}
private static double[] bounds(double dmin, double dmax, double u, Double setMin, Double setMax, boolean zeros, Bounds kind) {
double lo, hi;
if (kind == Bounds.PERCENT) {
lo = dmin >= 0 ? 0 : Math.max(-1, down(dmin, u));
hi = dmax <= 0 ? 0 : Math.min(1, up(dmax, u));
} else if (zeros) {
lo = 0;
hi = 1;
} else if (dmin >= 0) {
double range = dmax - dmin;
boolean fromZero = dmax == dmin || range > dmax / 6;
lo = fromZero ? 0 : down(dmin - (kind == Bounds.X ? range / 20 : range / 2), u);
// padded a twentieth of the range from the axis's minimum (R12: 1.1 to 4.8 is 0 to 6
// by 1, not 0 to 5 by 0.5; a constant series so pads from zero)
hi = up(dmax + (dmax - lo) / 20, u);
} else if (dmax <= 0) {
double[] m = bounds(-dmax, -dmin, u, null, null, false, kind);
lo = -m[1];
hi = -m[0];
} else {
double pad = (dmax - dmin) / 20;
lo = down(dmin - pad, u);
hi = up(dmax + pad, u);
}
// a bound set anchors the ticks: the other runs from it by the unit (R2: max 150 by 20 gives -10)
if (setMin != null && setMax == null) {
hi = setMin + Math.ceil((hi - setMin) / u - 1e-9) * u;
lo = setMin;
} else if (setMax != null && setMin == null) {
lo = setMax - Math.ceil((setMax - lo) / u - 1e-9) * u;
hi = setMax;
} else if (setMin != null) {
lo = setMin;
hi = setMax;
}
if (hi <= lo) hi = lo + u;
return new double[] { lo, hi };
}
}
@@ -0,0 +1,298 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.chart.render.api;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
/**
* Where Office puts a chart's title and legend, and so where the plot area goes (CR-037's
* measurements, R1 to R17): the title centred at the top, its lines wrapped to a share of the
* chart; the legend at the top, bottom, left, right or top right, its entries in rows or a
* column; the plot area in what they leave. These are a classic chart's rules (a {@code c:title},
* a {@code c:legend}); a chartex chart's {@code cx:title} and {@code cx:legend} also take an
* alignment, which these don't.
*
* <p>Sizes are points, from the chart's top left. The plot area's edges are an array: left, top,
* right, bottom.</p>
*
* @since 17.3.3 (CR-039: from docx4j-chart-render's internals, CR-037)
*/
public final class ChartFrame {
/** The chart area's inner frame: Office's elements are placed from 4pt inside the chart's box */
public static final double INSET = 4;
/** The title's top, in the inner frame */
public static final double TITLE_TOP = 2;
/** The title's box: its text, 3pt either side, 1.5pt above and below */
public static final double TITLE_PAD_X = 3, TITLE_PAD_Y = 1.5;
/** The title's lines are no wider than this share of the chart, less its padding (R4) */
public static final double TITLE_MAX = 0.8;
/** Between the title, the plot area and the legend */
public static final double GAP = 11;
/** The plot area from the inner frame's edges, where nothing else is beside it */
public static final double PLOT_EDGE = 7;
/** The legend from the inner frame's edge it is at */
public static final double LEGEND_EDGE = 2;
/** A legend key's side, a share of the legend's line; the key is inset half a key */
public static final double LEGEND_KEY = 0.45;
/**
* A horizontal legend is its entries plus this share of each entry's width, spread evenly
* before, between and after them (R1, R2, R4: one, two, three and eight entries; Calibri and Aptos)
*/
public static final double LEGEND_SLOT = 0.2;
/** A vertical legend's entries are inset this much either side */
public static final double LEGEND_SIDE = 1.5;
/** A legend's entries are this far below its top */
public static final double LEGEND_TOP = 3;
/** A legend at the top (or top right) is this far below the title (r14-legend-top, r14-legend-top-right) */
public static final double LEGEND_BELOW_TITLE = 6;
/**
* A legend at the top right: the plot area this far below it, and this much higher off the
* bottom (r14-legend-top-right, one probe: provisional)
*/
public static final double LEGEND_TR_BELOW = 5, LEGEND_TR_BOTTOM = 6;
/**
* A horizontal legend's entries too wide for {@link #LEGEND_MAX} of the chart go in rows, as many
* entries to each as the fewest rows allow, closed up; each row after the first adds a row's
* height less this (r14-legend-rows-8: eight entries in two rows of four; one probe: provisional)
*/
public static final double LEGEND_ROW_LESS = 1.5;
/** A horizontal legend is at most this share of the chart's width, its entries closing up (r11-bar-w144) */
public static final double LEGEND_MAX = 0.9;
private ChartFrame() {
}
/** The plot area's edges where nothing takes room from it: left, top, right, bottom */
public static double[] plotEdges(double w, double h) {
double ix = INSET, iy = INSET, iw = w - 2 * INSET, ih = h - 2 * INSET;
return new double[] { ix + PLOT_EDGE, iy + PLOT_EDGE, ix + iw - PLOT_EDGE, iy + ih - PLOT_EDGE };
}
// ------------------------------------------------------------------ the title
/** How wide a title's lines may be ({@link TextWrap#wrap(List, double)} them to it) */
public static double titleWidth(double w) {
return TITLE_MAX * w - 2 * TITLE_PAD_X;
}
/** The title's box where Office puts it: its lines, padded, centred at the chart's top */
public static Rectangle2D titleBox(double w, List<TextWrap.Line> lines) {
double ix = INSET, iy = INSET, iw = w - 2 * INSET;
double tw = 0, th = 0;
for (TextWrap.Line l : lines) {
tw = Math.max(tw, l.getWidth());
th += l.getLineHeight();
}
double bw = tw + 2 * TITLE_PAD_X, bh = th + 2 * TITLE_PAD_Y;
return new Rectangle2D.Double(ix + (iw - bw) / 2, iy + TITLE_TOP, bw, bh);
}
/**
* The plot area's top below a title's box where Office puts it ({@link #titleBox}): kept so
* where the title is placed by hand (r9-title-moved); not taken where the title is over the
* plot area (overlay)
*/
public static double belowTitle(Rectangle2D titleBox) {
return titleBox.getY() + titleBox.getHeight() + GAP;
}
/** The title's lines in its box, each centred, its pieces one after another in their styles */
public static List<Drawing.Text> titleTexts(Rectangle2D box, List<TextWrap.Line> lines) {
List<Drawing.Text> texts = new ArrayList<>();
double bx = box.getX(), bw = box.getWidth();
double y = box.getY() + TITLE_PAD_Y;
for (TextWrap.Line l : lines) {
double x = bx + (bw - l.getWidth()) / 2;
for (TextWrap.Seg sg : l.getSegs()) {
double sw = sg.getStyle().width(sg.getText());
texts.add(sg.getStyle().text(sg.getText(), x, y + l.getAscent() + 0.15, sw, 0, "title"));
x += sw;
}
y += l.getLineHeight();
}
return texts;
}
// ------------------------------------------------------------------ the legend
/** A legend's key's side for its text's style (a line key is as high, and wider) */
public static double key(TextStyle s) {
return LEGEND_KEY * s.getLineHeight();
}
/** A legend laid out: its box, its entries' places, and the plot area's edges it leaves */
public static final class Legend {
private final Rectangle2D box;
private final List<double[]> entries;
private final double[] plot;
private final double cellWidth;
Legend(Rectangle2D box, List<double[]> entries, double[] plot, double cellWidth) {
this.box = box;
this.entries = entries;
this.plot = plot;
this.cellWidth = cellWidth;
}
/** The box Office reports for the legend */
public Rectangle2D getBox() {
return box;
}
/** Each entry's place: its left, its top and its width (the widest's: Excel reports each at it) */
public List<double[]> getEntries() {
return entries;
}
/** The plot area's edges the legend leaves: left, top, right, bottom */
public double[] getPlot() {
return plot;
}
/** An entry's cell, where the legend is sized by hand ({@link ChartFrame#grid}) */
public double getCellWidth() {
return cellWidth;
}
}
/**
* The legend where Office puts it: at the top or bottom ({@code t}, {@code b}) its entries in
* rows, each spaced by its own width, centred across the chart; at the left or right ({@code l},
* {@code r}) in a column centred on the plot area; at the top right ({@code tr}) in a column below
* the title, the plot area below it
*
* @param widths each entry's width: twice its key's, and its text's
* @param overlay the legend over the plot area, taking no room from it
* @param title the title's box as placed, or null for none
* @param plot the plot area's edges so far (below the title): left, top, right, bottom
*/
public static Legend legend(double w, double h, List<Double> widths, TextStyle s, String pos, boolean overlay, Rectangle2D title,
double[] plot) {
double ix = INSET, iy = INSET, iw = w - 2 * INSET, ih = h - 2 * INSET;
double plotLeft = plot[0], plotTop = plot[1], plotRight = plot[2], plotBottom = plot[3];
boolean horizontal = "b".equals(pos) || "t".equals(pos);
// at the top, or the top right, the legend is below the title (or at the frame's edge)
double top = title != null ? title.getMaxY() + LEGEND_BELOW_TITLE : iy + LEGEND_EDGE;
double rowH = s.getLineHeight() + 5.97 - 0.0102 * s.getSize();
double maxW = 0;
for (double ew : widths) maxW = Math.max(maxW, ew);
double lx, ly, lw, lh;
List<double[]> at = new ArrayList<>();
if (horizontal) {
// each entry spaced by its own width, but reported (Excel) at the widest's (r1-pie)
int k = widths.size();
double sum = 0;
for (double ew : widths) sum += ew;
int rows = Math.max(1, (int) Math.ceil(sum / (LEGEND_MAX * w) - 1e-9));
int perRow = (int) Math.ceil(k / (double) rows);
rows = (int) Math.ceil(k / (double) perRow);
if (rows == 1) {
lw = Math.min((1 + LEGEND_SLOT) * sum, Math.max(sum, LEGEND_MAX * w));
} else {
lw = 0;
for (int r = 0; r < rows; r++) {
double rw = 0;
for (int i = r * perRow; i < Math.min(k, (r + 1) * perRow); i++) rw += widths.get(i);
lw = Math.max(lw, rw);
}
}
double pad = rows == 1 ? (lw - sum) / (k + 1) : 0;
lh = rows * rowH - (rows - 1) * LEGEND_ROW_LESS;
lx = ix + (iw - lw) / 2;
ly = "b".equals(pos) ? iy + ih - LEGEND_EDGE - lh : top;
for (int r = 0; r < rows; r++) {
double x = lx + pad;
for (int i = r * perRow; i < Math.min(k, (r + 1) * perRow); i++) {
at.add(new double[] { x, ly + LEGEND_TOP + r * rowH, maxW });
x += widths.get(i) + pad;
}
}
// a legend over the plot area (overlay) takes no room from it
if (overlay) {
// nothing
} else if ("b".equals(pos)) plotBottom = ly - GAP;
else plotTop = ly + lh + GAP;
} else {
lw = maxW + 3 + 2 * LEGEND_SIDE;
lh = widths.size() * rowH;
lx = "l".equals(pos) ? ix + LEGEND_EDGE : ix + iw - LEGEND_EDGE - lw;
// centred on the plot area; at the top right, below the title, the plot area below it
ly = "tr".equals(pos) ? top : (plotTop + plotBottom) / 2 - lh / 2;
for (int i = 0; i < widths.size(); i++) at.add(new double[] { lx + LEGEND_SIDE, ly + LEGEND_TOP + i * rowH, maxW + 3 });
if (overlay) {
// nothing
} else if ("l".equals(pos)) plotLeft = lx + lw + GAP;
else plotRight = lx - GAP;
if ("tr".equals(pos) && !overlay) {
plotTop = ly + lh + LEGEND_TR_BELOW;
plotBottom -= LEGEND_TR_BOTTOM;
}
}
return new Legend(new Rectangle2D.Double(lx, ly, lw, lh), at, new double[] { plotLeft, plotTop, plotRight, plotBottom },
horizontal ? maxW : maxW + 3);
}
/**
* A legend sized by hand: its k entries in a grid of as many columns as hold the widest, each
* centred in its cell, 0.75pt right and 0.055pt down (r9-legend-moved, r15-legend-right-sized)
*
* @param cellWidth {@link Legend#getCellWidth()}
*/
public static List<double[]> grid(Rectangle2D box, int k, double cellWidth, TextStyle s) {
int cols = Math.max(1, Math.min(k, (int) Math.floor(box.getWidth() / cellWidth)));
int rows = (int) Math.ceil(k / (double) cols);
double cw = box.getWidth() / cols, ch = box.getHeight() / rows;
List<double[]> at = new ArrayList<>();
for (int i = 0; i < k; i++) {
at.add(new double[] { box.getX() + (i % cols) * cw + (cw - cellWidth) / 2 + 0.75,
box.getY() + (i / cols) * ch + (ch - s.getLineHeight()) / 2 + 0.055, cellWidth });
}
return at;
}
/** The box Office reports for an entry: its place's, a line high */
public static Rectangle2D entryBox(double[] entry, TextStyle s) {
return new Rectangle2D.Double(entry[0], entry[1], entry[2], s.getLineHeight());
}
/** The box Office reports for an entry's key, keyWidth wide (a line key's, else {@link #key}) */
public static Rectangle2D keyBox(double[] entry, double keyWidth, TextStyle s) {
double key = key(s);
return new Rectangle2D.Double(entry[0] + keyWidth / 2, entry[1] + key / 2, keyWidth, key);
}
/** Where an entry's key is drawn: its top left, 0.75pt right and 0.055 of the text's size down of {@link #keyBox} */
public static Point2D keyAt(double[] entry, double keyWidth, TextStyle s) {
double key = key(s);
return new Point2D.Double(entry[0] + keyWidth / 2 + 0.75, entry[1] + key / 2 + 0.055 * s.getSize());
}
/** Where an entry's text starts */
public static double textX(double[] entry, double keyWidth, TextStyle s) {
return entry[0] + 2 * keyWidth + (2.94 / 10.986 - LEGEND_KEY / 2) * s.getLineHeight();
}
/** An entry's text's baseline */
public static double textBaseline(double[] entry, TextStyle s) {
return entry[1] + s.getAscent() * 0.956;
}
}
@@ -0,0 +1,770 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.chart.render.api;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A chart laid out: what is painted, in painting order, in points from the chart's top left,
* and the boxes Office's object model reports for the same chart (CR-037 §11: the plot area,
* the title, the legend and its entries, each point, a pie's slices), so that a layout can be
* compared with Excel's without painting it.
*
* <p>A renderer builds one ({@link #add}), and paints it ({@link #paint}) or writes it as SVG
* ({@link SvgWriter}). Sizes are points, from the chart's top left.</p>
*
* @since 17.3.3 (CR-039: from docx4j-chart-render's internals, CR-037)
*/
public final class Drawing {
/**
* A DrawingML gradient ({@code a:gradFill}), made a paint for each shape's box: linear at an
* angle (clockwise from the x axis, scaled to the box where it says), or along a path from its
* focus ({@code a:fillToRect}) out to the farthest corner, its first stop at the focus
*/
public static final class Gradient {
private final float[] stops;
private final Color[] colours;
private final boolean linear, scaled;
private final double angle;
/** a path's focus: its insets from the box's left, top, right and bottom, shares of the box */
private final double[] focus;
/**
* @param stops strictly increasing, 0 to 1
* @param angle a linear gradient's, degrees clockwise from the x axis
* @param focus a path's (null for a linear gradient)
*/
public Gradient(float[] stops, Color[] colours, boolean linear, double angle, boolean scaled, double[] focus) {
this.stops = stops;
this.colours = colours;
this.linear = linear;
this.angle = angle;
this.scaled = scaled;
this.focus = focus;
}
/** The stops' places, 0 to 1 */
public float[] getStops() {
return stops;
}
/** The stops' colours */
public Color[] getColours() {
return colours;
}
/** Linear at {@link #getAngle()}, else along a path from {@link #getFocus()} */
public boolean isLinear() {
return linear;
}
/** A linear gradient's angle scaled to the box ({@code a:lin/@scaled}) */
public boolean isScaled() {
return scaled;
}
/** A linear gradient's angle, degrees clockwise from the x axis */
public double getAngle() {
return angle;
}
/** A path's focus: its insets from the box's left, top, right and bottom, shares of the box; null where linear */
public double[] getFocus() {
return focus;
}
/** The gradient as a paint for a shape's box */
public java.awt.Paint paint(Rectangle2D b) {
if (colours.length == 1) return colours[0];
double w = Math.max(b.getWidth(), 1e-6), h = Math.max(b.getHeight(), 1e-6);
if (linear) {
double t = Math.toRadians(angle), cos = Math.cos(t), sin = Math.sin(t);
if (scaled) {
// in the unit square, then scaled to the box (the angle is the box's diagonal's at 45)
double len = Math.abs(cos) + Math.abs(sin);
java.awt.geom.Point2D p0 = new java.awt.geom.Point2D.Double(0.5 - cos * len / 2, 0.5 - sin * len / 2);
java.awt.geom.Point2D p1 = new java.awt.geom.Point2D.Double(0.5 + cos * len / 2, 0.5 + sin * len / 2);
AffineTransform at = new AffineTransform(w, 0, 0, h, b.getX(), b.getY());
return new java.awt.LinearGradientPaint(p0, p1, stops, colours, java.awt.MultipleGradientPaint.CycleMethod.NO_CYCLE,
java.awt.MultipleGradientPaint.ColorSpaceType.SRGB, at);
}
double len = Math.abs(w * cos) + Math.abs(h * sin), cx = b.getCenterX(), cy = b.getCenterY();
return new java.awt.LinearGradientPaint(new java.awt.geom.Point2D.Double(cx - cos * len / 2, cy - sin * len / 2),
new java.awt.geom.Point2D.Double(cx + cos * len / 2, cy + sin * len / 2), stops, colours);
}
double fx = b.getX() + w * (focus[0] + (1 - focus[0] - focus[2]) / 2), fy = b.getY() + h * (focus[1] + (1 - focus[1] - focus[3]) / 2);
double r = 0;
for (double[] c : new double[][] { { b.getMinX(), b.getMinY() }, { b.getMaxX(), b.getMinY() }, { b.getMinX(), b.getMaxY() },
{ b.getMaxX(), b.getMaxY() } }) {
r = Math.max(r, Math.hypot(c[0] - fx, c[1] - fy));
}
return new java.awt.RadialGradientPaint(new java.awt.geom.Point2D.Double(fx, fy), (float) Math.max(r, 1e-3), stops, colours);
}
}
/**
* A DrawingML preset pattern ({@code a:pattFill}): an 8 by 8 tile of the foreground over the
* background, a pixel 0.75pt (96 dpi), as Office draws it (Word's PDF: tiled pictures, r15-patterns)
*/
public static final class Pattern {
private final boolean[] on;
private final Color fg, bg;
/** @param on the tile's 64 pixels, row by row, true where the foreground is */
public Pattern(boolean[] on, Color fg, Color bg) {
this.on = on;
this.fg = fg;
this.bg = bg;
}
/** The tile's 64 pixels, row by row: true where the foreground is */
public boolean[] getTile() {
return on;
}
/** The foreground */
public Color getForeground() {
return fg;
}
/** The background, or null for none */
public Color getBackground() {
return bg;
}
/** The pattern as a paint */
public java.awt.Paint paint() {
java.awt.image.BufferedImage tile = new java.awt.image.BufferedImage(8, 8, java.awt.image.BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
Color c = on[y * 8 + x] ? fg : bg;
if (c != null) tile.setRGB(x, y, c.getRGB());
}
}
return new java.awt.TexturePaint(tile, new Rectangle2D.Double(0, 0, 6, 6));
}
/** The preset's tile: the common presets by their rows, columns and diagonals; pctN by an ordered dither; others half on */
public static boolean[] preset(String prst) {
boolean[] on = new boolean[64];
int[] bayer = { 0, 32, 8, 40, 2, 34, 10, 42, 48, 16, 56, 24, 50, 18, 58, 26, 12, 44, 4, 36, 14, 46, 6, 38, 60, 28, 52, 20, 62, 30, 54, 22, 3,
35, 11, 43, 1, 33, 9, 41, 51, 19, 59, 27, 49, 17, 57, 25, 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23, 61, 29, 53, 21 };
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
int d = (x - y + 8) % 8, u = (x + y) % 8;
boolean v;
switch (prst) {
case "horz": v = y == 0; break;
case "vert": v = x == 0; break;
case "ltHorz": v = y % 4 == 0; break;
case "ltVert": v = x % 4 == 0; break;
case "dkHorz": v = y % 4 < 2; break;
case "dkVert": v = x % 4 < 2; break;
case "narHorz": v = y % 2 == 0; break;
case "narVert": v = x % 2 == 0; break;
case "dashHorz": v = y == 0 && x < 4 || y == 4 && x >= 4; break;
case "dashVert": v = x == 0 && y < 4 || x == 4 && y >= 4; break;
case "cross": case "lgGrid": v = x == 0 || y == 0; break;
case "smGrid": v = x % 4 == 0 || y % 4 == 0; break;
case "dotGrid": v = (x == 0 && y % 2 == 0) || (y == 0 && x % 2 == 0); break;
case "dnDiag": v = d == 0; break;
case "upDiag": v = u == 7; break;
case "ltDnDiag": v = d % 4 == 0; break;
case "ltUpDiag": v = u % 4 == 3; break;
case "dkDnDiag": v = d % 4 < 2; break;
case "dkUpDiag": v = u % 4 >= 2; break;
case "wdDnDiag": v = d < 3; break;
case "wdUpDiag": v = u >= 5; break;
case "dashDnDiag": v = d % 4 == 0 && y % 4 < 2; break;
case "dashUpDiag": v = u % 4 == 3 && y % 4 < 2; break;
case "diagCross": v = d == 0 || u == 7; break;
case "smCheck": v = (x / 2 + y / 2) % 2 == 0; break;
case "lgCheck": v = (x / 4 + y / 4) % 2 == 0; break;
default:
int pct = prst.startsWith("pct") ? Integer.parseInt(prst.substring(3)) : 50;
v = bayer[y * 8 + x] < Math.round(pct * 64 / 100.0);
}
on[y * 8 + x] = v;
}
}
return on;
}
}
/**
* A shape's outer shadow or glow ({@code a:outerShdw}, {@code a:glow}), drawn as Office draws
* them in a PDF, a picture under the shape (CR-037 finding 6): the shape, moved by the shadow's
* distance along its direction, scaled and skewed about its alignment point, or (a glow) grown
* by its radius, filled in the colour and blurred
*/
public static final class Shadow {
Color colour;
/** the blur's radius, the distance and direction (degrees clockwise from the x axis), in points */
double blur, dist, dir;
double sx = 1, sy = 1, kx, ky;
/** the alignment point's horizontal and vertical place in the shape's box, 0 to 1 */
double ax = 0.5, ay = 0.5;
/** a glow: its radius, in points; 0 for a shadow */
double glow;
/**
* A glow's spread beyond what is drawn, and its blur's sigma, shares of its radius (r10-column-style-213
* against Excel's picture: 0.15% of pixels off, mean 0.6 of 255; one style)
*/
public static final double GLOW_SPREAD = 0.5, GLOW_BLUR = 0.25;
private Shadow() {
}
/**
* An outer shadow ({@code a:outerShdw}), in points and degrees
*
* @param dir its direction, degrees clockwise from the x axis
* @param sx sy kx ky its scale and skew (degrees)
* @param ax ay its alignment point's place in the shape's box, 0 to 1
*/
public static Shadow outer(Color colour, double blur, double dist, double dir, double sx, double sy, double kx, double ky, double ax,
double ay) {
Shadow s = new Shadow();
s.colour = colour;
s.blur = blur;
s.dist = dist;
s.dir = dir;
s.sx = sx;
s.sy = sy;
s.kx = kx;
s.ky = ky;
s.ax = ax;
s.ay = ay;
return s;
}
/** A glow ({@code a:glow}) of a radius in points */
public static Shadow glow(Color colour, double radius) {
Shadow s = new Shadow();
s.colour = colour;
s.glow = radius;
return s;
}
public Color getColour() {
return colour;
}
/** The blur's radius, in points */
public double getBlur() {
return blur;
}
/** The distance, in points */
public double getDistance() {
return dist;
}
/** The direction, degrees clockwise from the x axis */
public double getDirection() {
return dir;
}
/** A glow's radius, in points; 0 for a shadow */
public double getGlow() {
return glow;
}
/** the shadow's (or glow's) shape: a glow around what is drawn, the outline alone where the shape isn't filled */
public Shape shape(Shape s, boolean filled, double lineWidth) {
if (glow > 0) {
java.awt.geom.Area a = new java.awt.geom.Area(new BasicStroke((float) (lineWidth + 2 * GLOW_SPREAD * glow), BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND).createStrokedShape(s));
if (filled) a.add(new java.awt.geom.Area(s));
return a;
}
Rectangle2D b = s.getBounds2D();
double px = b.getX() + ax * b.getWidth(), py = b.getY() + ay * b.getHeight();
AffineTransform t = new AffineTransform();
t.translate(dist * Math.cos(Math.toRadians(dir)), dist * Math.sin(Math.toRadians(dir)));
t.translate(px, py);
t.shear(Math.tan(Math.toRadians(kx)), Math.tan(Math.toRadians(ky)));
t.scale(sx, sy);
t.translate(-px, -py);
return t.createTransformedShape(s);
}
/** Drawn under the shape: a picture at the drawing's own scale (at least 2 pixels a point) */
public void paint(Graphics2D g, Shape s, boolean filled, double lineWidth) {
Shape ss = shape(s, filled, lineWidth);
double sigma = Math.max(0.01, glow > 0 ? GLOW_BLUR * glow : blur / 2);
double scale = Math.max(2, Math.abs(g.getTransform().getScaleX()));
Rectangle2D b = ss.getBounds2D();
double pad = 3 * sigma + 1;
Rectangle2D area = new Rectangle2D.Double(b.getX() - pad, b.getY() - pad, b.getWidth() + 2 * pad, b.getHeight() + 2 * pad);
int w = (int) Math.ceil(area.getWidth() * scale), h = (int) Math.ceil(area.getHeight() * scale);
if (w <= 0 || h <= 0 || (long) w * h > 16_000_000L) return;
java.awt.image.BufferedImage im = new java.awt.image.BufferedImage(w, h, java.awt.image.BufferedImage.TYPE_INT_ARGB);
Graphics2D ig = im.createGraphics();
ig.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
ig.scale(scale, scale);
ig.translate(-area.getX(), -area.getY());
ig.setColor(Color.BLACK);
ig.fill(ss);
ig.dispose();
// the alpha blurred (Gaussian, separable), then the colour at its alpha
int[] px = im.getRGB(0, 0, w, h, null, 0, w);
float[] a = new float[px.length];
for (int i = 0; i < px.length; i++) a[i] = (px[i] >>> 24) / 255f;
a = blur(a, w, h, sigma * scale);
int rgb = colour.getRGB() & 0xFFFFFF;
double alpha = colour.getAlpha() / 255.0;
for (int i = 0; i < px.length; i++) px[i] = ((int) Math.round(Math.min(1, a[i]) * alpha * 255) << 24) | rgb;
im.setRGB(0, 0, w, h, px, 0, w);
g.drawImage(im, new AffineTransform(1 / scale, 0, 0, 1 / scale, area.getX(), area.getY()), null);
}
private static float[] blur(float[] a, int w, int h, double sigma) {
int r = (int) Math.ceil(3 * sigma);
if (r < 1) return a;
float[] k = new float[2 * r + 1];
float sum = 0;
for (int i = -r; i <= r; i++) sum += k[i + r] = (float) Math.exp(-i * i / (2 * sigma * sigma));
for (int i = 0; i < k.length; i++) k[i] /= sum;
float[] t = new float[a.length], o = new float[a.length];
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
float v = 0;
for (int i = -r; i <= r; i++) {
int xx = x + i;
if (xx >= 0 && xx < w) v += k[i + r] * a[y * w + xx];
}
t[y * w + x] = v;
}
}
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
float v = 0;
for (int i = -r; i <= r; i++) {
int yy = y + i;
if (yy >= 0 && yy < h) v += k[i + r] * t[yy * w + x];
}
o[y * w + x] = v;
}
}
return o;
}
}
/** A filled or stroked shape: a bar, a gridline, the chart area, a legend key */
public static final class Area {
private final Shape shape;
private final Color fill;
private final Color line;
private final double lineWidth;
private final String role;
/** what it is drawn within (a bar, the plot's inside: Office clips there), or null */
private final Shape clip;
/** its line's ends and joins rounded (a line series'), else butt and mitred */
private final boolean round;
/** its fill a gradient ({@link #fill} its first colour), or null */
private Gradient gradient;
/** its line a gradient ({@link #line} its first colour), or null */
private Gradient lineGradient;
/** its fill a pattern ({@link #fill} its foreground), or null */
private Pattern pattern;
/** its shadows and glow, drawn under it */
private List<Shadow> shadows;
/** its line's dashes, in points, or null for a solid line */
private float[] dash;
public Area(Shape shape, Color fill, Color line, double lineWidth, String role) {
this(shape, fill, line, lineWidth, role, null, false);
}
public Area(Shape shape, Color fill, Color line, double lineWidth, String role, Shape clip) {
this(shape, fill, line, lineWidth, role, clip, false);
}
public Area(Shape shape, Color fill, Color line, double lineWidth, String role, Shape clip, boolean round) {
this.shape = shape;
this.fill = fill;
this.line = line;
this.lineWidth = lineWidth;
this.role = role;
this.clip = clip;
this.round = round;
}
public Shape getShape() {
return shape;
}
/** Its solid fill (a gradient's or pattern's first colour), or null */
public Color getFill() {
return fill;
}
/** Its line's colour, or null for none */
public Color getLine() {
return line;
}
/** Its line's width, in points */
public double getLineWidth() {
return lineWidth;
}
/** What it is, as Office's object model names it: plotArea, point.S.P, legend.key.N, ... */
public String getRole() {
return role;
}
/** What it is drawn within, or null */
public Shape getClip() {
return clip;
}
/** Its line's ends and joins rounded (a line series'), else butt and mitred */
public boolean isRound() {
return round;
}
public Gradient getGradient() {
return gradient;
}
public void setGradient(Gradient gradient) {
this.gradient = gradient;
}
public Gradient getLineGradient() {
return lineGradient;
}
public void setLineGradient(Gradient lineGradient) {
this.lineGradient = lineGradient;
}
public Pattern getPattern() {
return pattern;
}
public void setPattern(Pattern pattern) {
this.pattern = pattern;
}
/** Its shadows and glow, drawn under it, or null */
public List<Shadow> getShadows() {
return shadows;
}
public void setShadows(List<Shadow> shadows) {
this.shadows = shadows;
}
/** Its line's dashes, in points, or null for a solid line */
public float[] getDash() {
return dash;
}
public void setDash(float[] dash) {
this.dash = dash;
}
}
/** A line of text, from its baseline's start, turned by angle degrees (clockwise) about it */
public static final class Text {
private final String text;
/** the face the chart names (Calibri), where {@link #font} is the file it is drawn in (Carlito) */
private final String face;
private final Font font;
private final Color colour;
private final double x;
private final double baseline;
private final double width;
private final double angle;
private final String role;
/** the space after each character (DrawingML's spc), in points */
private final double spacing;
public Text(String text, String face, Font font, Color colour, double x, double baseline, double width, double angle, String role) {
this(text, face, font, colour, x, baseline, width, angle, role, 0);
}
public Text(String text, String face, Font font, Color colour, double x, double baseline, double width, double angle, String role, double spacing) {
this.spacing = spacing;
this.text = text;
this.face = face;
this.font = font;
this.colour = colour;
this.x = x;
this.baseline = baseline;
this.width = width;
this.angle = angle;
this.role = role;
}
/** The text, as shown (in capitals where its style says) */
public String getText() {
return text;
}
/** The face the chart names (Calibri), where {@link #getFont()} is the file it is drawn in (Carlito) */
public String getFace() {
return face;
}
public Font getFont() {
return font;
}
public Color getColour() {
return colour;
}
/** Its baseline's start */
public double getX() {
return x;
}
public double getBaseline() {
return baseline;
}
/** Its width, to its last glyph */
public double getWidth() {
return width;
}
/** Turned by this many degrees, clockwise, about its baseline's start */
public double getAngle() {
return angle;
}
/** What it is, as Office's object model names it: title, legend.text.N, ... */
public String getRole() {
return role;
}
/** The space after each character (DrawingML's spc), in points */
public double getSpacing() {
return spacing;
}
}
private final double width;
private final double height;
private final List<Object> items = new ArrayList<>();
/** The boxes Office reports, by name: title, legend, legend.entry.N, legend.key.N, plotArea, inside, point.S.P */
private final Map<String, Rectangle2D> boxes = new LinkedHashMap<>();
/**
* A pie's or doughnut's slices, by point (point.S.P), at the places Office reports
* ({@code PieSliceLocation}, 1 to 9: the end's outer point, the arc's middle, the start's outer
* point, the start edge's middle, the centre, the end edge's middle, then a doughnut's inner
* start, inner arc's middle and inner end); null where a pie has none
*/
private final Map<String, double[][]> slices = new LinkedHashMap<>();
/** The value axis as laid out: min, max, major unit */
private double[] valueAxis;
/** A scatter chart's x axis as laid out: min, max, major unit; a date axis's first and last dates and major unit */
private double[] xAxis;
/** A drawing of width by height points, empty */
public Drawing(double width, double height) {
this.width = width;
this.height = height;
}
/** Adds a shape, painted after those before it */
public void add(Area a) {
items.add(a);
}
/** Adds a text, painted after what is before it */
public void add(Text t) {
items.add(t);
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
/** What is painted, {@link Area}s and {@link Text}s in painting order (the list itself) */
public List<Object> getItems() {
return items;
}
/** The boxes Office reports, by name (the map itself): title, legend, legend.entry.N, legend.key.N, plotArea, inside, point.S.P */
public Map<String, Rectangle2D> getBoxes() {
return boxes;
}
/** A pie's or doughnut's slices, by point, at Office's nine places (the map itself; see the field's note) */
public Map<String, double[][]> getSlices() {
return slices;
}
/** The value axis as laid out: min, max, major unit; null where there is none */
public double[] getValueAxis() {
return valueAxis;
}
public void setValueAxis(double[] valueAxis) {
this.valueAxis = valueAxis;
}
/** A scatter chart's x axis as laid out, a date axis's first and last dates and major unit; null where there is none */
public double[] getXAxis() {
return xAxis;
}
public void setXAxis(double[] xAxis) {
this.xAxis = xAxis;
}
/** A line across or down (a gridline, an axis) */
private static boolean level(Shape s) {
if (!(s instanceof java.awt.geom.Line2D)) return false;
java.awt.geom.Line2D l = (java.awt.geom.Line2D) s;
return l.getX1() == l.getX2() || l.getY1() == l.getY2();
}
/** Paints the items in order */
public void paint(Graphics2D g) {
paint(g, false);
}
/**
* Paints the items in order; for a picture (raster), with a rectangle's edges on whole pixels,
* as Excel's pictures have them (a bar's edge is its colour or the background, not a blend)
*/
public void paint(Graphics2D g, boolean raster) {
for (Object o : items) {
if (o instanceof Area) {
Area a = (Area) o;
Shape saved = g.getClip();
Object aa = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
boolean crisp = raster && (a.shape instanceof Rectangle2D || level(a.shape));
if (crisp) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
if (a.clip != null) g.clip(a.clip);
if (a.shadows != null) {
for (Shadow sh : a.shadows) sh.paint(g, a.shape, a.fill != null || a.gradient != null || a.pattern != null, a.line == null ? 0 : a.lineWidth);
}
if (a.gradient != null) {
g.setPaint(a.gradient.paint(a.shape.getBounds2D()));
g.fill(a.shape);
} else if (a.pattern != null) {
g.setPaint(a.pattern.paint());
g.fill(a.shape);
} else if (a.fill != null) {
g.setColor(a.fill);
g.fill(a.shape);
}
if (a.line != null && a.lineWidth > 0) {
if (a.lineGradient != null) {
java.awt.Stroke st = new BasicStroke((float) a.lineWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
g.setPaint(a.lineGradient.paint(st.createStrokedShape(a.shape).getBounds2D()));
} else {
g.setColor(a.line);
}
g.setStroke(a.dash != null
? new BasicStroke((float) a.lineWidth, a.round ? BasicStroke.CAP_ROUND : BasicStroke.CAP_BUTT,
a.round ? BasicStroke.JOIN_ROUND : BasicStroke.JOIN_MITER, 10f, a.dash, 0f)
: a.round ? new BasicStroke((float) a.lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)
: new BasicStroke((float) a.lineWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
g.draw(a.shape);
}
if (a.clip != null) g.setClip(saved);
if (crisp) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, aa);
} else {
Text t = (Text) o;
g.setColor(t.colour);
g.setFont(t.font);
if (t.angle == 0) {
drawString(g, t, raster);
} else {
AffineTransform saved = g.getTransform();
g.rotate(Math.toRadians(t.angle), t.x, t.baseline);
drawString(g, t, raster);
g.setTransform(saved);
}
}
}
}
/**
* A text drawn: kerned, for anything but a picture, as runs split at each kerned pair, each
* from where the kerned layout puts its first glyph. An SVG's text carries no kerning, so
* FOP and a browser draw a {@code <text>} unkerned, a kerned title 1.1pt wider than Office's
* ("Y-Values" at 14pt, CR-037 phase 3); as runs, each is drawn at its own advances (the
* mapped font's, the same file) from its kerned place. A picture is drawn by AWT, kerned.
*/
private static void drawString(Graphics2D g, Text t, boolean raster) {
float x = (float) t.x, y = (float) t.baseline;
if (t.spacing != 0 && t.text.length() > 1) {
// letter-spaced: each character from its kerned place and the spacing before it
char[] cs = t.text.toCharArray();
java.awt.font.GlyphVector gv = t.font.layoutGlyphVector(g.getFontRenderContext(), cs, 0, cs.length, java.awt.Font.LAYOUT_LEFT_TO_RIGHT);
if (gv.getNumGlyphs() == cs.length) {
for (int i = 0; i < cs.length; i++) {
if (cs[i] == ' ') continue;
g.drawString(String.valueOf(cs[i]), x + (float) (gv.getGlyphPosition(i).getX() + i * t.spacing), y);
}
return;
}
}
if (raster || !java.awt.font.TextAttribute.KERNING_ON.equals(t.font.getAttributes().get(java.awt.font.TextAttribute.KERNING))
|| t.text.length() < 2) {
g.drawString(t.text, x, y);
return;
}
char[] cs = t.text.toCharArray();
java.awt.font.GlyphVector gv = t.font.layoutGlyphVector(g.getFontRenderContext(), cs, 0, cs.length,
java.awt.Font.LAYOUT_LEFT_TO_RIGHT);
if (gv.getNumGlyphs() != cs.length) {
g.drawString(t.text, x, y);
return;
}
int start = 0;
for (int i = 1; i <= cs.length; i++) {
boolean kerned = i < cs.length && Math.abs(gv.getGlyphPosition(i).getX()
- gv.getGlyphPosition(i - 1).getX() - gv.getGlyphMetrics(i - 1).getAdvanceX()) > 1e-4;
if (i == cs.length || kerned) {
g.drawString(new String(cs, start, i - start), x + (float) gv.getGlyphPosition(start).getX(), y);
start = i;
}
}
}
}
@@ -0,0 +1,183 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.chart.render.api;
import java.awt.Color;
import java.awt.Shape;
import java.util.ArrayList;
import java.util.List;
import org.docx4j.dml.CTLineProperties;
import org.docx4j.dml.CTShapeProperties;
import org.docx4j.model.color.DrawingMLColors;
import org.docx4j.model.color.ResolvedColor;
import org.docx4j.model.color.ThemeColors;
/**
* A DrawingML shape's properties ({@code a:spPr}: a classic chart's {@code c:spPr}, a chartex's
* {@code cx:spPr}) as a {@link Drawing}'s: its solid fill, gradient (any number of stops, linear
* or along a path) or pattern (Office's 8 by 8 tiles), its line and dashes, its outer shadow and
* glow, each colour resolved through the theme as Office resolves it (CR-034).
*
* @since 17.3.3 (CR-039: from docx4j-chart-render's internals, CR-037)
*/
public final class Fills {
private final ThemeColors theme;
/** @param theme the colours a shape's scheme colours resolve through: the chart's (its own override and map applied) */
public Fills(ThemeColors theme) {
this.theme = theme;
}
/** A resolved DrawingML colour as AWT's, its alpha kept; null for none */
public static Color awt(ResolvedColor c) {
if (c == null) return null;
return new Color(c.getRed(), c.getGreen(), c.getBlue(), (int) Math.round(255.0 * c.getAlpha() / ResolvedColor.OPAQUE));
}
/** A shape's fill: solid only (phases 1 and 2); null for none */
public Color fill(CTShapeProperties sp) {
if (sp == null || sp.getNoFill() != null) return null;
if (sp.getSolidFill() != null) return awt(DrawingMLColors.resolve(sp.getSolidFill(), theme));
return null;
}
/** A shape's gradient fill (a:gradFill), its stops resolved through the theme; null for none */
public Drawing.Gradient gradient(CTShapeProperties sp) {
return sp == null ? null : gradient(sp.getGradFill());
}
/** A gradient fill (a:gradFill, a line's too), its stops resolved through the theme; null for none */
public Drawing.Gradient gradient(org.docx4j.dml.CTGradientFillProperties g) {
if (g == null || g.getGsLst() == null) return null;
List<org.docx4j.dml.CTGradientStop> gs = new ArrayList<>(g.getGsLst().getGs());
if (gs.isEmpty()) return null;
gs.sort((a, b) -> Integer.compare(a.getPos(), b.getPos()));
float[] stops = new float[gs.size()];
Color[] colours = new Color[gs.size()];
for (int i = 0; i < gs.size(); i++) {
org.docx4j.dml.CTGradientStop st = gs.get(i);
Object c = st.getSchemeClr() != null ? st.getSchemeClr() : st.getSrgbClr() != null ? st.getSrgbClr()
: st.getPrstClr() != null ? st.getPrstClr() : st.getSysClr() != null ? st.getSysClr()
: st.getHslClr() != null ? st.getHslClr() : st.getScrgbClr();
colours[i] = awt(DrawingMLColors.resolve(c, theme));
if (colours[i] == null) colours[i] = Color.GRAY;
// strictly increasing, as AWT's gradients need
float f = (float) Math.max(0, Math.min(1, st.getPos() / 100000.0));
stops[i] = i > 0 && f <= stops[i - 1] ? Math.min(1f, stops[i - 1] + 1e-5f) : f;
}
if (stops.length > 1 && stops[stops.length - 1] <= stops[stops.length - 2]) {
// stops crowded at the end: as they came, spread a little below it
for (int i = stops.length - 2; i >= 0 && stops[i] >= stops[i + 1]; i--) stops[i] = stops[i + 1] - 1e-5f;
}
if (g.getPath() != null) {
org.docx4j.dml.CTRelativeRect r = g.getPath().getFillToRect();
double[] focus = r == null ? new double[] { 0.5, 0.5, 0.5, 0.5 }
: new double[] { r.getL() / 100000.0, r.getT() / 100000.0, r.getR() / 100000.0, r.getB() / 100000.0 };
return new Drawing.Gradient(stops, colours, false, 0, false, focus);
}
double angle = g.getLin() != null && g.getLin().getAng() != null ? g.getLin().getAng() / 60000.0 : 0;
boolean scaled = g.getLin() != null && Boolean.TRUE.equals(g.getLin().isScaled());
return new Drawing.Gradient(stops, colours, true, angle, scaled, null);
}
/** A shape's outer shadow and glow (a:effectLst), or null for none */
public List<Drawing.Shadow> shadows(CTShapeProperties sp) {
if (sp == null || sp.getEffectLst() == null) return null;
List<Drawing.Shadow> out = new ArrayList<>();
org.docx4j.dml.CTGlowEffect gl = sp.getEffectLst().getGlow();
if (gl != null) {
Object c = gl.getSchemeClr() != null ? gl.getSchemeClr() : gl.getSrgbClr() != null ? gl.getSrgbClr() : gl.getPrstClr() != null ? gl.getPrstClr()
: gl.getSysClr() != null ? gl.getSysClr() : gl.getHslClr() != null ? gl.getHslClr() : gl.getScrgbClr();
Drawing.Shadow g = Drawing.Shadow.glow(awt(DrawingMLColors.resolve(c, theme)), gl.getRad() / 12700.0);
if (g.getColour() != null && g.getGlow() > 0) out.add(g);
}
org.docx4j.dml.CTOuterShadowEffect os = sp.getEffectLst().getOuterShdw();
if (os != null) {
Object c = os.getSchemeClr() != null ? os.getSchemeClr() : os.getSrgbClr() != null ? os.getSrgbClr() : os.getPrstClr() != null ? os.getPrstClr()
: os.getSysClr() != null ? os.getSysClr() : os.getHslClr() != null ? os.getHslClr() : os.getScrgbClr();
String al = os.getAlgn() == null ? "b" : os.getAlgn().value();
Drawing.Shadow sh = Drawing.Shadow.outer(awt(DrawingMLColors.resolve(c, theme)), os.getBlurRad() / 12700.0, os.getDist() / 12700.0,
os.getDir() / 60000.0, os.getSx() / 100000.0, os.getSy() / 100000.0, os.getKx() / 60000.0, os.getKy() / 60000.0,
al.endsWith("l") ? 0 : al.endsWith("r") ? 1 : 0.5, al.startsWith("t") ? 0 : al.startsWith("b") ? 1 : 0.5);
if (sh.getColour() != null) out.add(sh);
}
return out.isEmpty() ? null : out;
}
/** A shape's pattern fill (a:pattFill), its colours resolved through the theme; null for none */
public Drawing.Pattern pattern(CTShapeProperties sp) {
if (sp == null || sp.getPattFill() == null) return null;
org.docx4j.dml.CTPatternFillProperties pf = sp.getPattFill();
Color fg = pf.getFgClr() == null ? Color.BLACK : awt(DrawingMLColors.resolve(pf.getFgClr(), theme));
Color bg = pf.getBgClr() == null ? Color.WHITE : awt(DrawingMLColors.resolve(pf.getBgClr(), theme));
String prst = pf.getPrst() == null ? "pct5" : pf.getPrst().value();
return new Drawing.Pattern(Drawing.Pattern.preset(prst), fg == null ? Color.BLACK : fg, bg);
}
/** An area filled by a shape's properties: its solid fill, gradient or pattern, and its line */
public Drawing.Area area(Shape shape, CTShapeProperties sp, Color fill, String role, Shape clip) {
Drawing.Gradient gr = gradient(sp);
Drawing.Pattern pt = gr == null ? pattern(sp) : null;
Drawing.Area a = new Drawing.Area(shape, gr != null ? gr.getColours()[0] : pt != null ? pt.getForeground() : fill, lineColour(sp), lineWidth(sp),
role, clip);
a.setGradient(gr);
a.setPattern(pt);
a.setShadows(shadows(sp));
a.setDash(dashes(sp, a.getLineWidth()));
return a;
}
/** A shape's line's colour (solid only); null for none */
public Color lineColour(CTShapeProperties sp) {
CTLineProperties ln = sp == null ? null : sp.getLn();
if (ln == null || ln.getNoFill() != null || ln.getSolidFill() == null) return null;
return awt(DrawingMLColors.resolve(ln.getSolidFill(), theme));
}
/** A shape's line's width in points: 0.75 where it says none */
public static double lineWidth(CTShapeProperties sp) {
CTLineProperties ln = sp == null ? null : sp.getLn();
return ln == null || ln.getW() == null ? 0.75 : ln.getW() / 12700.0;
}
/**
* A line's dashes (a:prstDash), in points: DrawingML's presets in multiples of the line's
* width (Office's: dash 4 3, sysDash 3 1, ...); null for a solid line
*/
public static float[] dashes(CTShapeProperties sp, double width) {
if (sp == null || sp.getLn() == null || sp.getLn().getPrstDash() == null || sp.getLn().getPrstDash().getVal() == null) return null;
float[] u;
switch (sp.getLn().getPrstDash().getVal().value()) {
case "dot": u = new float[] { 1, 3 }; break;
case "dash": u = new float[] { 4, 3 }; break;
case "lgDash": u = new float[] { 8, 3 }; break;
case "dashDot": u = new float[] { 4, 3, 1, 3 }; break;
case "lgDashDot": u = new float[] { 8, 3, 1, 3 }; break;
case "lgDashDotDot": u = new float[] { 8, 3, 1, 3, 1, 3 }; break;
case "sysDash": u = new float[] { 3, 1 }; break;
case "sysDot": u = new float[] { 1, 1 }; break;
case "sysDashDot": u = new float[] { 3, 1, 1, 1 }; break;
case "sysDashDotDot": u = new float[] { 3, 1, 1, 1, 1, 1 }; break;
default: return null;
}
for (int i = 0; i < u.length; i++) u[i] *= (float) Math.max(width, 0.1);
return u;
}
}
@@ -0,0 +1,94 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.chart.render.api;
import java.awt.Color;
import java.awt.LinearGradientPaint;
import java.awt.MultipleGradientPaint;
import java.awt.Paint;
import java.awt.RadialGradientPaint;
import java.awt.geom.AffineTransform;
import java.util.Locale;
import org.apache.batik.svggen.DefaultExtensionHandler;
import org.apache.batik.svggen.SVGGeneratorContext;
import org.apache.batik.svggen.SVGPaintDescriptor;
import org.w3c.dom.Element;
/**
* Batik's SVG generator writes a two-stop {@code GradientPaint} only; this writes the chart's
* gradients (DrawingML's, any number of stops, linear or radial: {@link Drawing.Gradient}) as SVG
* {@code linearGradient} and {@code radialGradient} definitions, in user space, which FOP and
* browsers draw.
*/
final class GradientHandler extends DefaultExtensionHandler {
private static final String SVG_NS = "http://www.w3.org/2000/svg";
@Override
public SVGPaintDescriptor handlePaint(Paint paint, SVGGeneratorContext ctx) {
if (!(paint instanceof MultipleGradientPaint)) return null;
MultipleGradientPaint p = (MultipleGradientPaint) paint;
Element e;
String id;
if (p instanceof LinearGradientPaint) {
LinearGradientPaint l = (LinearGradientPaint) p;
id = ctx.getIDGenerator().generateID("linearGradient");
e = ctx.getDOMFactory().createElementNS(SVG_NS, "linearGradient");
e.setAttributeNS(null, "x1", n(l.getStartPoint().getX()));
e.setAttributeNS(null, "y1", n(l.getStartPoint().getY()));
e.setAttributeNS(null, "x2", n(l.getEndPoint().getX()));
e.setAttributeNS(null, "y2", n(l.getEndPoint().getY()));
} else if (p instanceof RadialGradientPaint) {
RadialGradientPaint r = (RadialGradientPaint) p;
id = ctx.getIDGenerator().generateID("radialGradient");
e = ctx.getDOMFactory().createElementNS(SVG_NS, "radialGradient");
e.setAttributeNS(null, "cx", n(r.getCenterPoint().getX()));
e.setAttributeNS(null, "cy", n(r.getCenterPoint().getY()));
e.setAttributeNS(null, "r", n(r.getRadius()));
e.setAttributeNS(null, "fx", n(r.getFocusPoint().getX()));
e.setAttributeNS(null, "fy", n(r.getFocusPoint().getY()));
} else {
return null;
}
e.setAttributeNS(null, "id", id);
e.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
AffineTransform t = p.getTransform();
if (t != null && !t.isIdentity()) {
e.setAttributeNS(null, "gradientTransform", "matrix(" + n(t.getScaleX()) + " " + n(t.getShearY()) + " " + n(t.getShearX()) + " "
+ n(t.getScaleY()) + " " + n(t.getTranslateX()) + " " + n(t.getTranslateY()) + ")");
}
float[] f = p.getFractions();
Color[] c = p.getColors();
for (int i = 0; i < f.length; i++) {
Element stop = ctx.getDOMFactory().createElementNS(SVG_NS, "stop");
stop.setAttributeNS(null, "offset", n(f[i]));
stop.setAttributeNS(null, "stop-color", String.format(Locale.ROOT, "#%02x%02x%02x", c[i].getRed(), c[i].getGreen(), c[i].getBlue()));
if (c[i].getAlpha() < 255) stop.setAttributeNS(null, "stop-opacity", n(c[i].getAlpha() / 255.0));
e.appendChild(stop);
}
return new SVGPaintDescriptor("url(#" + id + ")", "1", e);
}
/** at most four decimals, no trailing zeros */
private static String n(double v) {
String s = String.format(Locale.ROOT, "%.4f", v);
while (s.contains(".") && (s.endsWith("0") || s.endsWith("."))) s = s.substring(0, s.length() - 1);
return s.equals("-0") ? "0" : s;
}
}
@@ -0,0 +1,105 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.chart.render.api;
import java.awt.Dimension;
import java.awt.RenderingHints;
import java.util.Locale;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGeneratorContext;
import org.apache.batik.svggen.SVGGraphics2D;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* A {@link Drawing} as an SVG document, as docx4j's outputs want a chart's: one user unit a
* point, the frame filled exactly; its text as text under the families docx4j's font mapping gives
* FOP (CR-037 D6), or as outlines on {@link #TEXT_AS_SHAPES}; DrawingML's gradients (any number of
* stops, linear or radial) as SVG gradients, which Batik's generator alone doesn't write; shadows,
* glows and patterns' tiles as PNG pictures.
*
* @since 17.3.3 (CR-039: from docx4j-chart-render's internals, CR-037)
*/
public final class SvgWriter {
private static final String SVG_NS = "http://www.w3.org/2000/svg";
/**
* The property which, set true, writes a chart's text in its SVG as glyph outlines rather
* than {@code <text>} (CR-037 D6): drawn alike whatever fonts the reader of the SVG has, but
* no longer text in a PDF (not searchable, not selectable) and larger. False by default.
*/
public static final String TEXT_AS_SHAPES = "docx4j.chart.render.textAsShapes";
private SvgWriter() {
}
/** The drawing as SVG, its width by height points */
public static Document toSvg(Drawing drawing) {
double width = drawing.getWidth(), height = drawing.getHeight();
DOMImplementation impl = GenericDOMImplementation.getDOMImplementation();
Document doc = impl.createDocument(SVG_NS, "svg", null);
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(doc);
ctx.setComment(null);
ctx.setPrecision(4);
// DrawingML's gradients: any number of stops, linear or radial
ctx.setExtensionHandler(new GradientHandler());
// pictures (shadows, glows, a pattern's tile) as PNG data, by the JDK's own writer (Batik's
// default needs batik-codec)
ctx.setImageHandler(new org.apache.batik.svggen.ImageHandlerBase64Encoder() {
@Override
public void encodeImage(java.awt.image.RenderedImage image, java.io.OutputStream os)
throws org.apache.batik.svggen.SVGGraphics2DIOException {
try {
javax.imageio.ImageIO.write(image, "png", os);
} catch (java.io.IOException e) {
throw new org.apache.batik.svggen.SVGGraphics2DIOException(e);
}
}
});
// text as text, under the families docx4j's mapping gives FOP; outlines on the
// property (D6), as for a metafile's
SVGGraphics2D g = new SVGGraphics2D(ctx, org.docx4j.Docx4jProperties.getProperty(TEXT_AS_SHAPES, false));
g.setSVGCanvasSize(new Dimension((int) Math.max(1, Math.ceil(width)), (int) Math.max(1, Math.ceil(height))));
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
drawing.paint(g, false);
Element root = doc.getDocumentElement();
g.getRoot(root);
// one user unit a point, the frame filled exactly (as BatikMetafileSvgProvider's)
root.setAttributeNS(null, "width", length(width) + "pt");
root.setAttributeNS(null, "height", length(height) + "pt");
root.setAttributeNS(null, "viewBox", "0 0 " + length(width) + " " + length(height));
root.setAttributeNS(null, "preserveAspectRatio", "none");
// each text is placed and split at its kerned pairs already (Drawing): a browser
// kerns an SVG's text and makes ligatures by default, FOP doesn't, and neither should
root.setAttributeNS(null, "style", "font-kerning: none; font-variant-ligatures: none");
return doc;
}
/** at most four decimals, no trailing zeros */
private static String length(double v) {
String s = String.format(Locale.ROOT, "%.4f", v);
while (s.contains(".") && (s.endsWith("0") || s.endsWith("."))) s = s.substring(0, s.length() - 1);
return s;
}
}
@@ -0,0 +1,217 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.chart.render.api;
import java.awt.Color;
import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.util.Locale;
import org.docx4j.dml.CTTextBody;
import org.docx4j.dml.CTTextCharacterProperties;
import org.docx4j.dml.CTTextParagraph;
import org.docx4j.model.chart.ChartFonts;
import org.docx4j.model.color.DrawingMLColors;
import org.docx4j.model.color.ThemeColors;
/**
* A text style: a chart's c:txPr, inherited from the chart space's, else Office's default.
* Text at or above its kern size (DrawingML's {@code kern}, hundredths of a point; Office's
* charts write 1200) is kerned, as Office kerns it (R4's long title: its width is Carlito's
* kerned advances, to 0.01pt); an axis's labels never are (r14-kerning: sixteen pairs as 14pt
* category labels, kern 1200, none kerned).
*
* <p>A style measures text in the font docx4j's mapping gives its face ({@link ChartFonts}), as
* the chart is drawn in it; {@link #with(CTTextCharacterProperties, ThemeColors)} lays a
* DrawingML run's properties over it (a chartex's {@code cx:txPr} is the same {@code a:txPr}).</p>
*
* @since 17.3.3 (CR-039: from docx4j-chart-render's internals, CR-037)
*/
public final class TextStyle {
private static final FontRenderContext FRC = new FontRenderContext(null, true, true);
private final ChartFonts fonts;
private final String typeface;
private final double size;
private final boolean bold;
private final boolean italic;
private final Color colour;
private final int kern;
private final Font font;
private final double ascent, line;
/** the space after each character, in points (DrawingML's spc), and capitals (cap="all") */
private final double spc;
private final boolean caps;
public TextStyle(ChartFonts fonts, String typeface, double size, boolean bold, boolean italic, Color colour, int kern) {
this(fonts, typeface, size, bold, italic, colour, kern, 0, false);
}
/**
* @param typeface the face the chart names, or a theme's ({@code +mn-lt})
* @param kern DrawingML's {@code kern}: the size, in hundredths of a point, from which text is kerned (0: never)
* @param spc the space after each character, in points
* @param caps in capitals ({@code cap="all"})
*/
public TextStyle(ChartFonts fonts, String typeface, double size, boolean bold, boolean italic, Color colour, int kern, double spc, boolean caps) {
this.fonts = fonts;
this.spc = spc;
this.caps = caps;
this.typeface = typeface;
this.size = size;
this.bold = bold;
this.italic = italic;
this.colour = colour;
this.kern = kern;
Font f = fonts.font(typeface, bold, italic, size);
if (kern > 0 && size * 100 >= kern) {
f = f.deriveFont(java.util.Collections.singletonMap(java.awt.font.TextAttribute.KERNING,
java.awt.font.TextAttribute.KERNING_ON));
}
this.font = f;
LineMetrics lm = font.getLineMetrics("Xg", FRC);
this.ascent = lm.getAscent();
this.line = lm.getAscent() + lm.getDescent() + lm.getLeading();
}
/** The fonts the style was made with */
public ChartFonts getFonts() {
return fonts;
}
/** The face the chart names, or a theme's ({@code +mn-lt}) */
public String getTypeface() {
return typeface;
}
/** Its size, in points */
public double getSize() {
return size;
}
public boolean isBold() {
return bold;
}
public boolean isItalic() {
return italic;
}
public Color getColour() {
return colour;
}
/** DrawingML's {@code kern}: the size, in hundredths of a point, from which text is kerned (0: never) */
public int getKern() {
return kern;
}
/** The font it is measured and drawn in: the face docx4j's mapping gives it, kerned where it is */
public Font getFont() {
return font;
}
/** The font's ascent, in points */
public double getAscent() {
return ascent;
}
/** A line's height: the font's ascent, descent and leading, in points */
public double getLineHeight() {
return line;
}
/** The space after each character, in points (DrawingML's spc) */
public double getSpacing() {
return spc;
}
/** In capitals ({@code cap="all"}) */
public boolean isCaps() {
return caps;
}
/** A text as shown: in capitals where the style says */
public String shown(String s) {
return caps ? s.toUpperCase(Locale.ROOT) : s;
}
/**
* A text's width: its kerned advances and the space after each character, the last's
* included (r10's styles 202, 209 and 258: the titles' boxes to 0.01pt; Office's spacing is
* DrawingML's spc after every character)
*/
public double width(String s) {
if (s.isEmpty()) return 0;
String u = shown(s);
return font.getStringBounds(u, FRC).getWidth() + u.length() * spc;
}
/** This style, never kerned (an axis's labels') */
public TextStyle unkerned() {
return kern == 0 ? this : new TextStyle(fonts, typeface, size, bold, italic, colour, 0, spc, caps);
}
/** A text body's first paragraph's defRPr, or null */
public static CTTextCharacterProperties defRPr(CTTextBody tx) {
if (tx == null || tx.getP().isEmpty() || tx.getP().get(0).getPPr() == null) return null;
return tx.getP().get(0).getPPr().getDefRPr();
}
/** A c:txPr (its first paragraph's defRPr) over this style */
public TextStyle with(CTTextBody tx, ThemeColors theme) {
CTTextCharacterProperties p = null;
if (tx != null && !tx.getP().isEmpty()) {
CTTextParagraph para = tx.getP().get(0);
if (para.getPPr() != null) p = para.getPPr().getDefRPr();
}
return with(p, theme);
}
/** A run's properties over this style, its colour resolved through the theme */
public TextStyle with(CTTextCharacterProperties p, ThemeColors theme) {
if (p == null) return this;
double size = p.getSz() != null ? p.getSz() / 100.0 : this.size;
boolean bold = p.isB() != null ? p.isB() : this.bold;
boolean italic = p.isI() != null ? p.isI() : this.italic;
String face = p.getLatin() != null && p.getLatin().getTypeface() != null ? p.getLatin().getTypeface() : this.typeface;
Color colour = this.colour;
if (p.getSolidFill() != null) {
Color c = Fills.awt(DrawingMLColors.resolve(p.getSolidFill(), theme));
if (c != null) colour = c;
}
int kern = p.getKern() != null ? p.getKern() : this.kern;
double spc = p.getSpc() != null ? p.getSpc() / 100.0 : this.spc;
boolean caps = p.getCap() != null ? p.getCap() == org.docx4j.dml.STTextCapsType.ALL : this.caps;
return new TextStyle(fonts, face, size, bold, italic, colour, kern, spc, caps);
}
/**
* A line of text in this style, from its baseline's start; width is the style's (spacing
* after its last character included)
*/
public Drawing.Text text(String t, double x, double baseline, double width, double angle, String role) {
// (a run ending in spaces is drawn to its last glyph: its spaces' width off, r15-title-runs)
String drawn = t.replaceAll(" +$", "");
if (drawn.length() < t.length()) width = width(drawn);
return new Drawing.Text(shown(t), fonts.face(typeface), font, colour, x, baseline, drawn.isEmpty() ? width : width - spc, angle, role,
spc);
}
}
@@ -0,0 +1,248 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.chart.render.api;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.docx4j.dml.CTTextBody;
import org.docx4j.dml.CTTextParagraph;
import org.docx4j.model.color.ThemeColors;
/**
* Text wrapped as Office wraps a chart's: rich text (a title's runs) to lines of pieces in their
* styles, and plain text (a label's, a legend entry's) to lines at spaces and after hyphens.
*
* @since 17.3.3 (CR-039: from docx4j-chart-render's internals, CR-037)
*/
public final class TextWrap {
private TextWrap() {
}
/** A piece of rich text: its text in a style */
public static final class Seg {
private String text;
private final TextStyle style;
public Seg(String text, TextStyle style) {
this.text = text;
this.style = style;
}
public String getText() {
return text;
}
public TextStyle getStyle() {
return style;
}
}
/** A line of rich text: its pieces, its width, its height and ascent (its tallest piece's) */
public static final class Line {
private final List<Seg> segs = new ArrayList<>();
private double width, line, ascent;
/** Its pieces, in order */
public List<Seg> getSegs() {
return Collections.unmodifiableList(segs);
}
/** Its pieces' widths */
public double getWidth() {
return width;
}
/** Its height: its tallest piece's line */
public double getLineHeight() {
return line;
}
/** Its tallest piece's ascent */
public double getAscent() {
return ascent;
}
}
/**
* A text body's paragraphs, each its runs in their styles: the paragraph's defRPr over the
* parent, a run's rPr over that; a line break starts a new paragraph
*/
public static List<List<Seg>> paragraphs(CTTextBody rich, TextStyle parent, ThemeColors theme) {
List<List<Seg>> out = new ArrayList<>();
for (CTTextParagraph p : rich.getP()) {
TextStyle ps = parent.with(p.getPPr() == null ? null : p.getPPr().getDefRPr(), theme);
List<Seg> para = new ArrayList<>();
for (Object o : p.getEGTextRun()) {
Object r = org.docx4j.XmlUtils.unwrap(o);
if (r instanceof org.docx4j.dml.CTRegularTextRun) {
org.docx4j.dml.CTRegularTextRun run = (org.docx4j.dml.CTRegularTextRun) r;
if (run.getT() != null) para.add(new Seg(run.getT(), ps.with(run.getRPr(), theme)));
} else if (r instanceof org.docx4j.dml.CTTextField) {
org.docx4j.dml.CTTextField fld = (org.docx4j.dml.CTTextField) r;
if (fld.getT() != null) para.add(new Seg(fld.getT(), ps.with(fld.getRPr(), theme)));
} else if (r instanceof org.docx4j.dml.CTTextLineBreak) {
out.add(para);
para = new ArrayList<>();
}
}
if (para.isEmpty()) para.add(new Seg("", ps));
out.add(para);
}
return out;
}
/**
* Paragraphs of runs wrapped to lines no wider than max, at spaces (a word wider than max on a
* line of its own; a run's word that goes on into the next run kept whole); each line's pieces
* of one style joined; text of spaces alone a line with nothing on it
*/
public static List<Line> wrap(List<List<Seg>> paragraphs, double max) {
List<Line> out = new ArrayList<>();
for (List<Seg> para : paragraphs) {
// the paragraph's words, each its pieces
List<List<Seg>> words = new ArrayList<>();
List<Seg> cur = new ArrayList<>();
TextStyle last = para.isEmpty() ? null : para.get(0).style;
for (Seg sg : para) {
last = sg.style;
String t = sg.text;
int start = 0;
for (int k = 0; k <= t.length(); k++) {
if (k < t.length() && t.charAt(k) != ' ') continue;
if (k > start) cur.add(new Seg(t.substring(start, k), sg.style));
if (k < t.length()) {
words.add(cur);
cur = new ArrayList<>();
}
start = k + 1;
}
}
words.add(cur);
Line line = null;
for (List<Seg> word : words) {
// spaces at either end, or more than one, are dropped (p6-pie-numbers' title of a space: no width)
if (word.isEmpty()) continue;
double ww = 0;
for (Seg sg : word) ww += sg.style.width(sg.text);
TextStyle ws = word.isEmpty() ? last : word.get(0).style;
if (line != null && line.width + ws.width(" ") + ww > max && !line.segs.isEmpty()) {
out.add(line);
line = null;
}
if (line == null) {
line = new Line();
line.line = ws.getLineHeight();
line.ascent = ws.getAscent();
} else {
// the space before the word, on the line's last piece
Seg prev = line.segs.isEmpty() ? null : line.segs.get(line.segs.size() - 1);
if (prev != null) prev.text += " ";
else line.segs.add(new Seg(" ", ws));
line.width += ws.width(" ");
}
for (Seg sg : word) {
Seg prev = line.segs.isEmpty() ? null : line.segs.get(line.segs.size() - 1);
if (prev != null && prev.style == sg.style) prev.text += sg.text;
else line.segs.add(new Seg(sg.text, sg.style));
line.line = Math.max(line.line, sg.style.getLineHeight());
line.ascent = Math.max(line.ascent, sg.style.getAscent());
}
line.width = 0;
for (Seg sg : line.segs) line.width += sg.style.width(sg.text);
}
if (line == null) {
line = new Line();
line.line = last == null ? 0 : last.getLineHeight();
line.ascent = last == null ? 0 : last.getAscent();
}
out.add(line);
}
return out;
}
/** The pieces a line can break between: at spaces, and after a hyphen ("22-Jan", r14-sweep-dates) */
public static List<String> words(String text) {
List<String> out = new ArrayList<>();
for (String word : text.split(" ")) {
int from = 0;
for (int i = word.indexOf('-'); i >= 0 && i < word.length() - 1; i = word.indexOf('-', i + 1)) {
if (i == 0) continue;
out.add(word.substring(from, i + 1));
from = i + 1;
}
out.add(word.substring(from));
}
return out;
}
/**
* Words wrapped to lines no wider than max (a word wider than max on a line of its own); a
* hyphen's word breaks after it; text of spaces alone is a line with nothing on it (p6-pie-numbers'
* title, " ")
*/
public static List<String> wrap(String text, TextStyle s, double max) {
List<String> out = new ArrayList<>();
String line = null;
for (String word : text.split(" ")) {
List<String> parts = words(word);
for (int p = 0; p < parts.size(); p++) {
String part = parts.get(p);
String next = line == null ? part : line + (p == 0 ? " " : "") + part;
if (line != null && s.width(next) > max) {
out.add(line);
line = part;
} else {
line = next;
}
}
}
if (line != null) out.add(line);
if (out.isEmpty()) out.add("");
return out;
}
/** Words wrapped to lines no wider than max, a word wider than max broken where it reaches it */
public static List<String> wrapBroken(String text, TextStyle s, double max) {
List<String> out = new ArrayList<>();
String line = null;
for (String word : text.split(" ")) {
String rest = word;
while (!rest.isEmpty()) {
String next = line == null ? rest : line + " " + rest;
if (s.width(next) <= max) {
line = next;
rest = "";
} else if (line != null) {
out.add(line);
line = null;
} else {
int k = rest.length();
while (k > 1 && s.width(rest.substring(0, k)) > max) k--;
out.add(rest.substring(0, k));
rest = rest.substring(k);
}
}
}
if (line != null) out.add(line);
if (out.isEmpty()) out.add("");
return out;
}
}
@@ -0,0 +1,41 @@
/*
* Copyright 2026, Plutext Pty Ltd.
*
* This file is part of docx4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The open chart renderer's frame, for a renderer of other charts (a chartex renderer: a
* {@link org.docx4j.model.chart.ChartExRenderer}, CR-039): what docx4j-chart-render measured
* against Office (CR-037), offered as functions and a drawing, without the renderer itself.
*
* <ul>
* <li>{@link org.docx4j.chart.render.api.AxisScale}: Excel's automatic axis bounds and unit;</li>
* <li>{@link org.docx4j.chart.render.api.TextStyle} and {@link org.docx4j.chart.render.api.TextWrap}:
* text measured in the face docx4j's font mapping gives it, and wrapped as Office wraps it;</li>
* <li>{@link org.docx4j.chart.render.api.Fills}: a shape's {@code a:spPr} as fills, lines, dashes,
* shadows and glows, through the theme;</li>
* <li>{@link org.docx4j.chart.render.api.ChartFrame}: the title's and legend's places, and the plot
* area they leave;</li>
* <li>{@link org.docx4j.chart.render.api.Drawing} and {@link org.docx4j.chart.render.api.SvgWriter}:
* what is painted, in order, painted to a {@code Graphics2D} or written as SVG for docx4j's
* outputs.</li>
* </ul>
*
* <p>Number formats are docx4j-core's (xlsx4j's port of POI's {@code DataFormatter}). The
* signatures are kept from 17.3.3; the numbers behind them improve as CR-037's open items close.</p>
*
* @since 17.3.3 (CR-039)
*/
package org.docx4j.chart.render.api;
@@ -0,0 +1,47 @@
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Signifies that a public API (public class, method or field) is subject to incompatible changes,
* or even removal, in a future release. An API bearing this annotation is exempt from any
* compatibility guarantees made by its containing library. Note that the presence of this
* annotation implies nothing about the quality or performance of the API in question, only the fact
* that it is not "API-frozen."
*
* <p>It is generally safe for <i>applications</i> to depend on beta APIs, at the cost of some extra
* work during upgrades. However it is generally inadvisable for <i>libraries</i> (which get
* included on users' CLASSPATHs, outside the library developers' control) to do so.
*
*
* @author Kevin Bourrillion
*/
@Retention(RetentionPolicy.CLASS)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.TYPE
})
@Documented
@GwtCompatible
public @interface Beta {}
@@ -0,0 +1,86 @@
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The presence of this annotation on a type indicates that the type may be used with the <a
* href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> (GWT). When applied to a method,
* the return type of the method is GWT compatible. It's useful to indicate that an instance created
* by factory methods has a GWT serializable type. In the following example,
*
* <pre>
* {@literal @}GwtCompatible
* class Lists {
* ...
* {@literal @}GwtCompatible(serializable = true)
* {@literal static <E> List<E>} newArrayList(E... elements) {
* ...
* }
* }
* </pre>
*
* <p>The return value of {@code Lists.newArrayList(E[])} has GWT serializable type. It is also
* useful in specifying contracts of interface methods. In the following example,
*
* <pre>
* {@literal @}GwtCompatible
* interface ListFactory {
* ...
* {@literal @}GwtCompatible(serializable = true)
* {@literal <E> List<E>} newArrayList(E... elements);
* }
* </pre>
*
* <p>The {@code newArrayList(E[])} method of all implementations of {@code ListFactory} is expected
* to return a value with a GWT serializable type.
*
* <p>Note that a {@code GwtCompatible} type may have some {@link GwtIncompatible} methods.
*
*
* @author Charles Fry
* @author Hayward Chan
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@GwtCompatible
public @interface GwtCompatible {
/**
* When {@code true}, the annotated type or the type of the method return value is GWT
* serializable.
*
* @see <a href=
* "http://code.google.com/webtoolkit/doc/latest/DevGuideServerCommunication.html#DevGuideSerializableTypes">
* Documentation about GWT serialization</a>
*/
boolean serializable() default false;
/**
* When {@code true}, the annotated type is emulated in GWT. The emulated source (also known as
* super-source) is different from the implementation used by the JVM.
*
* @see <a href=
* "http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideModules">
* Documentation about GWT emulated source</a>
*/
boolean emulated() default false;
}
@@ -0,0 +1,47 @@
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The presence of this annotation on an API indicates that the method may <em>not</em> be used with
* the <a href="http://www.gwtproject.org/">Google Web Toolkit</a> (GWT).
*
* <p>This annotation behaves identically to <a href=
* "http://www.gwtproject.org/javadoc/latest/com/google/gwt/core/shared/GwtIncompatible.html">the
* {@code @GwtIncompatible} annotation in GWT itself</a>.
*
* @author Charles Fry
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Documented
@GwtCompatible
public @interface GwtIncompatible {
/**
* Describes why the annotated element is incompatible with GWT. Since this is generally due to a
* dependence on a type/method which GWT doesn't support, it is sufficient to simply reference the
* unsupported type/method. E.g. "Class.isInstance".
*
* <p>As of Guava 20.0, this value is optional. We encourage authors who wish to describe why an
* API is {@code @GwtIncompatible} to instead leave an implementation comment.
*/
String value() default "";
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2006 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.annotations;
/**
* Annotates a program element that exists, or is more widely visible than otherwise necessary, only
* for use in test code.
*
* @author Johannes Henkel
*/
@GwtCompatible
public @interface VisibleForTesting {
}
@@ -0,0 +1,19 @@
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Common annotation types. This package is a part of the open-source <a
* href="http://github.com/google/guava">Guava</a> library.
*/
package org.docx4j.com.google.common.annotations;
@@ -0,0 +1,635 @@
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import static org.docx4j.com.google.common.base.Preconditions.checkArgument;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* Static methods pertaining to ASCII characters (those in the range of values {@code 0x00} through
* {@code 0x7F}), and to strings containing such characters.
*
* <p>ASCII utilities also exist in other classes of this package:
*
* <ul>
* <!-- TODO(kevinb): how can we make this not produce a warning when building gwt javadoc? -->
* <li>{@link Charsets#US_ASCII} specifies the {@code Charset} of ASCII characters.
* <li>{@link CharMatcher#ascii} matches ASCII characters and provides text processing methods
* which operate only on the ASCII characters of a string.
* </ul>
*
* @author Catherine Berry
* @author Gregory Kick
* @since 7.0
*/
@GwtCompatible
public final class Ascii {
private Ascii() {}
/* The ASCII control characters, per RFC 20. */
/**
* Null ('\0'): The all-zeros character which may serve to accomplish time fill and media fill.
* Normally used as a C string terminator.
*
* <p>Although RFC 20 names this as "Null", note that it is distinct from the C/C++ "NULL"
* pointer.
*
* @since 8.0
*/
public static final byte NUL = 0;
/**
* Start of Heading: A communication control character used at the beginning of a sequence of
* characters which constitute a machine-sensible address or routing information. Such a sequence
* is referred to as the "heading." An STX character has the effect of terminating a heading.
*
* @since 8.0
*/
public static final byte SOH = 1;
/**
* Start of Text: A communication control character which precedes a sequence of characters that
* is to be treated as an entity and entirely transmitted through to the ultimate destination.
* Such a sequence is referred to as "text." STX may be used to terminate a sequence of characters
* started by SOH.
*
* @since 8.0
*/
public static final byte STX = 2;
/**
* End of Text: A communication control character used to terminate a sequence of characters
* started with STX and transmitted as an entity.
*
* @since 8.0
*/
public static final byte ETX = 3;
/**
* End of Transmission: A communication control character used to indicate the conclusion of a
* transmission, which may have contained one or more texts and any associated headings.
*
* @since 8.0
*/
public static final byte EOT = 4;
/**
* Enquiry: A communication control character used in data communication systems as a request for
* a response from a remote station. It may be used as a "Who Are You" (WRU) to obtain
* identification, or may be used to obtain station status, or both.
*
* @since 8.0
*/
public static final byte ENQ = 5;
/**
* Acknowledge: A communication control character transmitted by a receiver as an affirmative
* response to a sender.
*
* @since 8.0
*/
public static final byte ACK = 6;
/**
* Bell ('\a'): A character for use when there is a need to call for human attention. It may
* control alarm or attention devices.
*
* @since 8.0
*/
public static final byte BEL = 7;
/**
* Backspace ('\b'): A format effector which controls the movement of the printing position one
* printing space backward on the same printing line. (Applicable also to display devices.)
*
* @since 8.0
*/
public static final byte BS = 8;
/**
* Horizontal Tabulation ('\t'): A format effector which controls the movement of the printing
* position to the next in a series of predetermined positions along the printing line.
* (Applicable also to display devices and the skip function on punched cards.)
*
* @since 8.0
*/
public static final byte HT = 9;
/**
* Line Feed ('\n'): A format effector which controls the movement of the printing position to the
* next printing line. (Applicable also to display devices.) Where appropriate, this character may
* have the meaning "New Line" (NL), a format effector which controls the movement of the printing
* point to the first printing position on the next printing line. Use of this convention requires
* agreement between sender and recipient of data.
*
* @since 8.0
*/
public static final byte LF = 10;
/**
* Alternate name for {@link #LF}. ({@code LF} is preferred.)
*
* @since 8.0
*/
public static final byte NL = 10;
/**
* Vertical Tabulation ('\v'): A format effector which controls the movement of the printing
* position to the next in a series of predetermined printing lines. (Applicable also to display
* devices.)
*
* @since 8.0
*/
public static final byte VT = 11;
/**
* Form Feed ('\f'): A format effector which controls the movement of the printing position to the
* first pre-determined printing line on the next form or page. (Applicable also to display
* devices.)
*
* @since 8.0
*/
public static final byte FF = 12;
/**
* Carriage Return ('\r'): A format effector which controls the movement of the printing position
* to the first printing position on the same printing line. (Applicable also to display devices.)
*
* @since 8.0
*/
public static final byte CR = 13;
/**
* Shift Out: A control character indicating that the code combinations which follow shall be
* interpreted as outside of the character set of the standard code table until a Shift In
* character is reached.
*
* @since 8.0
*/
public static final byte SO = 14;
/**
* Shift In: A control character indicating that the code combinations which follow shall be
* interpreted according to the standard code table.
*
* @since 8.0
*/
public static final byte SI = 15;
/**
* Data Link Escape: A communication control character which will change the meaning of a limited
* number of contiguously following characters. It is used exclusively to provide supplementary
* controls in data communication networks.
*
* @since 8.0
*/
public static final byte DLE = 16;
/**
* Device Control 1. Characters for the control of ancillary devices associated with data
* processing or telecommunication systems, more especially switching devices "on" or "off." (If a
* single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the
* preferred assignment.)
*
* @since 8.0
*/
public static final byte DC1 = 17; // aka XON
/**
* Transmission On: Although originally defined as DC1, this ASCII control character is now better
* known as the XON code used for software flow control in serial communications. The main use is
* restarting the transmission after the communication has been stopped by the XOFF control code.
*
* @since 8.0
*/
public static final byte XON = 17; // aka DC1
/**
* Device Control 2. Characters for the control of ancillary devices associated with data
* processing or telecommunication systems, more especially switching devices "on" or "off." (If a
* single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the
* preferred assignment.)
*
* @since 8.0
*/
public static final byte DC2 = 18;
/**
* Device Control 3. Characters for the control of ancillary devices associated with data
* processing or telecommunication systems, more especially switching devices "on" or "off." (If a
* single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the
* preferred assignment.)
*
* @since 8.0
*/
public static final byte DC3 = 19; // aka XOFF
/**
* Transmission off. See {@link #XON} for explanation.
*
* @since 8.0
*/
public static final byte XOFF = 19; // aka DC3
/**
* Device Control 4. Characters for the control of ancillary devices associated with data
* processing or telecommunication systems, more especially switching devices "on" or "off." (If a
* single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the
* preferred assignment.)
*
* @since 8.0
*/
public static final byte DC4 = 20;
/**
* Negative Acknowledge: A communication control character transmitted by a receiver as a negative
* response to the sender.
*
* @since 8.0
*/
public static final byte NAK = 21;
/**
* Synchronous Idle: A communication control character used by a synchronous transmission system
* in the absence of any other character to provide a signal from which synchronism may be
* achieved or retained.
*
* @since 8.0
*/
public static final byte SYN = 22;
/**
* End of Transmission Block: A communication control character used to indicate the end of a
* block of data for communication purposes. ETB is used for blocking data where the block
* structure is not necessarily related to the processing format.
*
* @since 8.0
*/
public static final byte ETB = 23;
/**
* Cancel: A control character used to indicate that the data with which it is sent is in error or
* is to be disregarded.
*
* @since 8.0
*/
public static final byte CAN = 24;
/**
* End of Medium: A control character associated with the sent data which may be used to identify
* the physical end of the medium, or the end of the used, or wanted, portion of information
* recorded on a medium. (The position of this character does not necessarily correspond to the
* physical end of the medium.)
*
* @since 8.0
*/
public static final byte EM = 25;
/**
* Substitute: A character that may be substituted for a character which is determined to be
* invalid or in error.
*
* @since 8.0
*/
public static final byte SUB = 26;
/**
* Escape: A control character intended to provide code extension (supplementary characters) in
* general information interchange. The Escape character itself is a prefix affecting the
* interpretation of a limited number of contiguously following characters.
*
* @since 8.0
*/
public static final byte ESC = 27;
/**
* File Separator: These four information separators may be used within data in optional fashion,
* except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then
* RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are
* not specified.)
*
* @since 8.0
*/
public static final byte FS = 28;
/**
* Group Separator: These four information separators may be used within data in optional fashion,
* except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then
* RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are
* not specified.)
*
* @since 8.0
*/
public static final byte GS = 29;
/**
* Record Separator: These four information separators may be used within data in optional
* fashion, except that their hierarchical relationship shall be: FS is the most inclusive, then
* GS, then RS, and US is least inclusive. (The content and length of a File, Group, Record, or
* Unit are not specified.)
*
* @since 8.0
*/
public static final byte RS = 30;
/**
* Unit Separator: These four information separators may be used within data in optional fashion,
* except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then
* RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are
* not specified.)
*
* @since 8.0
*/
public static final byte US = 31;
/**
* Space: A normally non-printing graphic character used to separate words. It is also a format
* effector which controls the movement of the printing position, one printing position forward.
* (Applicable also to display devices.)
*
* @since 8.0
*/
public static final byte SP = 32;
/**
* Alternate name for {@link #SP}.
*
* @since 8.0
*/
public static final byte SPACE = 32;
/**
* Delete: This character is used primarily to "erase" or "obliterate" erroneous or unwanted
* characters in perforated tape.
*
* @since 8.0
*/
public static final byte DEL = 127;
/**
* The minimum value of an ASCII character.
*
* @since 9.0 (was type {@code int} before 12.0)
*/
public static final char MIN = 0;
/**
* The maximum value of an ASCII character.
*
* @since 9.0 (was type {@code int} before 12.0)
*/
public static final char MAX = 127;
/** A bit mask which selects the bit encoding ASCII character case. */
private static final char CASE_MASK = 0x20;
/**
* Returns a copy of the input string in which all {@linkplain #isUpperCase(char) uppercase ASCII
* characters} have been converted to lowercase. All other characters are copied without
* modification.
*/
public static String toLowerCase(String string) {
int length = string.length();
for (int i = 0; i < length; i++) {
if (isUpperCase(string.charAt(i))) {
char[] chars = string.toCharArray();
for (; i < length; i++) {
char c = chars[i];
if (isUpperCase(c)) {
chars[i] = (char) (c ^ CASE_MASK);
}
}
return String.valueOf(chars);
}
}
return string;
}
/**
* Returns a copy of the input character sequence in which all {@linkplain #isUpperCase(char)
* uppercase ASCII characters} have been converted to lowercase. All other characters are copied
* without modification.
*
* @since 14.0
*/
public static String toLowerCase(CharSequence chars) {
if (chars instanceof String) {
return toLowerCase((String) chars);
}
char[] newChars = new char[chars.length()];
for (int i = 0; i < newChars.length; i++) {
newChars[i] = toLowerCase(chars.charAt(i));
}
return String.valueOf(newChars);
}
/**
* If the argument is an {@linkplain #isUpperCase(char) uppercase ASCII character} returns the
* lowercase equivalent. Otherwise returns the argument.
*/
public static char toLowerCase(char c) {
return isUpperCase(c) ? (char) (c ^ CASE_MASK) : c;
}
/**
* Returns a copy of the input string in which all {@linkplain #isLowerCase(char) lowercase ASCII
* characters} have been converted to uppercase. All other characters are copied without
* modification.
*/
public static String toUpperCase(String string) {
int length = string.length();
for (int i = 0; i < length; i++) {
if (isLowerCase(string.charAt(i))) {
char[] chars = string.toCharArray();
for (; i < length; i++) {
char c = chars[i];
if (isLowerCase(c)) {
chars[i] = (char) (c ^ CASE_MASK);
}
}
return String.valueOf(chars);
}
}
return string;
}
/**
* Returns a copy of the input character sequence in which all {@linkplain #isLowerCase(char)
* lowercase ASCII characters} have been converted to uppercase. All other characters are copied
* without modification.
*
* @since 14.0
*/
public static String toUpperCase(CharSequence chars) {
if (chars instanceof String) {
return toUpperCase((String) chars);
}
char[] newChars = new char[chars.length()];
for (int i = 0; i < newChars.length; i++) {
newChars[i] = toUpperCase(chars.charAt(i));
}
return String.valueOf(newChars);
}
/**
* If the argument is a {@linkplain #isLowerCase(char) lowercase ASCII character} returns the
* uppercase equivalent. Otherwise returns the argument.
*/
public static char toUpperCase(char c) {
return isLowerCase(c) ? (char) (c ^ CASE_MASK) : c;
}
/**
* Indicates whether {@code c} is one of the twenty-six lowercase ASCII alphabetic characters
* between {@code 'a'} and {@code 'z'} inclusive. All others (including non-ASCII characters)
* return {@code false}.
*/
public static boolean isLowerCase(char c) {
// Note: This was benchmarked against the alternate expression "(char)(c - 'a') < 26" (Nov '13)
// and found to perform at least as well, or better.
return (c >= 'a') && (c <= 'z');
}
/**
* Indicates whether {@code c} is one of the twenty-six uppercase ASCII alphabetic characters
* between {@code 'A'} and {@code 'Z'} inclusive. All others (including non-ASCII characters)
* return {@code false}.
*/
public static boolean isUpperCase(char c) {
return (c >= 'A') && (c <= 'Z');
}
/**
* Truncates the given character sequence to the given maximum length. If the length of the
* sequence is greater than {@code maxLength}, the returned string will be exactly {@code
* maxLength} chars in length and will end with the given {@code truncationIndicator}. Otherwise,
* the sequence will be returned as a string with no changes to the content.
*
* <p>Examples:
*
* <pre>{@code
* Ascii.truncate("foobar", 7, "..."); // returns "foobar"
* Ascii.truncate("foobar", 5, "..."); // returns "fo..."
* }</pre>
*
* <p><b>Note:</b> This method <i>may</i> work with certain non-ASCII text but is not safe for use
* with arbitrary Unicode text. It is mostly intended for use with text that is known to be safe
* for use with it (such as all-ASCII text) and for simple debugging text. When using this method,
* consider the following:
*
* <ul>
* <li>it may split surrogate pairs
* <li>it may split characters and combining characters
* <li>it does not consider word boundaries
* <li>if truncating for display to users, there are other considerations that must be taken
* into account
* <li>the appropriate truncation indicator may be locale-dependent
* <li>it is safe to use non-ASCII characters in the truncation indicator
* </ul>
*
*
* @throws IllegalArgumentException if {@code maxLength} is less than the length of {@code
* truncationIndicator}
* @since 16.0
*/
public static String truncate(CharSequence seq, int maxLength, String truncationIndicator) {
checkNotNull(seq);
// length to truncate the sequence to, not including the truncation indicator
int truncationLength = maxLength - truncationIndicator.length();
// in this worst case, this allows a maxLength equal to the length of the truncationIndicator,
// meaning that a string will be truncated to just the truncation indicator itself
checkArgument(
truncationLength >= 0,
"maxLength (%s) must be >= length of the truncation indicator (%s)",
maxLength,
truncationIndicator.length());
if (seq.length() <= maxLength) {
String string = seq.toString();
if (string.length() <= maxLength) {
return string;
}
// if the length of the toString() result was > maxLength for some reason, truncate that
seq = string;
}
return new StringBuilder(maxLength)
.append(seq, 0, truncationLength)
.append(truncationIndicator)
.toString();
}
/**
* Indicates whether the contents of the given character sequences {@code s1} and {@code s2} are
* equal, ignoring the case of any ASCII alphabetic characters between {@code 'a'} and {@code 'z'}
* or {@code 'A'} and {@code 'Z'} inclusive.
*
* <p>This method is significantly faster than {@link String#equalsIgnoreCase} and should be used
* in preference if at least one of the parameters is known to contain only ASCII characters.
*
* <p>Note however that this method does not always behave identically to expressions such as:
*
* <ul>
* <li>{@code string.toUpperCase().equals("UPPER CASE ASCII")}
* <li>{@code string.toLowerCase().equals("lower case ascii")}
* </ul>
*
* <p>due to case-folding of some non-ASCII characters (which does not occur in {@link
* String#equalsIgnoreCase}). However in almost all cases that ASCII strings are used, the author
* probably wanted the behavior provided by this method rather than the subtle and sometimes
* surprising behavior of {@code toUpperCase()} and {@code toLowerCase()}.
*
* @since 16.0
*/
public static boolean equalsIgnoreCase(CharSequence s1, CharSequence s2) {
// Calling length() is the null pointer check (so do it before we can exit early).
int length = s1.length();
if (s1 == s2) {
return true;
}
if (length != s2.length()) {
return false;
}
for (int i = 0; i < length; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 == c2) {
continue;
}
int alphaIndex = getAlphaIndex(c1);
// This was also benchmarked using '&' to avoid branching (but always evaluate the rhs),
// however this showed no obvious improvement.
if (alphaIndex < 26 && alphaIndex == getAlphaIndex(c2)) {
continue;
}
return false;
}
return true;
}
/**
* Returns the non-negative index value of the alpha character {@code c}, regardless of case. Ie,
* 'a'/'A' returns 0 and 'z'/'Z' returns 25. Non-alpha characters return a value of 26 or greater.
*/
private static int getAlphaIndex(char c) {
// Fold upper-case ASCII to lower-case and make zero-indexed and unsigned (by casting to char).
return (char) ((c | CASE_MASK) - 'a');
}
}
@@ -0,0 +1,335 @@
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import com.google.errorprone.annotations.ForOverride;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import java.io.Serializable;
import java.util.function.BiPredicate;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* A strategy for determining whether two instances are considered equivalent, and for computing
* hash codes in a manner consistent with that equivalence. Two examples of equivalences are the
* {@linkplain #identity() identity equivalence} and the {@linkplain #equals "equals" equivalence}.
*
* @author Bob Lee
* @author Ben Yu
* @author Gregory Kick
* @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly
* source-compatible</a> since 4.0)
*/
@GwtCompatible
public abstract class Equivalence<T> implements BiPredicate<T, T> {
/** Constructor for use by subclasses. */
protected Equivalence() {}
/**
* Returns {@code true} if the given objects are considered equivalent.
*
* <p>This method describes an <i>equivalence relation</i> on object references, meaning that for
* all references {@code x}, {@code y}, and {@code z} (any of which may be null):
*
* <ul>
* <li>{@code equivalent(x, x)} is true (<i>reflexive</i> property)
* <li>{@code equivalent(x, y)} and {@code equivalent(y, x)} each return the same result
* (<i>symmetric</i> property)
* <li>If {@code equivalent(x, y)} and {@code equivalent(y, z)} are both true, then {@code
* equivalent(x, z)} is also true (<i>transitive</i> property)
* </ul>
*
* <p>Note that all calls to {@code equivalent(x, y)} are expected to return the same result as
* long as neither {@code x} nor {@code y} is modified.
*/
public final boolean equivalent(@Nullable T a, @Nullable T b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
return doEquivalent(a, b);
}
/**
* @deprecated Provided only to satisfy the {@link BiPredicate} interface; use {@link #equivalent}
* instead.
* @since 21.0
*/
@Deprecated
@Override
public final boolean test(@Nullable T t, @Nullable T u) {
return equivalent(t, u);
}
/**
* Implemented by the user to determine whether {@code a} and {@code b} are considered equivalent,
* subject to the requirements specified in {@link #equivalent}.
*
* <p>This method should not be called except by {@link #equivalent}. When {@link #equivalent}
* calls this method, {@code a} and {@code b} are guaranteed to be distinct, non-null instances.
*
* @since 10.0 (previously, subclasses would override equivalent())
*/
@ForOverride
protected abstract boolean doEquivalent(T a, T b);
/**
* Returns a hash code for {@code t}.
*
* <p>The {@code hash} has the following properties:
*
* <ul>
* <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of {@code
* hash(x}} consistently return the same value provided {@code x} remains unchanged
* according to the definition of the equivalence. The hash need not remain consistent from
* one execution of an application to another execution of the same application.
* <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code
* y}, if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i>
* necessary that the hash be distributable across <i>inequivalence</i>. If {@code
* equivalence(x, y)} is false, {@code hash(x) == hash(y)} may still be true.
* <li>{@code hash(null)} is {@code 0}.
* </ul>
*/
public final int hash(@Nullable T t) {
if (t == null) {
return 0;
}
return doHash(t);
}
/**
* Implemented by the user to return a hash code for {@code t}, subject to the requirements
* specified in {@link #hash}.
*
* <p>This method should not be called except by {@link #hash}. When {@link #hash} calls this
* method, {@code t} is guaranteed to be non-null.
*
* @since 10.0 (previously, subclasses would override hash())
*/
@ForOverride
protected abstract int doHash(T t);
/**
* Returns a wrapper of {@code reference} that implements {@link Wrapper#equals(Object)
* Object.equals()} such that {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a,
* b)}.
*
* @since 10.0
*/
public final <S extends T> Wrapper<S> wrap(@Nullable S reference) {
return new Wrapper<S>(this, reference);
}
/**
* Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an {@link
* Equivalence}.
*
* <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv}
* that tests equivalence using their lengths:
*
* <pre>{@code
* equiv.wrap("a").equals(equiv.wrap("b")) // true
* equiv.wrap("a").equals(equiv.wrap("hello")) // false
* }</pre>
*
* <p>Note in particular that an equivalence wrapper is never equal to the object it wraps.
*
* <pre>{@code
* equiv.wrap(obj).equals(obj) // always false
* }</pre>
*
* @since 10.0
*/
public static final class Wrapper<T> implements Serializable {
private final Equivalence<? super T> equivalence;
private final @Nullable T reference;
private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) {
this.equivalence = checkNotNull(equivalence);
this.reference = reference;
}
/** Returns the (possibly null) reference wrapped by this instance. */
public @Nullable T get() {
return reference;
}
/**
* Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
* references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
* equivalence.
*/
@Override
public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Wrapper) {
Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T>
if (this.equivalence.equals(that.equivalence)) {
/*
* We'll accept that as sufficient "proof" that either equivalence should be able to
* handle either reference, so it's safe to circumvent compile-time type checking.
*/
@SuppressWarnings("unchecked")
Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence;
return equivalence.equivalent(this.reference, that.reference);
}
}
return false;
}
/** Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. */
@Override
public int hashCode() {
return equivalence.hash(reference);
}
/**
* Returns a string representation for this equivalence wrapper. The form of this string
* representation is not specified.
*/
@Override
public String toString() {
return equivalence + ".wrap(" + reference + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a predicate that evaluates to true if and only if the input is equivalent to {@code
* target} according to this equivalence relation.
*
* @since 10.0
*/
public final Predicate<T> equivalentTo(@Nullable T target) {
return new EquivalentToPredicate<T>(this, target);
}
private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable {
private final Equivalence<T> equivalence;
private final @Nullable T target;
EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) {
this.equivalence = checkNotNull(equivalence);
this.target = target;
}
@Override
public boolean apply(@Nullable T input) {
return equivalence.equivalent(input, target);
}
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof EquivalentToPredicate) {
EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
return equivalence.equals(that.equivalence) && Objects.equal(target, that.target);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(equivalence, target);
}
@Override
public String toString() {
return equivalence + ".equivalentTo(" + target + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}.
* {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither
* value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns
* {@code 0} if passed a null value.
*
* @since 13.0
* @since 8.0 (in Equivalences with null-friendly behavior)
* @since 4.0 (in Equivalences)
*/
public static Equivalence<Object> equals() {
return Equals.INSTANCE;
}
/**
* Returns an equivalence that uses {@code ==} to compare values and {@link
* System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent}
* returns {@code true} if {@code a == b}, including in the case that a and b are both null.
*
* @since 13.0
* @since 4.0 (in Equivalences)
*/
public static Equivalence<Object> identity() {
return Identity.INSTANCE;
}
static final class Equals extends Equivalence<Object> implements Serializable {
static final Equals INSTANCE = new Equals();
@Override
protected boolean doEquivalent(Object a, Object b) {
return a.equals(b);
}
@Override
protected int doHash(Object o) {
return o.hashCode();
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 1;
}
static final class Identity extends Equivalence<Object> implements Serializable {
static final Identity INSTANCE = new Identity();
@Override
protected boolean doEquivalent(Object a, Object b) {
return false;
}
@Override
protected int doHash(Object o) {
return System.identityHashCode(o);
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 1;
}
}
@@ -0,0 +1,24 @@
/*
* Copyright (C) 2016 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* Holder for extra methods of {@code Objects} only in web. Intended to be empty for regular
* version.
*/
@GwtCompatible(emulated = true)
abstract class ExtraObjectsMethodsForWeb {}
@@ -0,0 +1,63 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* Legacy version of {@link java.util.function.Function java.util.function.Function}.
*
* <p>The {@link Functions} class provides common functions and related utilities.
*
* <p>As this interface extends {@code java.util.function.Function}, an instance of this type can be
* used as a {@code java.util.function.Function} directly. To use a {@code
* java.util.function.Function} in a context where a {@code org.docx4j.com.google.common.base.Function} is
* needed, use {@code function::apply}.
*
* <p>This interface is now a legacy type. Use {@code java.util.function.Function} (or the
* appropriate primitive specialization such as {@code ToIntFunction}) instead whenever possible.
* Otherwise, at least reduce <i>explicit</i> dependencies on this type by using lambda expressions
* or method references instead of classes, leaving your code easier to migrate in the future.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/FunctionalExplained">the use of {@code Function}</a>.
*
* @author Kevin Bourrillion
* @since 2.0
*/
@GwtCompatible
@FunctionalInterface
public interface Function<F, T> extends java.util.function.Function<F, T> {
@Override
@CanIgnoreReturnValue // TODO(kevinb): remove this
@Nullable
T apply(@Nullable F input);
/**
* <i>May</i> return {@code true} if {@code object} is a {@code Function} that behaves identically
* to this function.
*
* <p><b>Warning: do not depend</b> on the behavior of this method.
*
* <p>Historically, {@code Function} instances in this library have implemented this method to
* recognize certain cases where distinct {@code Function} instances would in fact behave
* identically. However, as code migrates to {@code java.util.function}, that behavior will
* disappear. It is best not to depend on it.
*/
@Override
boolean equals(@Nullable Object object);
}
@@ -0,0 +1,388 @@
/*
* Copyright (C) 2014 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import java.util.Arrays;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* Helper functions that operate on any {@code Object}, and are not already provided in {@link
* java.util.Objects}.
*
* <p>See the Guava User Guide on <a
* href="https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained">writing {@code Object}
* methods with {@code MoreObjects}</a>.
*
* @author Laurence Gonsalves
* @since 18.0 (since 2.0 as {@code Objects})
*/
@GwtCompatible
public final class MoreObjects {
/**
* Returns the first of two given parameters that is not {@code null}, if either is, or otherwise
* throws a {@link NullPointerException}.
*
* <p>To find the first non-null element in an iterable, use {@code Iterables.find(iterable,
* Predicates.notNull())}. For varargs, use {@code Iterables.find(Arrays.asList(a, b, c, ...),
* Predicates.notNull())}, static importing as necessary.
*
* <p><b>Note:</b> if {@code first} is represented as an {@link Optional}, this can be
* accomplished with {@link Optional#or(Object) first.or(second)}. That approach also allows for
* lazy evaluation of the fallback instance, using {@link Optional#or(Supplier)
* first.or(supplier)}.
*
* @return {@code first} if it is non-null; otherwise {@code second} if it is non-null
* @throws NullPointerException if both {@code first} and {@code second} are null
* @since 18.0 (since 3.0 as {@code Objects.firstNonNull()}).
*/
public static <T> T firstNonNull(@Nullable T first, @Nullable T second) {
if (first != null) {
return first;
}
if (second != null) {
return second;
}
throw new NullPointerException("Both parameters are null");
}
/**
* Creates an instance of {@link ToStringHelper}.
*
* <p>This is helpful for implementing {@link Object#toString()}. Specification by example:
*
* <pre>{@code
* // Returns "ClassName{}"
* MoreObjects.toStringHelper(this)
* .toString();
*
* // Returns "ClassName{x=1}"
* MoreObjects.toStringHelper(this)
* .add("x", 1)
* .toString();
*
* // Returns "MyObject{x=1}"
* MoreObjects.toStringHelper("MyObject")
* .add("x", 1)
* .toString();
*
* // Returns "ClassName{x=1, y=foo}"
* MoreObjects.toStringHelper(this)
* .add("x", 1)
* .add("y", "foo")
* .toString();
*
* // Returns "ClassName{x=1}"
* MoreObjects.toStringHelper(this)
* .omitNullValues()
* .add("x", 1)
* .add("y", null)
* .toString();
* }</pre>
*
* <p>Note that in GWT, class names are often obfuscated.
*
* @param self the object to generate the string for (typically {@code this}), used only for its
* class name
* @since 18.0 (since 2.0 as {@code Objects.toStringHelper()}).
*/
public static ToStringHelper toStringHelper(Object self) {
return new ToStringHelper(self.getClass().getSimpleName());
}
/**
* Creates an instance of {@link ToStringHelper} in the same manner as {@link
* #toStringHelper(Object)}, but using the simple name of {@code clazz} instead of using an
* instance's {@link Object#getClass()}.
*
* <p>Note that in GWT, class names are often obfuscated.
*
* @param clazz the {@link Class} of the instance
* @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
*/
public static ToStringHelper toStringHelper(Class<?> clazz) {
return new ToStringHelper(clazz.getSimpleName());
}
/**
* Creates an instance of {@link ToStringHelper} in the same manner as {@link
* #toStringHelper(Object)}, but using {@code className} instead of using an instance's {@link
* Object#getClass()}.
*
* @param className the name of the instance type
* @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
*/
public static ToStringHelper toStringHelper(String className) {
return new ToStringHelper(className);
}
/**
* Support class for {@link MoreObjects#toStringHelper}.
*
* @author Jason Lee
* @since 18.0 (since 2.0 as {@code Objects.ToStringHelper}).
*/
public static final class ToStringHelper {
private final String className;
private final ValueHolder holderHead = new ValueHolder();
private ValueHolder holderTail = holderHead;
private boolean omitNullValues = false;
/** Use {@link MoreObjects#toStringHelper(Object)} to create an instance. */
private ToStringHelper(String className) {
this.className = checkNotNull(className);
}
/**
* Configures the {@link ToStringHelper} so {@link #toString()} will ignore properties with null
* value. The order of calling this method, relative to the {@code add()}/{@code addValue()}
* methods, is not significant.
*
* @since 18.0 (since 12.0 as {@code Objects.ToStringHelper.omitNullValues()}).
*/
@CanIgnoreReturnValue
public ToStringHelper omitNullValues() {
omitNullValues = true;
return this;
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format. If {@code value}
* is {@code null}, the string {@code "null"} is used, unless {@link #omitNullValues()} is
* called, in which case this name/value pair will not be added.
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, @Nullable Object value) {
return addHolder(name, value);
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, boolean value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, char value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, double value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, float value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, int value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, long value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, Object)} instead and give value a
* readable name.
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(@Nullable Object value) {
return addHolder(value);
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, boolean)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(boolean value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, char)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(char value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, double)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(double value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, float)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(float value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, int)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(int value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, long)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(long value) {
return addHolder(String.valueOf(value));
}
/**
* Returns a string in the format specified by {@link MoreObjects#toStringHelper(Object)}.
*
* <p>After calling this method, you can keep adding more properties to later call toString()
* again and get a more complete representation of the same object; but properties cannot be
* removed, so this only allows limited reuse of the helper instance. The helper allows
* duplication of properties (multiple name/value pairs with the same name can be added).
*/
@Override
public String toString() {
// create a copy to keep it consistent in case value changes
boolean omitNullValuesSnapshot = omitNullValues;
String nextSeparator = "";
StringBuilder builder = new StringBuilder(32).append(className).append('{');
for (ValueHolder valueHolder = holderHead.next;
valueHolder != null;
valueHolder = valueHolder.next) {
Object value = valueHolder.value;
if (!omitNullValuesSnapshot || value != null) {
builder.append(nextSeparator);
nextSeparator = ", ";
if (valueHolder.name != null) {
builder.append(valueHolder.name).append('=');
}
if (value != null && value.getClass().isArray()) {
Object[] objectArray = {value};
String arrayString = Arrays.deepToString(objectArray);
builder.append(arrayString, 1, arrayString.length() - 1);
} else {
builder.append(value);
}
}
}
return builder.append('}').toString();
}
private ValueHolder addHolder() {
ValueHolder valueHolder = new ValueHolder();
holderTail = holderTail.next = valueHolder;
return valueHolder;
}
private ToStringHelper addHolder(@Nullable Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
return this;
}
private ToStringHelper addHolder(String name, @Nullable Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
valueHolder.name = checkNotNull(name);
return this;
}
private static final class ValueHolder {
@Nullable String name;
@Nullable Object value;
@Nullable ValueHolder next;
}
}
private MoreObjects() {}
}
@@ -0,0 +1,79 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import java.util.Arrays;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* Helper functions that can operate on any {@code Object}.
*
* <p>See the Guava User Guide on <a
* href="https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained">writing {@code Object}
* methods with {@code Objects}</a>.
*
* @author Laurence Gonsalves
* @since 2.0
*/
@GwtCompatible
public final class Objects extends ExtraObjectsMethodsForWeb {
private Objects() {}
/**
* Determines whether two possibly-null objects are equal. Returns:
*
* <ul>
* <li>{@code true} if {@code a} and {@code b} are both null.
* <li>{@code true} if {@code a} and {@code b} are both non-null and they are equal according to
* {@link Object#equals(Object)}.
* <li>{@code false} in all other situations.
* </ul>
*
* <p>This assumes that any non-null objects passed to this function conform to the {@code
* equals()} contract.
*
* <p><b>Note for Java 7 and later:</b> This method should be treated as deprecated; use {@link
* java.util.Objects#equals} instead.
*/
public static boolean equal(@Nullable Object a, @Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
/**
* Generates a hash code for multiple values. The hash code is generated by calling {@link
* Arrays#hashCode(Object[])}. Note that array arguments to this method, with the exception of a
* single Object array, do not get any special handling; their hash codes are based on identity
* and not contents.
*
* <p>This is useful for implementing {@link Object#hashCode()}. For example, in an object that
* has three properties, {@code x}, {@code y}, and {@code z}, one could write:
*
* <pre>{@code
* public int hashCode() {
* return Objects.hashCode(getX(), getY(), getZ());
* }
* }</pre>
*
* <p><b>Warning:</b> When a single object is supplied, the returned hash code does not equal the
* hash code of that object.
*
* <p><b>Note for Java 7 and later:</b> This method should be treated as deprecated; use {@link
* java.util.Objects#hash} instead.
*/
public static int hashCode(Object @Nullable ... objects) {
return Arrays.hashCode(objects);
}
}
@@ -0,0 +1,66 @@
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import java.lang.ref.WeakReference;
import java.util.Locale;
import java.util.ServiceConfigurationError;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Methods factored out so that they can be emulated differently in GWT.
*
* @author Jesse Wilson
*/
@GwtCompatible(emulated = true)
final class Platform {
private static Logger log = LoggerFactory.getLogger(Platform.class);
private Platform() {}
/** Calls {@link System#nanoTime()}. */
@SuppressWarnings("GoodTime") // reading system time without TimeSource
static long systemNanoTime() {
return System.nanoTime();
}
static String formatCompact4Digits(double value) {
return String.format(Locale.ROOT, "%.4g", value);
}
static boolean stringIsNullOrEmpty(@Nullable String string) {
return string == null || string.isEmpty();
}
static String nullToEmpty(@Nullable String string) {
return (string == null) ? "" : string;
}
static String emptyToNull(@Nullable String string) {
return stringIsNullOrEmpty(string) ? null : string;
}
private static void logPatternCompilerError(ServiceConfigurationError e) {
log.warn("Error loading regex compiler, falling back to next option", e);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,81 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* Legacy version of {@link java.util.function.Predicate java.util.function.Predicate}. Determines a
* true or false value for a given input.
*
* <p>As this interface extends {@code java.util.function.Predicate}, an instance of this type may
* be used as a {@code Predicate} directly. To use a {@code java.util.function.Predicate} where a
* {@code org.docx4j.com.google.common.base.Predicate} is expected, use the method reference {@code
* predicate::test}.
*
* <p>This interface is now a legacy type. Use {@code java.util.function.Predicate} (or the
* appropriate primitive specialization such as {@code IntPredicate}) instead whenever possible.
* Otherwise, at least reduce <i>explicit</i> dependencies on this type by using lambda expressions
* or method references instead of classes, leaving your code easier to migrate in the future.
*
* <p>The {@link Predicates} class provides common predicates and related utilities.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/FunctionalExplained">the use of {@code Predicate}</a>.
*
* @author Kevin Bourrillion
* @since 2.0
*/
@FunctionalInterface
@GwtCompatible
public interface Predicate<T> extends java.util.function.Predicate<T> {
/**
* Returns the result of applying this predicate to {@code input} (Java 8 users, see notes in the
* class documentation above). This method is <i>generally expected</i>, but not absolutely
* required, to have the following properties:
*
* <ul>
* <li>Its execution does not cause any observable side effects.
* <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal
* Objects.equal}{@code (a, b)} implies that {@code predicate.apply(a) ==
* predicate.apply(b))}.
* </ul>
*
* @throws NullPointerException if {@code input} is null and this predicate does not accept null
* arguments
*/
@CanIgnoreReturnValue
boolean apply(@Nullable T input);
/**
* Indicates whether another object is equal to this predicate.
*
* <p>Most implementations will have no reason to override the behavior of {@link Object#equals}.
* However, an implementation may also choose to return {@code true} whenever {@code object} is a
* {@link Predicate} that it considers <i>interchangeable</i> with this one. "Interchangeable"
* <i>typically</i> means that {@code this.apply(t) == that.apply(t)} for all {@code t} of type
* {@code T}). Note that a {@code false} result from this method does not imply that the
* predicates are known <i>not</i> to be interchangeable.
*/
@Override
boolean equals(@Nullable Object object);
@Override
default boolean test(@Nullable T input) {
return apply(input);
}
}
@@ -0,0 +1,270 @@
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import static org.docx4j.com.google.common.base.Preconditions.checkState;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.annotations.GwtIncompatible;
/**
* An object that measures elapsed time in nanoseconds. It is useful to measure elapsed time using
* this class instead of direct calls to {@link System#nanoTime} for a few reasons:
*
* <ul>
* <li>An alternate time source can be substituted, for testing or performance reasons.
* <li>As documented by {@code nanoTime}, the value returned has no absolute meaning, and can only
* be interpreted as relative to another timestamp returned by {@code nanoTime} at a different
* time. {@code Stopwatch} is a more effective abstraction because it exposes only these
* relative values, not the absolute ones.
* </ul>
*
* <p>Basic usage:
*
* <pre>{@code
* Stopwatch stopwatch = Stopwatch.createStarted();
* doSomething();
* stopwatch.stop(); // optional
*
* Duration duration = stopwatch.elapsed();
*
* log.info("time: " + stopwatch); // formatted string like "12.3 ms"
* }</pre>
*
* <p>Stopwatch methods are not idempotent; it is an error to start or stop a stopwatch that is
* already in the desired state.
*
* <p>When testing code that uses this class, use {@link #createUnstarted(Ticker)} or {@link
* #createStarted(Ticker)} to supply a fake or mock ticker. This allows you to simulate any valid
* behavior of the stopwatch.
*
* <p><b>Note:</b> This class is not thread-safe.
*
* <p><b>Warning for Android users:</b> a stopwatch with default behavior may not continue to keep
* time while the device is asleep. Instead, create one like this:
*
* <pre>{@code
* Stopwatch.createStarted(
* new Ticker() {
* public long read() {
* return android.os.SystemClock.elapsedRealtimeNanos();
* }
* });
* }</pre>
*
* @author Kevin Bourrillion
* @since 10.0
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("GoodTime") // lots of violations
public final class Stopwatch {
private final Ticker ticker;
private boolean isRunning;
private long elapsedNanos;
private long startTick;
/**
* Creates (but does not start) a new stopwatch using {@link System#nanoTime} as its time source.
*
* @since 15.0
*/
public static Stopwatch createUnstarted() {
return new Stopwatch();
}
/**
* Creates (but does not start) a new stopwatch, using the specified time source.
*
* @since 15.0
*/
public static Stopwatch createUnstarted(Ticker ticker) {
return new Stopwatch(ticker);
}
/**
* Creates (and starts) a new stopwatch using {@link System#nanoTime} as its time source.
*
* @since 15.0
*/
public static Stopwatch createStarted() {
return new Stopwatch().start();
}
/**
* Creates (and starts) a new stopwatch, using the specified time source.
*
* @since 15.0
*/
public static Stopwatch createStarted(Ticker ticker) {
return new Stopwatch(ticker).start();
}
Stopwatch() {
this.ticker = Ticker.systemTicker();
}
Stopwatch(Ticker ticker) {
this.ticker = checkNotNull(ticker, "ticker");
}
/**
* Returns {@code true} if {@link #start()} has been called on this stopwatch, and {@link #stop()}
* has not been called since the last call to {@code start()}.
*/
public boolean isRunning() {
return isRunning;
}
/**
* Starts the stopwatch.
*
* @return this {@code Stopwatch} instance
* @throws IllegalStateException if the stopwatch is already running.
*/
@CanIgnoreReturnValue
public Stopwatch start() {
checkState(!isRunning, "This stopwatch is already running.");
isRunning = true;
startTick = ticker.read();
return this;
}
/**
* Stops the stopwatch. Future reads will return the fixed duration that had elapsed up to this
* point.
*
* @return this {@code Stopwatch} instance
* @throws IllegalStateException if the stopwatch is already stopped.
*/
@CanIgnoreReturnValue
public Stopwatch stop() {
long tick = ticker.read();
checkState(isRunning, "This stopwatch is already stopped.");
isRunning = false;
elapsedNanos += tick - startTick;
return this;
}
/**
* Sets the elapsed time for this stopwatch to zero, and places it in a stopped state.
*
* @return this {@code Stopwatch} instance
*/
@CanIgnoreReturnValue
public Stopwatch reset() {
elapsedNanos = 0;
isRunning = false;
return this;
}
private long elapsedNanos() {
return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos;
}
/**
* Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit,
* with any fraction rounded down.
*
* <p><b>Note:</b> the overhead of measurement can be more than a microsecond, so it is generally
* not useful to specify {@link TimeUnit#NANOSECONDS} precision here.
*
* <p>It is generally not a good idea to use an ambiguous, unitless {@code long} to represent
* elapsed time. Therefore, we recommend using {@link #elapsed()} instead, which returns a
* strongly-typed {@link Duration} instance.
*
* @since 14.0 (since 10.0 as {@code elapsedTime()})
*/
public long elapsed(TimeUnit desiredUnit) {
return desiredUnit.convert(elapsedNanos(), NANOSECONDS);
}
/**
* Returns the current elapsed time shown on this stopwatch as a {@link Duration}. Unlike {@link
* #elapsed(TimeUnit)}, this method does not lose any precision due to rounding.
*
* @since 22.0
*/
@GwtIncompatible
public Duration elapsed() {
return Duration.ofNanos(elapsedNanos());
}
/** Returns a string representation of the current elapsed time. */
@Override
public String toString() {
long nanos = elapsedNanos();
TimeUnit unit = chooseUnit(nanos);
double value = (double) nanos / NANOSECONDS.convert(1, unit);
// Too bad this functionality is not exposed as a regular method call
return Platform.formatCompact4Digits(value) + " " + abbreviate(unit);
}
private static TimeUnit chooseUnit(long nanos) {
if (DAYS.convert(nanos, NANOSECONDS) > 0) {
return DAYS;
}
if (HOURS.convert(nanos, NANOSECONDS) > 0) {
return HOURS;
}
if (MINUTES.convert(nanos, NANOSECONDS) > 0) {
return MINUTES;
}
if (SECONDS.convert(nanos, NANOSECONDS) > 0) {
return SECONDS;
}
if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
return MILLISECONDS;
}
if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
return MICROSECONDS;
}
return NANOSECONDS;
}
private static String abbreviate(TimeUnit unit) {
switch (unit) {
case NANOSECONDS:
return "ns";
case MICROSECONDS:
return "\u03bcs"; // μs
case MILLISECONDS:
return "ms";
case SECONDS:
return "s";
case MINUTES:
return "min";
case HOURS:
return "h";
case DAYS:
return "d";
default:
throw new AssertionError();
}
}
}
@@ -0,0 +1,315 @@
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import static org.docx4j.com.google.common.base.Preconditions.checkArgument;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Static utility methods pertaining to {@code String} or {@code CharSequence} instances.
*
* @author Kevin Bourrillion
* @since 3.0
*/
@GwtCompatible
public final class Strings {
private static Logger log = LoggerFactory.getLogger(Strings.class);
private Strings() {}
/**
* Returns the given string if it is non-null; the empty string otherwise.
*
* @param string the string to test and possibly return
* @return {@code string} itself if it is non-null; {@code ""} if it is null
*/
public static String nullToEmpty(@Nullable String string) {
return Platform.nullToEmpty(string);
}
/**
* Returns the given string if it is nonempty; {@code null} otherwise.
*
* @param string the string to test and possibly return
* @return {@code string} itself if it is nonempty; {@code null} if it is empty or null
*/
public static @Nullable String emptyToNull(@Nullable String string) {
return Platform.emptyToNull(string);
}
/**
* Returns {@code true} if the given string is null or is the empty string.
*
* <p>Consider normalizing your string references with {@link #nullToEmpty}. If you do, you can
* use {@link String#isEmpty()} instead of this method, and you won't need special null-safe forms
* of methods like {@link String#toUpperCase} either. Or, if you'd like to normalize "in the other
* direction," converting empty strings to {@code null}, you can use {@link #emptyToNull}.
*
* @param string a string reference to check
* @return {@code true} if the string is null or is the empty string
*/
public static boolean isNullOrEmpty(@Nullable String string) {
return Platform.stringIsNullOrEmpty(string);
}
/**
* Returns a string, of length at least {@code minLength}, consisting of {@code string} prepended
* with as many copies of {@code padChar} as are necessary to reach that length. For example,
*
* <ul>
* <li>{@code padStart("7", 3, '0')} returns {@code "007"}
* <li>{@code padStart("2010", 3, '0')} returns {@code "2010"}
* </ul>
*
* <p>See {@link java.util.Formatter} for a richer set of formatting capabilities.
*
* @param string the string which should appear at the end of the result
* @param minLength the minimum length the resulting string must have. Can be zero or negative, in
* which case the input string is always returned.
* @param padChar the character to insert at the beginning of the result until the minimum length
* is reached
* @return the padded string
*/
public static String padStart(String string, int minLength, char padChar) {
checkNotNull(string); // eager for GWT.
if (string.length() >= minLength) {
return string;
}
StringBuilder sb = new StringBuilder(minLength);
for (int i = string.length(); i < minLength; i++) {
sb.append(padChar);
}
sb.append(string);
return sb.toString();
}
/**
* Returns a string, of length at least {@code minLength}, consisting of {@code string} appended
* with as many copies of {@code padChar} as are necessary to reach that length. For example,
*
* <ul>
* <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"}
* <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"}
* </ul>
*
* <p>See {@link java.util.Formatter} for a richer set of formatting capabilities.
*
* @param string the string which should appear at the beginning of the result
* @param minLength the minimum length the resulting string must have. Can be zero or negative, in
* which case the input string is always returned.
* @param padChar the character to append to the end of the result until the minimum length is
* reached
* @return the padded string
*/
public static String padEnd(String string, int minLength, char padChar) {
checkNotNull(string); // eager for GWT.
if (string.length() >= minLength) {
return string;
}
StringBuilder sb = new StringBuilder(minLength);
sb.append(string);
for (int i = string.length(); i < minLength; i++) {
sb.append(padChar);
}
return sb.toString();
}
/**
* Returns a string consisting of a specific number of concatenated copies of an input string. For
* example, {@code repeat("hey", 3)} returns the string {@code "heyheyhey"}.
*
* @param string any non-null string
* @param count the number of times to repeat it; a nonnegative integer
* @return a string containing {@code string} repeated {@code count} times (the empty string if
* {@code count} is zero)
* @throws IllegalArgumentException if {@code count} is negative
*/
public static String repeat(String string, int count) {
checkNotNull(string); // eager for GWT.
if (count <= 1) {
checkArgument(count >= 0, "invalid count: %s", count);
return (count == 0) ? "" : string;
}
// IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark
final int len = string.length();
final long longSize = (long) len * (long) count;
final int size = (int) longSize;
if (size != longSize) {
throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize);
}
final char[] array = new char[size];
string.getChars(0, len, array, 0);
int n;
for (n = len; n < size - n; n <<= 1) {
System.arraycopy(array, 0, array, n, n);
}
System.arraycopy(array, 0, array, n, size - n);
return new String(array);
}
/**
* Returns the longest string {@code prefix} such that {@code a.toString().startsWith(prefix) &&
* b.toString().startsWith(prefix)}, taking care not to split surrogate pairs. If {@code a} and
* {@code b} have no common prefix, returns the empty string.
*
* @since 11.0
*/
public static String commonPrefix(CharSequence a, CharSequence b) {
checkNotNull(a);
checkNotNull(b);
int maxPrefixLength = Math.min(a.length(), b.length());
int p = 0;
while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) {
p++;
}
if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) {
p--;
}
return a.subSequence(0, p).toString();
}
/**
* Returns the longest string {@code suffix} such that {@code a.toString().endsWith(suffix) &&
* b.toString().endsWith(suffix)}, taking care not to split surrogate pairs. If {@code a} and
* {@code b} have no common suffix, returns the empty string.
*
* @since 11.0
*/
public static String commonSuffix(CharSequence a, CharSequence b) {
checkNotNull(a);
checkNotNull(b);
int maxSuffixLength = Math.min(a.length(), b.length());
int s = 0;
while (s < maxSuffixLength && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) {
s++;
}
if (validSurrogatePairAt(a, a.length() - s - 1)
|| validSurrogatePairAt(b, b.length() - s - 1)) {
s--;
}
return a.subSequence(a.length() - s, a.length()).toString();
}
/**
* True when a valid surrogate pair starts at the given {@code index} in the given {@code string}.
* Out-of-range indexes return false.
*/
@VisibleForTesting
static boolean validSurrogatePairAt(CharSequence string, int index) {
return index >= 0
&& index <= (string.length() - 2)
&& Character.isHighSurrogate(string.charAt(index))
&& Character.isLowSurrogate(string.charAt(index + 1));
}
/**
* Returns the given {@code template} string with each occurrence of {@code "%s"} replaced with
* the corresponding argument value from {@code args}; or, if the placeholder and argument counts
* do not match, returns a best-effort form of that string. Will not throw an exception under
* normal conditions.
*
* <p><b>Note:</b> For most string-formatting needs, use {@link String#format String.format},
* {@link java.io.PrintWriter#format PrintWriter.format}, and related methods. These support the
* full range of <a
* href="https://docs.oracle.com/javase/9/docs/api/java/util/Formatter.html#syntax">format
* specifiers</a>, and alert you to usage errors by throwing {@link
* java.util.IllegalFormatException}.
*
* <p>In certain cases, such as outputting debugging information or constructing a message to be
* used for another unchecked exception, an exception during string formatting would serve little
* purpose except to supplant the real information you were trying to provide. These are the cases
* this method is made for; it instead generates a best-effort string with all supplied argument
* values present. This method is also useful in environments such as GWT where {@code
* String.format} is not available. As an example, method implementations of the {@link
* Preconditions} class use this formatter, for both of the reasons just discussed.
*
* <p><b>Warning:</b> Only the exact two-character placeholder sequence {@code "%s"} is
* recognized.
*
* @param template a string containing zero or more {@code "%s"} placeholder sequences. {@code
* null} is treated as the four-character string {@code "null"}.
* @param args the arguments to be substituted into the message template. The first argument
* specified is substituted for the first occurrence of {@code "%s"} in the template, and so
* forth. A {@code null} argument is converted to the four-character string {@code "null"};
* non-null values are converted to strings using {@link Object#toString()}.
* @since 25.1
*/
// TODO(diamondm) consider using Arrays.toString() for array parameters
public static String lenientFormat(
@Nullable String template, @Nullable Object @Nullable ... args) {
template = String.valueOf(template); // null -> "null"
if (args == null) {
args = new Object[] {"(Object[])null"};
} else {
for (int i = 0; i < args.length; i++) {
args[i] = lenientToString(args[i]);
}
}
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template, templateStart, placeholderStart);
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template, templateStart, template.length());
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
private static String lenientToString(@Nullable Object o) {
try {
return String.valueOf(o);
} catch (Exception e) {
// Default toString() behavior - see Object.toString()
String objectToString =
o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o));
// TODO? Logger is created inline with fixed name to avoid forcing Proguard to create another class.
log.warn("Exception during lenientFormat for " + objectToString, e);
return "<" + objectToString + " threw " + e.getClass().getName() + ">";
}
}
}
@@ -0,0 +1,51 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
/**
* Legacy version of {@link java.util.function.Supplier java.util.function.Supplier}. Semantically,
* this could be a factory, generator, builder, closure, or something else entirely. No guarantees
* are implied by this interface.
*
* <p>The {@link Suppliers} class provides common suppliers and related utilities.
*
* <p>As this interface extends {@code java.util.function.Supplier}, an instance of this type can be
* used as a {@code java.util.function.Supplier} directly. To use a {@code
* java.util.function.Supplier} in a context where a {@code org.docx4j.com.google.common.base.Supplier} is
* needed, use {@code supplier::get}.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/FunctionalExplained">the use of {@code Function}</a>.
*
* @author Harry Heymann
* @since 2.0
*/
@GwtCompatible
@FunctionalInterface
public interface Supplier<T> extends java.util.function.Supplier<T> {
/**
* Retrieves an instance of the appropriate type. The returned object may or may not be a new
* instance, depending on the implementation.
*
* @return an instance of the appropriate type
*/
@CanIgnoreReturnValue
@Override
T get();
}
@@ -0,0 +1,365 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import static org.docx4j.com.google.common.base.Preconditions.checkArgument;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.annotations.VisibleForTesting;
/**
* Useful suppliers.
*
* <p>All methods return serializable suppliers as long as they're given serializable parameters.
*
* @author Laurence Gonsalves
* @author Harry Heymann
* @since 2.0
*/
@GwtCompatible
public final class Suppliers {
private Suppliers() {}
/**
* Returns a new supplier which is the composition of the provided function and supplier. In other
* words, the new supplier's value will be computed by retrieving the value from {@code supplier},
* and then applying {@code function} to that value. Note that the resulting supplier will not
* call {@code supplier} or invoke {@code function} until it is called.
*/
public static <F, T> Supplier<T> compose(Function<? super F, T> function, Supplier<F> supplier) {
return new SupplierComposition<>(function, supplier);
}
private static class SupplierComposition<F, T> implements Supplier<T>, Serializable {
final Function<? super F, T> function;
final Supplier<F> supplier;
SupplierComposition(Function<? super F, T> function, Supplier<F> supplier) {
this.function = checkNotNull(function);
this.supplier = checkNotNull(supplier);
}
@Override
public T get() {
return function.apply(supplier.get());
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof SupplierComposition) {
SupplierComposition<?, ?> that = (SupplierComposition<?, ?>) obj;
return function.equals(that.function) && supplier.equals(that.supplier);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(function, supplier);
}
@Override
public String toString() {
return "Suppliers.compose(" + function + ", " + supplier + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a supplier which caches the instance retrieved during the first call to {@code get()}
* and returns that value on subsequent calls to {@code get()}. See: <a
* href="http://en.wikipedia.org/wiki/Memoization">memoization</a>
*
* <p>The returned supplier is thread-safe. The delegate's {@code get()} method will be invoked at
* most once unless the underlying {@code get()} throws an exception. The supplier's serialized
* form does not contain the cached value, which will be recalculated when {@code get()} is called
* on the reserialized instance.
*
* <p>When the underlying delegate throws an exception then this memoizing supplier will keep
* delegating calls until it returns valid data.
*
* <p>If {@code delegate} is an instance created by an earlier call to {@code memoize}, it is
* returned directly.
*/
public static <T> Supplier<T> memoize(Supplier<T> delegate) {
if (delegate instanceof NonSerializableMemoizingSupplier
|| delegate instanceof MemoizingSupplier) {
return delegate;
}
return delegate instanceof Serializable
? new MemoizingSupplier<T>(delegate)
: new NonSerializableMemoizingSupplier<T>(delegate);
}
@VisibleForTesting
static class MemoizingSupplier<T> implements Supplier<T>, Serializable {
final Supplier<T> delegate;
transient volatile boolean initialized;
// "value" does not need to be volatile; visibility piggy-backs
// on volatile read of "initialized".
transient @Nullable T value;
MemoizingSupplier(Supplier<T> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override
public T get() {
// A 2-field variant of Double Checked Locking.
if (!initialized) {
synchronized (this) {
if (!initialized) {
T t = delegate.get();
value = t;
initialized = true;
return t;
}
}
}
return value;
}
@Override
public String toString() {
return "Suppliers.memoize("
+ (initialized ? "<supplier that returned " + value + ">" : delegate)
+ ")";
}
private static final long serialVersionUID = 0;
}
@VisibleForTesting
static class NonSerializableMemoizingSupplier<T> implements Supplier<T> {
volatile Supplier<T> delegate;
volatile boolean initialized;
// "value" does not need to be volatile; visibility piggy-backs
// on volatile read of "initialized".
@Nullable T value;
NonSerializableMemoizingSupplier(Supplier<T> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override
public T get() {
// A 2-field variant of Double Checked Locking.
if (!initialized) {
synchronized (this) {
if (!initialized) {
T t = delegate.get();
value = t;
initialized = true;
// Release the delegate to GC.
delegate = null;
return t;
}
}
}
return value;
}
@Override
public String toString() {
Supplier<T> delegate = this.delegate;
return "Suppliers.memoize("
+ (delegate == null ? "<supplier that returned " + value + ">" : delegate)
+ ")";
}
}
/**
* Returns a supplier that caches the instance supplied by the delegate and removes the cached
* value after the specified time has passed. Subsequent calls to {@code get()} return the cached
* value if the expiration time has not passed. After the expiration time, a new value is
* retrieved, cached, and returned. See: <a
* href="http://en.wikipedia.org/wiki/Memoization">memoization</a>
*
* <p>The returned supplier is thread-safe. The supplier's serialized form does not contain the
* cached value, which will be recalculated when {@code get()} is called on the reserialized
* instance. The actual memoization does not happen when the underlying delegate throws an
* exception.
*
* <p>When the underlying delegate throws an exception then this memoizing supplier will keep
* delegating calls until it returns valid data.
*
* @param duration the length of time after a value is created that it should stop being returned
* by subsequent {@code get()} calls
* @param unit the unit that {@code duration} is expressed in
* @throws IllegalArgumentException if {@code duration} is not positive
* @since 2.0
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static <T> Supplier<T> memoizeWithExpiration(
Supplier<T> delegate, long duration, TimeUnit unit) {
return new ExpiringMemoizingSupplier<T>(delegate, duration, unit);
}
@VisibleForTesting
@SuppressWarnings("GoodTime") // lots of violations
static class ExpiringMemoizingSupplier<T> implements Supplier<T>, Serializable {
final Supplier<T> delegate;
final long durationNanos;
transient volatile @Nullable T value;
// The special value 0 means "not yet initialized".
transient volatile long expirationNanos;
ExpiringMemoizingSupplier(Supplier<T> delegate, long duration, TimeUnit unit) {
this.delegate = checkNotNull(delegate);
this.durationNanos = unit.toNanos(duration);
checkArgument(duration > 0, "duration (%s %s) must be > 0", duration, unit);
}
@Override
public T get() {
// Another variant of Double Checked Locking.
//
// We use two volatile reads. We could reduce this to one by
// putting our fields into a holder class, but (at least on x86)
// the extra memory consumption and indirection are more
// expensive than the extra volatile reads.
long nanos = expirationNanos;
long now = Platform.systemNanoTime();
if (nanos == 0 || now - nanos >= 0) {
synchronized (this) {
if (nanos == expirationNanos) { // recheck for lost race
T t = delegate.get();
value = t;
nanos = now + durationNanos;
// In the very unlikely event that nanos is 0, set it to 1;
// no one will notice 1 ns of tardiness.
expirationNanos = (nanos == 0) ? 1 : nanos;
return t;
}
}
}
return value;
}
@Override
public String toString() {
// This is a little strange if the unit the user provided was not NANOS,
// but we don't want to store the unit just for toString
return "Suppliers.memoizeWithExpiration(" + delegate + ", " + durationNanos + ", NANOS)";
}
private static final long serialVersionUID = 0;
}
/** Returns a supplier that always supplies {@code instance}. */
public static <T> Supplier<T> ofInstance(@Nullable T instance) {
return new SupplierOfInstance<T>(instance);
}
private static class SupplierOfInstance<T> implements Supplier<T>, Serializable {
final @Nullable T instance;
SupplierOfInstance(@Nullable T instance) {
this.instance = instance;
}
@Override
public T get() {
return instance;
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof SupplierOfInstance) {
SupplierOfInstance<?> that = (SupplierOfInstance<?>) obj;
return Objects.equal(instance, that.instance);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(instance);
}
@Override
public String toString() {
return "Suppliers.ofInstance(" + instance + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a supplier whose {@code get()} method synchronizes on {@code delegate} before calling
* it, making it thread-safe.
*/
public static <T> Supplier<T> synchronizedSupplier(Supplier<T> delegate) {
return new ThreadSafeSupplier<T>(delegate);
}
private static class ThreadSafeSupplier<T> implements Supplier<T>, Serializable {
final Supplier<T> delegate;
ThreadSafeSupplier(Supplier<T> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override
public T get() {
synchronized (delegate) {
return delegate.get();
}
}
@Override
public String toString() {
return "Suppliers.synchronizedSupplier(" + delegate + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a function that accepts a supplier and returns the result of invoking {@link
* Supplier#get} on that supplier.
*
* <p><b>Java 8 users:</b> use the method reference {@code Supplier::get} instead.
*
* @since 8.0
*/
public static <T> Function<Supplier<T>, T> supplierFunction() {
@SuppressWarnings("unchecked") // implementation is "fully variant"
SupplierFunction<T> sf = (SupplierFunction<T>) SupplierFunctionImpl.INSTANCE;
return sf;
}
private interface SupplierFunction<T> extends Function<Supplier<T>, T> {}
private enum SupplierFunctionImpl implements SupplierFunction<Object> {
INSTANCE;
// Note: This makes T a "pass-through type"
@Override
public Object apply(Supplier<Object> input) {
return input.get();
}
@Override
public String toString() {
return "Suppliers.supplierFunction()";
}
}
}
@@ -0,0 +1,541 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.Beta;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.annotations.GwtIncompatible;
import org.docx4j.com.google.common.annotations.VisibleForTesting;
/**
* Static utility methods pertaining to instances of {@link Throwable}.
*
* <p>See the Guava User Guide entry on <a
* href="https://github.com/google/guava/wiki/ThrowablesExplained">Throwables</a>.
*
* @author Kevin Bourrillion
* @author Ben Yu
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Throwables {
private Throwables() {}
/**
* Throws {@code throwable} if it is an instance of {@code declaredType}. Example usage:
*
* <pre>
* for (Foo foo : foos) {
* try {
* foo.bar();
* } catch (BarException | RuntimeException | Error t) {
* failure = t;
* }
* }
* if (failure != null) {
* throwIfInstanceOf(failure, BarException.class);
* throwIfUnchecked(failure);
* throw new AssertionError(failure);
* }
* </pre>
*
* @since 20.0
*/
@GwtIncompatible // Class.cast, Class.isInstance
public static <X extends Throwable> void throwIfInstanceOf(
Throwable throwable, Class<X> declaredType) throws X {
checkNotNull(throwable);
if (declaredType.isInstance(throwable)) {
throw declaredType.cast(throwable);
}
}
/**
* Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@code
* declaredType}. Example usage:
*
* <pre>
* try {
* someMethodThatCouldThrowAnything();
* } catch (IKnowWhatToDoWithThisException e) {
* handle(e);
* } catch (Throwable t) {
* Throwables.propagateIfInstanceOf(t, IOException.class);
* Throwables.propagateIfInstanceOf(t, SQLException.class);
* throw Throwables.propagate(t);
* }
* </pre>
*
* @deprecated Use {@link #throwIfInstanceOf}, which has the same behavior but rejects {@code
* null}.
*/
@Deprecated
@GwtIncompatible // throwIfInstanceOf
public static <X extends Throwable> void propagateIfInstanceOf(
@Nullable Throwable throwable, Class<X> declaredType) throws X {
if (throwable != null) {
throwIfInstanceOf(throwable, declaredType);
}
}
/**
* Throws {@code throwable} if it is a {@link RuntimeException} or {@link Error}. Example usage:
*
* <pre>
* for (Foo foo : foos) {
* try {
* foo.bar();
* } catch (RuntimeException | Error t) {
* failure = t;
* }
* }
* if (failure != null) {
* throwIfUnchecked(failure);
* throw new AssertionError(failure);
* }
* </pre>
*
* @since 20.0
*/
public static void throwIfUnchecked(Throwable throwable) {
checkNotNull(throwable);
if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
}
if (throwable instanceof Error) {
throw (Error) throwable;
}
}
/**
* Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
* RuntimeException} or {@link Error}. Example usage:
*
* <pre>
* try {
* someMethodThatCouldThrowAnything();
* } catch (IKnowWhatToDoWithThisException e) {
* handle(e);
* } catch (Throwable t) {
* Throwables.propagateIfPossible(t);
* throw new RuntimeException("unexpected", t);
* }
* </pre>
*
* @deprecated Use {@link #throwIfUnchecked}, which has the same behavior but rejects {@code
* null}.
*/
@Deprecated
@GwtIncompatible
public static void propagateIfPossible(@Nullable Throwable throwable) {
if (throwable != null) {
throwIfUnchecked(throwable);
}
}
/**
* Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
* RuntimeException}, {@link Error}, or {@code declaredType}. Example usage:
*
* <pre>
* try {
* someMethodThatCouldThrowAnything();
* } catch (IKnowWhatToDoWithThisException e) {
* handle(e);
* } catch (Throwable t) {
* Throwables.propagateIfPossible(t, OtherException.class);
* throw new RuntimeException("unexpected", t);
* }
* </pre>
*
* @param throwable the Throwable to possibly propagate
* @param declaredType the single checked exception type declared by the calling method
*/
@GwtIncompatible // propagateIfInstanceOf
public static <X extends Throwable> void propagateIfPossible(
@Nullable Throwable throwable, Class<X> declaredType) throws X {
propagateIfInstanceOf(throwable, declaredType);
propagateIfPossible(throwable);
}
/**
* Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
* RuntimeException}, {@link Error}, {@code declaredType1}, or {@code declaredType2}. In the
* unlikely case that you have three or more declared checked exception types, you can handle them
* all by invoking these methods repeatedly. See usage example in {@link
* #propagateIfPossible(Throwable, Class)}.
*
* @param throwable the Throwable to possibly propagate
* @param declaredType1 any checked exception type declared by the calling method
* @param declaredType2 any other checked exception type declared by the calling method
*/
@GwtIncompatible // propagateIfInstanceOf
public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible(
@Nullable Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2)
throws X1, X2 {
checkNotNull(declaredType2);
propagateIfInstanceOf(throwable, declaredType1);
propagateIfPossible(throwable, declaredType2);
}
/**
* Propagates {@code throwable} as-is if it is an instance of {@link RuntimeException} or {@link
* Error}, or else as a last resort, wraps it in a {@code RuntimeException} and then propagates.
*
* <p>This method always throws an exception. The {@code RuntimeException} return type allows
* client code to signal to the compiler that statements after the call are unreachable. Example
* usage:
*
* <pre>
* T doSomething() {
* try {
* return someMethodThatCouldThrowAnything();
* } catch (IKnowWhatToDoWithThisException e) {
* return handle(e);
* } catch (Throwable t) {
* throw Throwables.propagate(t);
* }
* }
* </pre>
*
* @param throwable the Throwable to propagate
* @return nothing will ever be returned; this return type is only for your convenience, as
* illustrated in the example above
* @deprecated Use {@code throw e} or {@code throw new RuntimeException(e)} directly, or use a
* combination of {@link #throwIfUnchecked} and {@code throw new RuntimeException(e)}. For
* background on the deprecation, read <a href="https://goo.gl/Ivn2kc">Why we deprecated
* {@code Throwables.propagate}</a>.
*/
@CanIgnoreReturnValue
@GwtIncompatible
@Deprecated
public static RuntimeException propagate(Throwable throwable) {
throwIfUnchecked(throwable);
throw new RuntimeException(throwable);
}
/**
* Returns the innermost cause of {@code throwable}. The first throwable in a chain provides
* context from when the error or exception was initially detected. Example usage:
*
* <pre>
* assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage());
* </pre>
*
* @throws IllegalArgumentException if there is a loop in the causal chain
*/
public static Throwable getRootCause(Throwable throwable) {
// Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches
// the slower pointer, then there's a loop.
Throwable slowPointer = throwable;
boolean advanceSlowPointer = false;
Throwable cause;
while ((cause = throwable.getCause()) != null) {
throwable = cause;
if (throwable == slowPointer) {
throw new IllegalArgumentException("Loop in causal chain detected.", throwable);
}
if (advanceSlowPointer) {
slowPointer = slowPointer.getCause();
}
advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration
}
return throwable;
}
/**
* Gets a {@code Throwable} cause chain as a list. The first entry in the list will be {@code
* throwable} followed by its cause hierarchy. Note that this is a snapshot of the cause chain and
* will not reflect any subsequent changes to the cause chain.
*
* <p>Here's an example of how it can be used to find specific types of exceptions in the cause
* chain:
*
* <pre>
* Iterables.filter(Throwables.getCausalChain(e), IOException.class));
* </pre>
*
* @param throwable the non-null {@code Throwable} to extract causes from
* @return an unmodifiable list containing the cause chain starting with {@code throwable}
* @throws IllegalArgumentException if there is a loop in the causal chain
*/
@Beta // TODO(kevinb): decide best return type
public static List<Throwable> getCausalChain(Throwable throwable) {
checkNotNull(throwable);
List<Throwable> causes = new ArrayList<>(4);
causes.add(throwable);
// Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches
// the slower pointer, then there's a loop.
Throwable slowPointer = throwable;
boolean advanceSlowPointer = false;
Throwable cause;
while ((cause = throwable.getCause()) != null) {
throwable = cause;
causes.add(throwable);
if (throwable == slowPointer) {
throw new IllegalArgumentException("Loop in causal chain detected.", throwable);
}
if (advanceSlowPointer) {
slowPointer = slowPointer.getCause();
}
advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration
}
return Collections.unmodifiableList(causes);
}
/**
* Returns {@code throwable}'s cause, cast to {@code expectedCauseType}.
*
* <p>Prefer this method instead of manually casting an exception's cause. For example, {@code
* (IOException) e.getCause()} throws a {@link ClassCastException} that discards the original
* exception {@code e} if the cause is not an {@link IOException}, but {@code
* Throwables.getCauseAs(e, IOException.class)} keeps {@code e} as the {@link
* ClassCastException}'s cause.
*
* @throws ClassCastException if the cause cannot be cast to the expected type. The {@code
* ClassCastException}'s cause is {@code throwable}.
* @since 22.0
*/
@Beta
@GwtIncompatible // Class.cast(Object)
public static <X extends Throwable> X getCauseAs(
Throwable throwable, Class<X> expectedCauseType) {
try {
return expectedCauseType.cast(throwable.getCause());
} catch (ClassCastException e) {
e.initCause(throwable);
throw e;
}
}
/**
* Returns a string containing the result of {@link Throwable#toString() toString()}, followed by
* the full, recursive stack trace of {@code throwable}. Note that you probably should not be
* parsing the resulting string; if you need programmatic access to the stack frames, you can call
* {@link Throwable#getStackTrace()}.
*/
@GwtIncompatible // java.io.PrintWriter, java.io.StringWriter
public static String getStackTraceAsString(Throwable throwable) {
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
/**
* Returns the stack trace of {@code throwable}, possibly providing slower iteration over the full
* trace but faster iteration over parts of the trace. Here, "slower" and "faster" are defined in
* comparison to the normal way to access the stack trace, {@link Throwable#getStackTrace()
* throwable.getStackTrace()}. Note, however, that this method's special implementation is not
* available for all platforms and configurations. If that implementation is unavailable, this
* method falls back to {@code getStackTrace}. Callers that require the special implementation can
* check its availability with {@link #lazyStackTraceIsLazy()}.
*
* <p>The expected (but not guaranteed) performance of the special implementation differs from
* {@code getStackTrace} in one main way: The {@code lazyStackTrace} call itself returns quickly
* by delaying the per-stack-frame work until each element is accessed. Roughly speaking:
*
* <ul>
* <li>{@code getStackTrace} takes {@code stackSize} time to return but then negligible time to
* retrieve each element of the returned list.
* <li>{@code lazyStackTrace} takes negligible time to return but then {@code 1/stackSize} time
* to retrieve each element of the returned list (probably slightly more than {@code
* 1/stackSize}).
* </ul>
*
* <p>Note: The special implementation does not respect calls to {@link Throwable#setStackTrace
* throwable.setStackTrace}. Instead, it always reflects the original stack trace from the
* exception's creation.
*
* @since 19.0
*/
// TODO(cpovirk): Say something about the possibility that List access could fail at runtime?
@Beta
@GwtIncompatible // lazyStackTraceIsLazy, jlaStackTrace
// TODO(cpovirk): Consider making this available under GWT (slow implementation only).
public static List<StackTraceElement> lazyStackTrace(Throwable throwable) {
return lazyStackTraceIsLazy()
? jlaStackTrace(throwable)
: unmodifiableList(asList(throwable.getStackTrace()));
}
/**
* Returns whether {@link #lazyStackTrace} will use the special implementation described in its
* documentation.
*
* @since 19.0
*/
@Beta
@GwtIncompatible // getStackTraceElementMethod
public static boolean lazyStackTraceIsLazy() {
return getStackTraceElementMethod != null && getStackTraceDepthMethod != null;
}
@GwtIncompatible // invokeAccessibleNonThrowingMethod
private static List<StackTraceElement> jlaStackTrace(final Throwable t) {
checkNotNull(t);
/*
* TODO(cpovirk): Consider optimizing iterator() to catch IOOBE instead of doing bounds checks.
*
* TODO(cpovirk): Consider the UnsignedBytes pattern if it performs faster and doesn't cause
* AOSP grief.
*/
return new AbstractList<StackTraceElement>() {
@Override
public StackTraceElement get(int n) {
return (StackTraceElement)
invokeAccessibleNonThrowingMethod(getStackTraceElementMethod, jla, t, n);
}
@Override
public int size() {
return (Integer) invokeAccessibleNonThrowingMethod(getStackTraceDepthMethod, jla, t);
}
};
}
@GwtIncompatible // java.lang.reflect
private static Object invokeAccessibleNonThrowingMethod(
Method method, Object receiver, Object... params) {
try {
return method.invoke(receiver, params);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw propagate(e.getCause());
}
}
/** JavaLangAccess class name to load using reflection */
@GwtIncompatible // not used by GWT emulation
private static final String JAVA_LANG_ACCESS_CLASSNAME = "sun.misc.JavaLangAccess";
/** SharedSecrets class name to load using reflection */
@GwtIncompatible // not used by GWT emulation
@VisibleForTesting
static final String SHARED_SECRETS_CLASSNAME = "sun.misc.SharedSecrets";
/** Access to some fancy internal JVM internals. */
@GwtIncompatible // java.lang.reflect
private static final @Nullable Object jla = getJLA();
/**
* The "getStackTraceElementMethod" method, only available on some JDKs so we use reflection to
* find it when available. When this is null, use the slow way.
*/
@GwtIncompatible // java.lang.reflect
private static final @Nullable Method getStackTraceElementMethod =
(jla == null) ? null : getGetMethod();
/**
* The "getStackTraceDepth" method, only available on some JDKs so we use reflection to find it
* when available. When this is null, use the slow way.
*/
@GwtIncompatible // java.lang.reflect
private static final @Nullable Method getStackTraceDepthMethod =
(jla == null) ? null : getSizeMethod();
/**
* Returns the JavaLangAccess class that is present in all Sun JDKs. It is not allowed in
* AppEngine, and not present in non-Sun JDKs.
*/
@GwtIncompatible // java.lang.reflect
private static @Nullable Object getJLA() {
try {
/*
* We load sun.misc.* classes using reflection since Android doesn't support these classes and
* would result in compilation failure if we directly refer to these classes.
*/
Class<?> sharedSecrets = Class.forName(SHARED_SECRETS_CLASSNAME, false, null);
Method langAccess = sharedSecrets.getMethod("getJavaLangAccess");
return langAccess.invoke(null);
} catch (ThreadDeath death) {
throw death;
} catch (Throwable t) {
/*
* This is not one of AppEngine's allowed classes, so even in Sun JDKs, this can fail with
* a NoClassDefFoundError. Other apps might deny access to sun.misc packages.
*/
return null;
}
}
/**
* Returns the Method that can be used to resolve an individual StackTraceElement, or null if that
* method cannot be found (it is only to be found in fairly recent JDKs).
*/
@GwtIncompatible // java.lang.reflect
private static @Nullable Method getGetMethod() {
return getJlaMethod("getStackTraceElement", Throwable.class, int.class);
}
/**
* Returns the Method that can be used to return the size of a stack, or null if that method
* cannot be found (it is only to be found in fairly recent JDKs). Tries to test method {@link
* sun.misc.JavaLangAccess#getStackTraceDepth(Throwable)} getStackTraceDepth} prior to return it
* (might fail some JDKs).
*
* <p>See <a href="https://github.com/google/guava/issues/2887">Throwables#lazyStackTrace throws
* UnsupportedOperationException</a>.
*/
@GwtIncompatible // java.lang.reflect
private static @Nullable Method getSizeMethod() {
try {
Method getStackTraceDepth = getJlaMethod("getStackTraceDepth", Throwable.class);
if (getStackTraceDepth == null) {
return null;
}
getStackTraceDepth.invoke(getJLA(), new Throwable());
return getStackTraceDepth;
} catch (UnsupportedOperationException | IllegalAccessException | InvocationTargetException e) {
return null;
}
}
@GwtIncompatible // java.lang.reflect
private static @Nullable Method getJlaMethod(String name, Class<?>... parameterTypes)
throws ThreadDeath {
try {
return Class.forName(JAVA_LANG_ACCESS_CLASSNAME, false, null).getMethod(name, parameterTypes);
} catch (ThreadDeath death) {
throw death;
} catch (Throwable t) {
/*
* Either the JavaLangAccess class itself is not found, or the method is not supported on the
* JVM.
*/
return null;
}
}
}
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.base;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* A time source; returns a time value representing the number of nanoseconds elapsed since some
* fixed but arbitrary point in time. Note that most users should use {@link Stopwatch} instead of
* interacting with this class directly.
*
* <p><b>Warning:</b> this interface can only be used to measure elapsed time, not wall time.
*
* @author Kevin Bourrillion
* @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly
* source-compatible</a> since 9.0)
*/
@GwtCompatible
public abstract class Ticker {
/** Constructor for use by subclasses. */
protected Ticker() {}
/** Returns the number of nanoseconds elapsed since this ticker's fixed point of reference. */
public abstract long read();
/**
* A ticker that reads the current time using {@link System#nanoTime}.
*
* @since 10.0
*/
public static Ticker systemTicker() {
return SYSTEM_TICKER;
}
private static final Ticker SYSTEM_TICKER =
new Ticker() {
@Override
public long read() {
return Platform.systemNanoTime();
}
};
}
@@ -0,0 +1,261 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.collect.ImmutableMap;
import org.docx4j.com.google.common.collect.Maps;
/**
* This class provides a skeletal implementation of the {@code Cache} interface to minimize the
* effort required to implement this interface.
*
* <p>To implement a cache, the programmer needs only to extend this class and provide an
* implementation for the {@link #put} and {@link #getIfPresent} methods. {@link #getAllPresent} is
* implemented in terms of {@link #getIfPresent}; {@link #putAll} is implemented in terms of {@link
* #put}, {@link #invalidateAll(Iterable)} is implemented in terms of {@link #invalidate}. The
* method {@link #cleanUp} is a no-op. All other methods throw an {@link
* UnsupportedOperationException}.
*
* @author Charles Fry
* @since 10.0
*/
@GwtCompatible
public abstract class AbstractCache<K, V> implements Cache<K, V> {
/** Constructor for use by subclasses. */
protected AbstractCache() {}
/** @since 11.0 */
@Override
public V get(K key, Callable<? extends V> valueLoader) throws ExecutionException {
throw new UnsupportedOperationException();
}
// /**
// * {@inheritDoc}
// *
// * <p>This implementation of {@code getAllPresent} lacks any insight into the internal cache data
// * structure, and is thus forced to return the query keys instead of the cached keys. This is only
// * possible with an unsafe cast which requires {@code keys} to actually be of type {@code K}.
// *
// * @since 11.0
// */
// @Override
// public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) {
// Map<K, V> result = Maps.newLinkedHashMap();
// for (Object key : keys) {
// if (!result.containsKey(key)) {
// @SuppressWarnings("unchecked")
// K castKey = (K) key;
// V value = getIfPresent(key);
// if (value != null) {
// result.put(castKey, value);
// }
// }
// }
// return ImmutableMap.copyOf(result);
// }
/** @since 11.0 */
@Override
public void put(K key, V value) {
throw new UnsupportedOperationException();
}
/** @since 12.0 */
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void cleanUp() {}
@Override
public long size() {
throw new UnsupportedOperationException();
}
@Override
public void invalidate(Object key) {
throw new UnsupportedOperationException();
}
/** @since 11.0 */
@Override
public void invalidateAll(Iterable<?> keys) {
for (Object key : keys) {
invalidate(key);
}
}
@Override
public void invalidateAll() {
throw new UnsupportedOperationException();
}
@Override
public CacheStats stats() {
throw new UnsupportedOperationException();
}
@Override
public ConcurrentMap<K, V> asMap() {
throw new UnsupportedOperationException();
}
/**
* Accumulates statistics during the operation of a {@link Cache} for presentation by {@link
* Cache#stats}. This is solely intended for consumption by {@code Cache} implementors.
*
* @since 10.0
*/
public interface StatsCounter {
/**
* Records cache hits. This should be called when a cache request returns a cached value.
*
* @param count the number of hits to record
* @since 11.0
*/
void recordHits(int count);
/**
* Records cache misses. This should be called when a cache request returns a value that was not
* found in the cache. This method should be called by the loading thread, as well as by threads
* blocking on the load. Multiple concurrent calls to {@link Cache} lookup methods with the same
* key on an absent value should result in a single call to either {@code recordLoadSuccess} or
* {@code recordLoadException} and multiple calls to this method, despite all being served by
* the results of a single load operation.
*
* @param count the number of misses to record
* @since 11.0
*/
void recordMisses(int count);
/**
* Records the successful load of a new entry. This should be called when a cache request causes
* an entry to be loaded, and the loading completes successfully. In contrast to {@link
* #recordMisses}, this method should only be called by the loading thread.
*
* @param loadTime the number of nanoseconds the cache spent computing or retrieving the new
* value
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
void recordLoadSuccess(long loadTime);
/**
* Records the failed load of a new entry. This should be called when a cache request causes an
* entry to be loaded, but an exception is thrown while loading the entry. In contrast to {@link
* #recordMisses}, this method should only be called by the loading thread.
*
* @param loadTime the number of nanoseconds the cache spent computing or retrieving the new
* value prior to an exception being thrown
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
void recordLoadException(long loadTime);
/**
* Records the eviction of an entry from the cache. This should only been called when an entry
* is evicted due to the cache's eviction strategy, and not as a result of manual {@linkplain
* Cache#invalidate invalidations}.
*/
void recordEviction();
/**
* Returns a snapshot of this counter's values. Note that this may be an inconsistent view, as
* it may be interleaved with update operations.
*/
CacheStats snapshot();
}
/**
* A thread-safe {@link StatsCounter} implementation for use by {@link Cache} implementors.
*
* @since 10.0
*/
public static final class SimpleStatsCounter implements StatsCounter {
private final LongAddable hitCount = LongAddables.create();
private final LongAddable missCount = LongAddables.create();
private final LongAddable loadSuccessCount = LongAddables.create();
private final LongAddable loadExceptionCount = LongAddables.create();
private final LongAddable totalLoadTime = LongAddables.create();
private final LongAddable evictionCount = LongAddables.create();
/** Constructs an instance with all counts initialized to zero. */
public SimpleStatsCounter() {}
/** @since 11.0 */
@Override
public void recordHits(int count) {
hitCount.add(count);
}
/** @since 11.0 */
@Override
public void recordMisses(int count) {
missCount.add(count);
}
@SuppressWarnings("GoodTime") // b/122668874
@Override
public void recordLoadSuccess(long loadTime) {
loadSuccessCount.increment();
totalLoadTime.add(loadTime);
}
@SuppressWarnings("GoodTime") // b/122668874
@Override
public void recordLoadException(long loadTime) {
loadExceptionCount.increment();
totalLoadTime.add(loadTime);
}
@Override
public void recordEviction() {
evictionCount.increment();
}
@Override
public CacheStats snapshot() {
return new CacheStats(
hitCount.sum(),
missCount.sum(),
loadSuccessCount.sum(),
loadExceptionCount.sum(),
totalLoadTime.sum(),
evictionCount.sum());
}
/** Increments all counters by the values in {@code other}. */
public void incrementBy(StatsCounter other) {
CacheStats otherStats = other.snapshot();
hitCount.add(otherStats.hitCount());
missCount.add(otherStats.missCount());
loadSuccessCount.add(otherStats.loadSuccessCount());
loadExceptionCount.add(otherStats.loadExceptionCount());
totalLoadTime.add(otherStats.totalLoadTime());
evictionCount.add(otherStats.evictionCount());
}
}
}
@@ -0,0 +1,172 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import com.google.errorprone.annotations.CompatibleWith;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.collect.ImmutableMap;
import org.docx4j.com.google.common.util.concurrent.ExecutionError;
import org.docx4j.com.google.common.util.concurrent.UncheckedExecutionException;
/**
* A semi-persistent mapping from keys to values. Cache entries are manually added using {@link
* #get(Object, Callable)} or {@link #put(Object, Object)}, and are stored in the cache until either
* evicted or manually invalidated. The common way to build instances is using {@link CacheBuilder}.
*
* <p>Implementations of this interface are expected to be thread-safe, and can be safely accessed
* by multiple concurrent threads.
*
* @author Charles Fry
* @since 10.0
*/
@GwtCompatible
public interface Cache<K, V> {
/**
* Returns the value associated with {@code key} in this cache, or {@code null} if there is no
* cached value for {@code key}.
*
* @since 11.0
*/
@Nullable
V getIfPresent(@CompatibleWith("K") Object key);
/**
* Returns the value associated with {@code key} in this cache, obtaining that value from {@code
* loader} if necessary. The method improves upon the conventional "if cached, return; otherwise
* create, cache and return" pattern. For further improvements, use {@link LoadingCache} and its
* {@link LoadingCache#get(Object) get(K)} method instead of this one.
*
* <p>Among the improvements that this method and {@code LoadingCache.get(K)} both provide are:
*
* <ul>
* <li>{@linkplain LoadingCache#get(Object) awaiting the result of a pending load} rather than
* starting a redundant one
* <li>eliminating the error-prone caching boilerplate
* <li>tracking load {@linkplain #stats statistics}
* </ul>
*
* <p>Among the further improvements that {@code LoadingCache} can provide but this method cannot:
*
* <ul>
* <li>consolidation of the loader logic to {@linkplain CacheBuilder#build(CacheLoader) a single
* authoritative location}
* <li>{@linkplain LoadingCache#refresh refreshing of entries}, including {@linkplain
* CacheBuilder#refreshAfterWrite automated refreshing}
* <li>{@linkplain LoadingCache#getAll bulk loading requests}, including {@linkplain
* CacheLoader#loadAll bulk loading implementations}
* </ul>
*
* <p><b>Warning:</b> For any given key, every {@code loader} used with it should compute the same
* value. Otherwise, a call that passes one {@code loader} may return the result of another call
* with a differently behaving {@code loader}. For example, a call that requests a short timeout
* for an RPC may wait for a similar call that requests a long timeout, or a call by an
* unprivileged user may return a resource accessible only to a privileged user making a similar
* call. To prevent this problem, create a key object that includes all values that affect the
* result of the query. Or use {@code LoadingCache.get(K)}, which lacks the ability to refer to
* state other than that in the key.
*
* <p><b>Warning:</b> as with {@link CacheLoader#load}, {@code loader} <b>must not</b> return
* {@code null}; it may either return a non-null value or throw an exception.
*
* <p>No observable state associated with this cache is modified until loading completes.
*
* @throws ExecutionException if a checked exception was thrown while loading the value
* @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
* value
* @throws ExecutionError if an error was thrown while loading the value
* @since 11.0
*/
V get(K key, Callable<? extends V> loader) throws ExecutionException;
/**
* Returns a map of the values associated with {@code keys} in this cache. The returned map will
* only contain entries which are already present in the cache.
*
* @since 11.0
*/
ImmutableMap<K, V> getAllPresent(Iterable<?> keys);
/**
* Associates {@code value} with {@code key} in this cache. If the cache previously contained a
* value associated with {@code key}, the old value is replaced by {@code value}.
*
* <p>Prefer {@link #get(Object, Callable)} when using the conventional "if cached, return;
* otherwise create, cache and return" pattern.
*
* @since 11.0
*/
void put(K key, V value);
/**
* Copies all of the mappings from the specified map to the cache. The effect of this call is
* equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key
* {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined
* if the specified map is modified while the operation is in progress.
*
* @since 12.0
*/
void putAll(Map<? extends K, ? extends V> m);
/** Discards any cached value for key {@code key}. */
void invalidate(@CompatibleWith("K") Object key);
/**
* Discards any cached values for keys {@code keys}.
*
* @since 11.0
*/
void invalidateAll(Iterable<?> keys);
/** Discards all entries in the cache. */
void invalidateAll();
/** Returns the approximate number of entries in this cache. */
long size();
/**
* Returns a current snapshot of this cache's cumulative statistics, or a set of default values if
* the cache is not recording statistics. All statistics begin at zero and never decrease over the
* lifetime of the cache.
*
* <p><b>Warning:</b> this cache may not be recording statistical data. For example, a cache
* created using {@link CacheBuilder} only does so if the {@link CacheBuilder#recordStats} method
* was called. If statistics are not being recorded, a {@code CacheStats} instance with zero for
* all values is returned.
*
*/
CacheStats stats();
/**
* Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to
* the map directly affect the cache.
*
* <p>Iterators from the returned map are at least <i>weakly consistent</i>: they are safe for
* concurrent use, but if the cache is modified (including by eviction) after the iterator is
* created, it is undefined which of the changes (if any) will be reflected in that iterator.
*/
ConcurrentMap<K, V> asMap();
/**
* Performs any pending maintenance operations needed by the cache. Exactly which activities are
* performed -- if any -- is implementation-dependent.
*/
void cleanUp();
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,252 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
//import org.docx4j.com.google.common.util.concurrent.ListenableFutureTask;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.annotations.GwtIncompatible;
import org.docx4j.com.google.common.base.Function;
import org.docx4j.com.google.common.base.Supplier;
import org.docx4j.com.google.common.util.concurrent.Futures;
import org.docx4j.com.google.common.util.concurrent.ListenableFuture;
/**
* Computes or retrieves values, based on a key, for use in populating a {@link LoadingCache}.
*
* <p>Most implementations will only need to implement {@link #load}. Other methods may be
* overridden as desired.
*
* <p>Usage example:
*
* <pre>{@code
* CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() {
* public Graph load(Key key) throws AnyException {
* return createExpensiveGraph(key);
* }
* };
* LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader);
* }</pre>
*
* <p>Since this example doesn't support reloading or bulk loading, it can also be specified much
* more simply:
*
* <pre>{@code
* CacheLoader<Key, Graph> loader = CacheLoader.from(key -> createExpensiveGraph(key));
* }</pre>
*
* @author Charles Fry
* @since 10.0
*/
@GwtCompatible(emulated = true)
public abstract class CacheLoader<K, V> {
/** Constructor for use by subclasses. */
protected CacheLoader() {}
/**
* Computes or retrieves the value corresponding to {@code key}.
*
* @param key the non-null key whose value should be loaded
* @return the value associated with {@code key}; <b>must not be null</b>
* @throws Exception if unable to load the result
* @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
* treated like any other {@code Exception} in all respects except that, when it is caught,
* the thread's interrupt status is set
*/
public abstract V load(K key) throws Exception;
/**
* Computes or retrieves a replacement value corresponding to an already-cached {@code key}. This
* method is called when an existing cache entry is refreshed by {@link
* CacheBuilder#refreshAfterWrite}, or through a call to {@link LoadingCache#refresh}.
*
* <p>This implementation synchronously delegates to {@link #load}. It is recommended that it be
* overridden with an asynchronous implementation when using {@link
* CacheBuilder#refreshAfterWrite}.
*
* <p><b>Note:</b> <i>all exceptions thrown by this method will be logged and then swallowed</i>.
*
* @param key the non-null key whose value should be loaded
* @param oldValue the non-null old value corresponding to {@code key}
* @return the future new value associated with {@code key}; <b>must not be null, must not return
* null</b>
* @throws Exception if unable to reload the result
* @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
* treated like any other {@code Exception} in all respects except that, when it is caught,
* the thread's interrupt status is set
* @since 11.0
*/
@GwtIncompatible // Futures
public ListenableFuture<V> reload(K key, V oldValue) throws Exception {
checkNotNull(key);
checkNotNull(oldValue);
return Futures.immediateFuture(load(key));
}
/**
* Computes or retrieves the values corresponding to {@code keys}. This method is called by {@link
* LoadingCache#getAll}.
*
* <p>If the returned map doesn't contain all requested {@code keys} then the entries it does
* contain will be cached, but {@code getAll} will throw an exception. If the returned map
* contains extra keys not present in {@code keys} then all returned entries will be cached, but
* only the entries for {@code keys} will be returned from {@code getAll}.
*
* <p>This method should be overridden when bulk retrieval is significantly more efficient than
* many individual lookups. Note that {@link LoadingCache#getAll} will defer to individual calls
* to {@link LoadingCache#get} if this method is not overridden.
*
* @param keys the unique, non-null keys whose values should be loaded
* @return a map from each key in {@code keys} to the value associated with that key; <b>may not
* contain null values</b>
* @throws Exception if unable to load the result
* @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
* treated like any other {@code Exception} in all respects except that, when it is caught,
* the thread's interrupt status is set
* @since 11.0
*/
public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
// This will be caught by getAll(), causing it to fall back to multiple calls to
// LoadingCache.get
throw new UnsupportedLoadingOperationException();
}
/**
* Returns a cache loader that uses {@code function} to load keys, without supporting either
* reloading or bulk loading. This allows creating a cache loader using a lambda expression.
*
* @param function the function to be used for loading values; must never return {@code null}
* @return a cache loader that loads values by passing each key to {@code function}
*/
public static <K, V> CacheLoader<K, V> from(Function<K, V> function) {
return new FunctionToCacheLoader<>(function);
}
/**
* Returns a cache loader based on an <i>existing</i> supplier instance. Note that there's no need
* to create a <i>new</i> supplier just to pass it in here; just subclass {@code CacheLoader} and
* implement {@link #load load} instead.
*
* @param supplier the supplier to be used for loading values; must never return {@code null}
* @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the
* key
*/
public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) {
return new SupplierToCacheLoader<V>(supplier);
}
private static final class FunctionToCacheLoader<K, V> extends CacheLoader<K, V>
implements Serializable {
private final Function<K, V> computingFunction;
public FunctionToCacheLoader(Function<K, V> computingFunction) {
this.computingFunction = checkNotNull(computingFunction);
}
@Override
public V load(K key) {
return computingFunction.apply(checkNotNull(key));
}
private static final long serialVersionUID = 0;
}
// /**
// * Returns a {@code CacheLoader} which wraps {@code loader}, executing calls to {@link
// * CacheLoader#reload} using {@code executor}.
// *
// * <p>This method is useful only when {@code loader.reload} has a synchronous implementation, such
// * as {@linkplain #reload the default implementation}.
// *
// * @since 17.0
// */
// @GwtIncompatible // Executor + Futures
// public static <K, V> CacheLoader<K, V> asyncReloading(
// final CacheLoader<K, V> loader, final Executor executor) {
// checkNotNull(loader);
// checkNotNull(executor);
// return new CacheLoader<K, V>() {
// @Override
// public V load(K key) throws Exception {
// return loader.load(key);
// }
//
// @Override
// public ListenableFuture<V> reload(final K key, final V oldValue) throws Exception {
// ListenableFutureTask<V> task =
// ListenableFutureTask.create(
// new Callable<V>() {
// @Override
// public V call() throws Exception {
// return loader.reload(key, oldValue).get();
// }
// });
// executor.execute(task);
// return task;
// }
//
// @Override
// public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
// return loader.loadAll(keys);
// }
// };
// }
private static final class SupplierToCacheLoader<V> extends CacheLoader<Object, V>
implements Serializable {
private final Supplier<V> computingSupplier;
public SupplierToCacheLoader(Supplier<V> computingSupplier) {
this.computingSupplier = checkNotNull(computingSupplier);
}
@Override
public V load(Object key) {
checkNotNull(key);
return computingSupplier.get();
}
private static final long serialVersionUID = 0;
}
/**
* Exception thrown by {@code loadAll()} to indicate that it is not supported.
*
* @since 19.0
*/
public static final class UnsupportedLoadingOperationException
extends UnsupportedOperationException {
// Package-private because this should only be thrown by loadAll() when it is not overridden.
// Cache implementors may want to catch it but should not need to be able to throw it.
UnsupportedLoadingOperationException() {}
}
/**
* Thrown to indicate that an invalid response was returned from a call to {@link CacheLoader}.
*
* @since 11.0
*/
public static final class InvalidCacheLoadException extends RuntimeException {
public InvalidCacheLoadException(String message) {
super(message);
}
}
}
@@ -0,0 +1,281 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import static org.docx4j.com.google.common.base.Preconditions.checkArgument;
import java.util.concurrent.Callable;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.base.MoreObjects;
import org.docx4j.com.google.common.base.Objects;
/**
* Statistics about the performance of a {@link Cache}. Instances of this class are immutable.
*
* <p>Cache statistics are incremented according to the following rules:
*
* <ul>
* <li>When a cache lookup encounters an existing cache entry {@code hitCount} is incremented.
* <li>When a cache lookup first encounters a missing cache entry, a new entry is loaded.
* <ul>
* <li>After successfully loading an entry {@code missCount} and {@code loadSuccessCount}
* are incremented, and the total loading time, in nanoseconds, is added to {@code
* totalLoadTime}.
* <li>When an exception is thrown while loading an entry, {@code missCount} and {@code
* loadExceptionCount} are incremented, and the total loading time, in nanoseconds, is
* added to {@code totalLoadTime}.
* <li>Cache lookups that encounter a missing cache entry that is still loading will wait
* for loading to complete (whether successful or not) and then increment {@code
* missCount}.
* </ul>
* <li>When an entry is evicted from the cache, {@code evictionCount} is incremented.
* <li>No stats are modified when a cache entry is invalidated or manually removed.
* <li>No stats are modified by operations invoked on the {@linkplain Cache#asMap asMap} view of
* the cache.
* </ul>
*
* <p>A lookup is specifically defined as an invocation of one of the methods {@link
* LoadingCache#get(Object)}, {@link LoadingCache#getUnchecked(Object)}, {@link Cache#get(Object,
* Callable)}, or {@link LoadingCache#getAll(Iterable)}.
*
* @author Charles Fry
* @since 10.0
*/
@GwtCompatible
public final class CacheStats {
private final long hitCount;
private final long missCount;
private final long loadSuccessCount;
private final long loadExceptionCount;
@SuppressWarnings("GoodTime") // should be a java.time.Duration
private final long totalLoadTime;
private final long evictionCount;
/**
* Constructs a new {@code CacheStats} instance.
*
* <p>Five parameters of the same type in a row is a bad thing, but this class is not constructed
* by end users and is too fine-grained for a builder.
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public CacheStats(
long hitCount,
long missCount,
long loadSuccessCount,
long loadExceptionCount,
long totalLoadTime,
long evictionCount) {
checkArgument(hitCount >= 0);
checkArgument(missCount >= 0);
checkArgument(loadSuccessCount >= 0);
checkArgument(loadExceptionCount >= 0);
checkArgument(totalLoadTime >= 0);
checkArgument(evictionCount >= 0);
this.hitCount = hitCount;
this.missCount = missCount;
this.loadSuccessCount = loadSuccessCount;
this.loadExceptionCount = loadExceptionCount;
this.totalLoadTime = totalLoadTime;
this.evictionCount = evictionCount;
}
/**
* Returns the number of times {@link Cache} lookup methods have returned either a cached or
* uncached value. This is defined as {@code hitCount + missCount}.
*/
public long requestCount() {
return hitCount + missCount;
}
/** Returns the number of times {@link Cache} lookup methods have returned a cached value. */
public long hitCount() {
return hitCount;
}
/**
* Returns the ratio of cache requests which were hits. This is defined as {@code hitCount /
* requestCount}, or {@code 1.0} when {@code requestCount == 0}. Note that {@code hitRate +
* missRate =~ 1.0}.
*/
public double hitRate() {
long requestCount = requestCount();
return (requestCount == 0) ? 1.0 : (double) hitCount / requestCount;
}
/**
* Returns the number of times {@link Cache} lookup methods have returned an uncached (newly
* loaded) value, or null. Multiple concurrent calls to {@link Cache} lookup methods on an absent
* value can result in multiple misses, all returning the results of a single cache load
* operation.
*/
public long missCount() {
return missCount;
}
/**
* Returns the ratio of cache requests which were misses. This is defined as {@code missCount /
* requestCount}, or {@code 0.0} when {@code requestCount == 0}. Note that {@code hitRate +
* missRate =~ 1.0}. Cache misses include all requests which weren't cache hits, including
* requests which resulted in either successful or failed loading attempts, and requests which
* waited for other threads to finish loading. It is thus the case that {@code missCount &gt;=
* loadSuccessCount + loadExceptionCount}. Multiple concurrent misses for the same key will result
* in a single load operation.
*/
public double missRate() {
long requestCount = requestCount();
return (requestCount == 0) ? 0.0 : (double) missCount / requestCount;
}
/**
* Returns the total number of times that {@link Cache} lookup methods attempted to load new
* values. This includes both successful load operations, as well as those that threw exceptions.
* This is defined as {@code loadSuccessCount + loadExceptionCount}.
*/
public long loadCount() {
return loadSuccessCount + loadExceptionCount;
}
/**
* Returns the number of times {@link Cache} lookup methods have successfully loaded a new value.
* This is usually incremented in conjunction with {@link #missCount}, though {@code missCount} is
* also incremented when an exception is encountered during cache loading (see {@link
* #loadExceptionCount}). Multiple concurrent misses for the same key will result in a single load
* operation. This may be incremented not in conjunction with {@code missCount} if the load occurs
* as a result of a refresh or if the cache loader returned more items than was requested. {@code
* missCount} may also be incremented not in conjunction with this (nor {@link
* #loadExceptionCount}) on calls to {@code getIfPresent}.
*/
public long loadSuccessCount() {
return loadSuccessCount;
}
/**
* Returns the number of times {@link Cache} lookup methods threw an exception while loading a new
* value. This is usually incremented in conjunction with {@code missCount}, though {@code
* missCount} is also incremented when cache loading completes successfully (see {@link
* #loadSuccessCount}). Multiple concurrent misses for the same key will result in a single load
* operation. This may be incremented not in conjunction with {@code missCount} if the load occurs
* as a result of a refresh or if the cache loader returned more items than was requested. {@code
* missCount} may also be incremented not in conjunction with this (nor {@link #loadSuccessCount})
* on calls to {@code getIfPresent}.
*/
public long loadExceptionCount() {
return loadExceptionCount;
}
/**
* Returns the ratio of cache loading attempts which threw exceptions. This is defined as {@code
* loadExceptionCount / (loadSuccessCount + loadExceptionCount)}, or {@code 0.0} when {@code
* loadSuccessCount + loadExceptionCount == 0}.
*/
public double loadExceptionRate() {
long totalLoadCount = loadSuccessCount + loadExceptionCount;
return (totalLoadCount == 0) ? 0.0 : (double) loadExceptionCount / totalLoadCount;
}
/**
* Returns the total number of nanoseconds the cache has spent loading new values. This can be
* used to calculate the miss penalty. This value is increased every time {@code loadSuccessCount}
* or {@code loadExceptionCount} is incremented.
*/
@SuppressWarnings("GoodTime") // should return a java.time.Duration
public long totalLoadTime() {
return totalLoadTime;
}
/**
* Returns the average time spent loading new values. This is defined as {@code totalLoadTime /
* (loadSuccessCount + loadExceptionCount)}.
*/
public double averageLoadPenalty() {
long totalLoadCount = loadSuccessCount + loadExceptionCount;
return (totalLoadCount == 0) ? 0.0 : (double) totalLoadTime / totalLoadCount;
}
/**
* Returns the number of times an entry has been evicted. This count does not include manual
* {@linkplain Cache#invalidate invalidations}.
*/
public long evictionCount() {
return evictionCount;
}
/**
* Returns a new {@code CacheStats} representing the difference between this {@code CacheStats}
* and {@code other}. Negative values, which aren't supported by {@code CacheStats} will be
* rounded up to zero.
*/
public CacheStats minus(CacheStats other) {
return new CacheStats(
Math.max(0, hitCount - other.hitCount),
Math.max(0, missCount - other.missCount),
Math.max(0, loadSuccessCount - other.loadSuccessCount),
Math.max(0, loadExceptionCount - other.loadExceptionCount),
Math.max(0, totalLoadTime - other.totalLoadTime),
Math.max(0, evictionCount - other.evictionCount));
}
/**
* Returns a new {@code CacheStats} representing the sum of this {@code CacheStats} and {@code
* other}.
*
* @since 11.0
*/
public CacheStats plus(CacheStats other) {
return new CacheStats(
hitCount + other.hitCount,
missCount + other.missCount,
loadSuccessCount + other.loadSuccessCount,
loadExceptionCount + other.loadExceptionCount,
totalLoadTime + other.totalLoadTime,
evictionCount + other.evictionCount);
}
@Override
public int hashCode() {
return Objects.hashCode(
hitCount, missCount, loadSuccessCount, loadExceptionCount, totalLoadTime, evictionCount);
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof CacheStats) {
CacheStats other = (CacheStats) object;
return hitCount == other.hitCount
&& missCount == other.missCount
&& loadSuccessCount == other.loadSuccessCount
&& loadExceptionCount == other.loadExceptionCount
&& totalLoadTime == other.totalLoadTime
&& evictionCount == other.evictionCount;
}
return false;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("hitCount", hitCount)
.add("missCount", missCount)
.add("loadSuccessCount", loadSuccessCount)
.add("loadExceptionCount", loadExceptionCount)
.add("totalLoadTime", totalLoadTime)
.add("evictionCount", evictionCount)
.toString();
}
}
@@ -0,0 +1,161 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.base.Function;
import org.docx4j.com.google.common.collect.ImmutableMap;
import org.docx4j.com.google.common.util.concurrent.ExecutionError;
import org.docx4j.com.google.common.util.concurrent.UncheckedExecutionException;
/**
* A semi-persistent mapping from keys to values. Values are automatically loaded by the cache, and
* are stored in the cache until either evicted or manually invalidated. The common way to build
* instances is using {@link CacheBuilder}.
*
* <p>Implementations of this interface are expected to be thread-safe, and can be safely accessed
* by multiple concurrent threads.
*
* <p>When evaluated as a {@link Function}, a cache yields the same result as invoking {@link
* #getUnchecked}.
*
* @author Charles Fry
* @since 11.0
*/
@GwtCompatible
public interface LoadingCache<K, V> extends Cache<K, V>, Function<K, V> {
/**
* Returns the value associated with {@code key} in this cache, first loading that value if
* necessary. No observable state associated with this cache is modified until loading completes.
*
* <p>If another call to {@link #get} or {@link #getUnchecked} is currently loading the value for
* {@code key}, simply waits for that thread to finish and returns its loaded value. Note that
* multiple threads can concurrently load values for distinct keys.
*
* <p>Caches loaded by a {@link CacheLoader} will call {@link CacheLoader#load} to load new values
* into the cache. Newly loaded values are added to the cache using {@code
* Cache.asMap().putIfAbsent} after loading has completed; if another value was associated with
* {@code key} while the new value was loading then a removal notification will be sent for the
* new value.
*
* <p>If the cache loader associated with this cache is known not to throw checked exceptions,
* then prefer {@link #getUnchecked} over this method.
*
* @throws ExecutionException if a checked exception was thrown while loading the value. ({@code
* ExecutionException} is thrown <a
* href="https://github.com/google/guava/wiki/CachesExplained#interruption">even if
* computation was interrupted by an {@code InterruptedException}</a>.)
* @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
* value
* @throws ExecutionError if an error was thrown while loading the value
*/
V get(K key) throws ExecutionException;
/**
* Returns the value associated with {@code key} in this cache, first loading that value if
* necessary. No observable state associated with this cache is modified until loading completes.
* Unlike {@link #get}, this method does not throw a checked exception, and thus should only be
* used in situations where checked exceptions are not thrown by the cache loader.
*
* <p>If another call to {@link #get} or {@link #getUnchecked} is currently loading the value for
* {@code key}, simply waits for that thread to finish and returns its loaded value. Note that
* multiple threads can concurrently load values for distinct keys.
*
* <p>Caches loaded by a {@link CacheLoader} will call {@link CacheLoader#load} to load new values
* into the cache. Newly loaded values are added to the cache using {@code
* Cache.asMap().putIfAbsent} after loading has completed; if another value was associated with
* {@code key} while the new value was loading then a removal notification will be sent for the
* new value.
*
* <p><b>Warning:</b> this method silently converts checked exceptions to unchecked exceptions,
* and should not be used with cache loaders which throw checked exceptions. In such cases use
* {@link #get} instead.
*
* @throws UncheckedExecutionException if an exception was thrown while loading the value. (As
* explained in the last paragraph above, this should be an unchecked exception only.)
* @throws ExecutionError if an error was thrown while loading the value
*/
V getUnchecked(K key);
/**
* Returns a map of the values associated with {@code keys}, creating or retrieving those values
* if necessary. The returned map contains entries that were already cached, combined with newly
* loaded entries; it will never contain null keys or values.
*
* <p>Caches loaded by a {@link CacheLoader} will issue a single request to {@link
* CacheLoader#loadAll} for all keys which are not already present in the cache. All entries
* returned by {@link CacheLoader#loadAll} will be stored in the cache, over-writing any
* previously cached values. This method will throw an exception if {@link CacheLoader#loadAll}
* returns {@code null}, returns a map containing null keys or values, or fails to return an entry
* for each requested key.
*
* <p>Note that duplicate elements in {@code keys}, as determined by {@link Object#equals}, will
* be ignored.
*
* @throws ExecutionException if a checked exception was thrown while loading the value. ({@code
* ExecutionException} is thrown <a
* href="https://github.com/google/guava/wiki/CachesExplained#interruption">even if
* computation was interrupted by an {@code InterruptedException}</a>.)
* @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
* values
* @throws ExecutionError if an error was thrown while loading the values
* @since 11.0
*/
ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException;
/**
* @deprecated Provided to satisfy the {@code Function} interface; use {@link #get} or {@link
* #getUnchecked} instead.
* @throws UncheckedExecutionException if an exception was thrown while loading the value. (As
* described in the documentation for {@link #getUnchecked}, {@code LoadingCache} should be
* used as a {@code Function} only with cache loaders that throw only unchecked exceptions.)
*/
@Deprecated
@Override
V apply(K key);
/**
* Loads a new value for key {@code key}, possibly asynchronously. While the new value is loading
* the previous value (if any) will continue to be returned by {@code get(key)} unless it is
* evicted. If the new value is loaded successfully it will replace the previous value in the
* cache; if an exception is thrown while refreshing the previous value will remain, <i>and the
* exception will be logged and swallowed</i>.
*
* <p>Caches loaded by a {@link CacheLoader} will call {@link CacheLoader#reload} if the cache
* currently contains a value for {@code key}, and {@link CacheLoader#load} otherwise. Loading is
* asynchronous only if {@link CacheLoader#reload} was overridden with an asynchronous
* implementation.
*
* <p>Returns without doing anything if another thread is currently loading the value for {@code
* key}. If the cache loader associated with this cache performs refresh asynchronously then this
* method may return before refresh completes.
*
* @since 11.0
*/
void refresh(K key);
/**
* {@inheritDoc}
*
* <p><b>Note that although the view <i>is</i> modifiable, no method on the returned map will ever
* cause entries to be automatically loaded.</b>
*/
@Override
ConcurrentMap<K, V> asMap();
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* Abstract interface for objects that can concurrently add longs.
*
* @author Louis Wasserman
*/
@GwtCompatible
interface LongAddable {
void increment();
void add(long x);
long sum();
}
@@ -0,0 +1,74 @@
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import java.util.concurrent.atomic.AtomicLong;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.base.Supplier;
/**
* Source of {@link LongAddable} objects that deals with GWT, Unsafe, and all that.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
final class LongAddables {
private static final Supplier<LongAddable> SUPPLIER;
static {
Supplier<LongAddable> supplier;
try {
new LongAdder(); // trigger static initialization of the LongAdder class, which may fail
supplier =
new Supplier<LongAddable>() {
@Override
public LongAddable get() {
return new LongAdder();
}
};
} catch (Throwable t) { // we really want to catch *everything*
supplier =
new Supplier<LongAddable>() {
@Override
public LongAddable get() {
return new PureJavaLongAddable();
}
};
}
SUPPLIER = supplier;
}
public static LongAddable create() {
return SUPPLIER.get();
}
private static final class PureJavaLongAddable extends AtomicLong implements LongAddable {
@Override
public void increment() {
getAndIncrement();
}
@Override
public void add(long x) {
getAndAdd(x);
}
@Override
public long sum() {
return get();
}
}
}
@@ -0,0 +1,194 @@
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/*
* Source:
* http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.17
*/
package org.docx4j.com.google.common.cache;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* One or more variables that together maintain an initially zero {@code long} sum. When updates
* (method {@link #add}) are contended across threads, the set of variables may grow dynamically to
* reduce contention. Method {@link #sum} (or, equivalently, {@link #longValue}) returns the current
* total combined across the variables maintaining the sum.
*
* <p>This class is usually preferable to {@link AtomicLong} when multiple threads update a common
* sum that is used for purposes such as collecting statistics, not for fine-grained synchronization
* control. Under low update contention, the two classes have similar characteristics. But under
* high contention, expected throughput of this class is significantly higher, at the expense of
* higher space consumption.
*
* <p>This class extends {@link Number}, but does <em>not</em> define methods such as {@code
* equals}, {@code hashCode} and {@code compareTo} because instances are expected to be mutated, and
* so are not useful as collection keys.
*
* <p><em>jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.</em>
*
* @since 1.8
* @author Doug Lea
*/
@GwtCompatible(emulated = true)
final class LongAdder extends Striped64 implements Serializable, LongAddable {
private static final long serialVersionUID = 7249069246863182397L;
/** Version of plus for use in retryUpdate */
@Override
final long fn(long v, long x) {
return v + x;
}
/** Creates a new adder with initial sum of zero. */
public LongAdder() {}
/**
* Adds the given value.
*
* @param x the value to add
*/
@Override
public void add(long x) {
Cell[] as;
long b, v;
int[] hc;
Cell a;
int n;
if ((as = cells) != null || !casBase(b = base, b + x)) {
boolean uncontended = true;
if ((hc = threadHashCode.get()) == null
|| as == null
|| (n = as.length) < 1
|| (a = as[(n - 1) & hc[0]]) == null
|| !(uncontended = a.cas(v = a.value, v + x))) retryUpdate(x, hc, uncontended);
}
}
/** Equivalent to {@code add(1)}. */
@Override
public void increment() {
add(1L);
}
/** Equivalent to {@code add(-1)}. */
public void decrement() {
add(-1L);
}
/**
* Returns the current sum. The returned value is <em>NOT</em> an atomic snapshot; invocation in
* the absence of concurrent updates returns an accurate result, but concurrent updates that occur
* while the sum is being calculated might not be incorporated.
*
* @return the sum
*/
@Override
public long sum() {
long sum = base;
Cell[] as = cells;
if (as != null) {
int n = as.length;
for (int i = 0; i < n; ++i) {
Cell a = as[i];
if (a != null) sum += a.value;
}
}
return sum;
}
/**
* Resets variables maintaining the sum to zero. This method may be a useful alternative to
* creating a new adder, but is only effective if there are no concurrent updates. Because this
* method is intrinsically racy, it should only be used when it is known that no threads are
* concurrently updating.
*/
public void reset() {
internalReset(0L);
}
/**
* Equivalent in effect to {@link #sum} followed by {@link #reset}. This method may apply for
* example during quiescent points between multithreaded computations. If there are updates
* concurrent with this method, the returned value is <em>not</em> guaranteed to be the final
* value occurring before the reset.
*
* @return the sum
*/
public long sumThenReset() {
long sum = base;
Cell[] as = cells;
base = 0L;
if (as != null) {
int n = as.length;
for (int i = 0; i < n; ++i) {
Cell a = as[i];
if (a != null) {
sum += a.value;
a.value = 0L;
}
}
}
return sum;
}
/**
* Returns the String representation of the {@link #sum}.
*
* @return the String representation of the {@link #sum}
*/
@Override
public String toString() {
return Long.toString(sum());
}
/**
* Equivalent to {@link #sum}.
*
* @return the sum
*/
@Override
public long longValue() {
return sum();
}
/** Returns the {@link #sum} as an {@code int} after a narrowing primitive conversion. */
@Override
public int intValue() {
return (int) sum();
}
/** Returns the {@link #sum} as a {@code float} after a widening primitive conversion. */
@Override
public float floatValue() {
return (float) sum();
}
/** Returns the {@link #sum} as a {@code double} after a widening primitive conversion. */
@Override
public double doubleValue() {
return (double) sum();
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeLong(sum());
}
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
busy = 0;
cells = null;
base = s.readLong();
}
}
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtIncompatible;
import org.docx4j.com.google.common.cache.LocalCache.ValueReference;
/**
* An entry in a reference map.
*
* <p>Entries in the map can be in the following states:
*
* <p>Valid:
*
* <ul>
* <li>Live: valid key/value are set
* <li>Loading: loading is pending
* </ul>
*
* <p>Invalid:
*
* <ul>
* <li>Expired: time expired (key/value may still be set)
* <li>Collected: key/value was partially collected, but not yet cleaned up
* <li>Unset: marked as unset, awaiting cleanup or reuse
* </ul>
*/
@GwtIncompatible
interface ReferenceEntry<K, V> {
/** Returns the value reference from this entry. */
ValueReference<K, V> getValueReference();
/** Sets the value reference for this entry. */
void setValueReference(ValueReference<K, V> valueReference);
/** Returns the next entry in the chain. */
@Nullable
ReferenceEntry<K, V> getNext();
/** Returns the entry's hash. */
int getHash();
/** Returns the key for this entry. */
@Nullable
K getKey();
/*
* Used by entries that use access order. Access entries are maintained in a doubly-linked list.
* New entries are added at the tail of the list at write time; stale entries are expired from
* the head of the list.
*/
/** Returns the time that this entry was last accessed, in ns. */
long getAccessTime();
/** Sets the entry access time in ns. */
@SuppressWarnings("GoodTime") // b/122668874
void setAccessTime(long time);
/** Returns the next entry in the access queue. */
ReferenceEntry<K, V> getNextInAccessQueue();
/** Sets the next entry in the access queue. */
void setNextInAccessQueue(ReferenceEntry<K, V> next);
/** Returns the previous entry in the access queue. */
ReferenceEntry<K, V> getPreviousInAccessQueue();
/** Sets the previous entry in the access queue. */
void setPreviousInAccessQueue(ReferenceEntry<K, V> previous);
/*
* Implemented by entries that use write order. Write entries are maintained in a doubly-linked
* list. New entries are added at the tail of the list at write time and stale entries are
* expired from the head of the list.
*/
/** Returns the time that this entry was last written, in ns. */
long getWriteTime();
/** Sets the entry write time in ns. */
@SuppressWarnings("GoodTime") // b/122668874
void setWriteTime(long time);
/** Returns the next entry in the write queue. */
ReferenceEntry<K, V> getNextInWriteQueue();
/** Sets the next entry in the write queue. */
void setNextInWriteQueue(ReferenceEntry<K, V> next);
/** Returns the previous entry in the write queue. */
ReferenceEntry<K, V> getPreviousInWriteQueue();
/** Sets the previous entry in the write queue. */
void setPreviousInWriteQueue(ReferenceEntry<K, V> previous);
}
@@ -0,0 +1,95 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* The reason why a cached entry was removed.
*
* @author Charles Fry
* @since 10.0
*/
@GwtCompatible
public enum RemovalCause {
/**
* The entry was manually removed by the user. This can result from the user invoking {@link
* Cache#invalidate}, {@link Cache#invalidateAll(Iterable)}, {@link Cache#invalidateAll()}, {@link
* Map#remove}, {@link ConcurrentMap#remove}, or {@link Iterator#remove}.
*/
EXPLICIT {
@Override
boolean wasEvicted() {
return false;
}
},
/**
* The entry itself was not actually removed, but its value was replaced by the user. This can
* result from the user invoking {@link Cache#put}, {@link LoadingCache#refresh}, {@link Map#put},
* {@link Map#putAll}, {@link ConcurrentMap#replace(Object, Object)}, or {@link
* ConcurrentMap#replace(Object, Object, Object)}.
*/
REPLACED {
@Override
boolean wasEvicted() {
return false;
}
},
/**
* The entry was removed automatically because its key or value was garbage-collected. This can
* occur when using {@link CacheBuilder#weakKeys}, {@link CacheBuilder#weakValues}, or {@link
* CacheBuilder#softValues}.
*/
COLLECTED {
@Override
boolean wasEvicted() {
return true;
}
},
/**
* The entry's expiration timestamp has passed. This can occur when using {@link
* CacheBuilder#expireAfterWrite} or {@link CacheBuilder#expireAfterAccess}.
*/
EXPIRED {
@Override
boolean wasEvicted() {
return true;
}
},
/**
* The entry was evicted due to size constraints. This can occur when using {@link
* CacheBuilder#maximumSize} or {@link CacheBuilder#maximumWeight}.
*/
SIZE {
@Override
boolean wasEvicted() {
return true;
}
};
/**
* Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
* {@link #EXPLICIT} nor {@link #REPLACED}).
*/
abstract boolean wasEvicted();
}
@@ -0,0 +1,47 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* An object that can receive a notification when an entry is removed from a cache. The removal
* resulting in notification could have occurred to an entry being manually removed or replaced, or
* due to eviction resulting from timed expiration, exceeding a maximum size, or garbage collection.
*
* <p>An instance may be called concurrently by multiple threads to process different entries.
* Implementations of this interface should avoid performing blocking calls or synchronizing on
* shared resources.
*
* @param <K> the most general type of keys this listener can listen for; for example {@code Object}
* if any key is acceptable
* @param <V> the most general type of values this listener can listen for; for example {@code
* Object} if any key is acceptable
* @author Charles Fry
* @since 10.0
*/
@GwtCompatible
@FunctionalInterface
public interface RemovalListener<K, V> {
/**
* Notifies the listener that a removal occurred at some point in the past.
*
* <p>This does not always signify that the key is now absent from the cache, as it may have
* already been re-added.
*/
// Technically should accept RemovalNotification<? extends K, ? extends V>, but because
// RemovalNotification is guaranteed covariant, let's make users' lives simpler.
void onRemoval(RemovalNotification<K, V> notification);
}
@@ -0,0 +1,69 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import java.util.AbstractMap.SimpleImmutableEntry;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* A notification of the removal of a single entry. The key and/or value may be null if they were
* already garbage collected.
*
* <p>Like other {@code Entry} instances associated with {@code CacheBuilder}, this class holds
* strong references to the key and value, regardless of the type of references the cache may be
* using.
*
* @author Charles Fry
* @since 10.0
*/
@GwtCompatible
public final class RemovalNotification<K, V> extends SimpleImmutableEntry<K, V> {
private final RemovalCause cause;
/**
* Creates a new {@code RemovalNotification} for the given {@code key}/{@code value} pair, with
* the given {@code cause} for the removal. The {@code key} and/or {@code value} may be {@code
* null} if they were already garbage collected.
*
* @since 19.0
*/
public static <K, V> RemovalNotification<K, V> create(
@Nullable K key, @Nullable V value, RemovalCause cause) {
return new RemovalNotification(key, value, cause);
}
private RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) {
super(key, value);
this.cause = checkNotNull(cause);
}
/** Returns the cause for which the entry was removed. */
public RemovalCause getCause() {
return cause;
}
/**
* Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
* {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}).
*/
public boolean wasEvicted() {
return cause.wasEvicted();
}
private static final long serialVersionUID = 0;
}
@@ -0,0 +1,311 @@
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/*
* Source:
* http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/Striped64.java?revision=1.9
*/
package org.docx4j.com.google.common.cache;
import java.util.Random;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtIncompatible;
/**
* A package-local class holding common representation and mechanics for classes supporting dynamic
* striping on 64bit values. The class extends Number so that concrete subclasses must publicly do
* so.
*/
@GwtIncompatible
abstract class Striped64 extends Number {
/*
* This class maintains a lazily-initialized table of atomically
* updated variables, plus an extra "base" field. The table size
* is a power of two. Indexing uses masked per-thread hash codes.
* Nearly all declarations in this class are package-private,
* accessed directly by subclasses.
*
* Table entries are of class Cell; a variant of AtomicLong padded
* to reduce cache contention on most processors. Padding is
* overkill for most Atomics because they are usually irregularly
* scattered in memory and thus don't interfere much with each
* other. But Atomic objects residing in arrays will tend to be
* placed adjacent to each other, and so will most often share
* cache lines (with a huge negative performance impact) without
* this precaution.
*
* In part because Cells are relatively large, we avoid creating
* them until they are needed. When there is no contention, all
* updates are made to the base field. Upon first contention (a
* failed CAS on base update), the table is initialized to size 2.
* The table size is doubled upon further contention until
* reaching the nearest power of two greater than or equal to the
* number of CPUS. Table slots remain empty (null) until they are
* needed.
*
* A single spinlock ("busy") is used for initializing and
* resizing the table, as well as populating slots with new Cells.
* There is no need for a blocking lock; when the lock is not
* available, threads try other slots (or the base). During these
* retries, there is increased contention and reduced locality,
* which is still better than alternatives.
*
* Per-thread hash codes are initialized to random values.
* Contention and/or table collisions are indicated by failed
* CASes when performing an update operation (see method
* retryUpdate). Upon a collision, if the table size is less than
* the capacity, it is doubled in size unless some other thread
* holds the lock. If a hashed slot is empty, and lock is
* available, a new Cell is created. Otherwise, if the slot
* exists, a CAS is tried. Retries proceed by "double hashing",
* using a secondary hash (Marsaglia XorShift) to try to find a
* free slot.
*
* The table size is capped because, when there are more threads
* than CPUs, supposing that each thread were bound to a CPU,
* there would exist a perfect hash function mapping threads to
* slots that eliminates collisions. When we reach capacity, we
* search for this mapping by randomly varying the hash codes of
* colliding threads. Because search is random, and collisions
* only become known via CAS failures, convergence can be slow,
* and because threads are typically not bound to CPUS forever,
* may not occur at all. However, despite these limitations,
* observed contention rates are typically low in these cases.
*
* It is possible for a Cell to become unused when threads that
* once hashed to it terminate, as well as in the case where
* doubling the table causes no thread to hash to it under
* expanded mask. We do not try to detect or remove such cells,
* under the assumption that for long-running instances, observed
* contention levels will recur, so the cells will eventually be
* needed again; and for short-lived ones, it does not matter.
*/
/**
* Padded variant of AtomicLong supporting only raw accesses plus CAS. The value field is placed
* between pads, hoping that the JVM doesn't reorder them.
*
* <p>JVM intrinsics note: It would be possible to use a release-only form of CAS here, if it were
* provided.
*/
static final class Cell {
volatile long p0, p1, p2, p3, p4, p5, p6;
volatile long value;
volatile long q0, q1, q2, q3, q4, q5, q6;
Cell(long x) {
value = x;
}
final boolean cas(long cmp, long val) {
return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val);
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long valueOffset;
static {
try {
UNSAFE = getUnsafe();
Class<?> ak = Cell.class;
valueOffset = UNSAFE.objectFieldOffset(ak.getDeclaredField("value"));
} catch (Exception e) {
throw new Error(e);
}
}
}
/**
* ThreadLocal holding a single-slot int array holding hash code. Unlike the JDK8 version of this
* class, we use a suboptimal int[] representation to avoid introducing a new type that can impede
* class-unloading when ThreadLocals are not removed.
*/
static final ThreadLocal<int[]> threadHashCode = new ThreadLocal<>();
/** Generator of new random hash codes */
static final Random rng = new Random();
/** Number of CPUS, to place bound on table size */
static final int NCPU = Runtime.getRuntime().availableProcessors();
/** Table of cells. When non-null, size is a power of 2. */
transient volatile Cell @Nullable [] cells;
/**
* Base value, used mainly when there is no contention, but also as a fallback during table
* initialization races. Updated via CAS.
*/
transient volatile long base;
/** Spinlock (locked via CAS) used when resizing and/or creating Cells. */
transient volatile int busy;
/** Package-private default constructor */
Striped64() {}
/** CASes the base field. */
final boolean casBase(long cmp, long val) {
return UNSAFE.compareAndSwapLong(this, baseOffset, cmp, val);
}
/** CASes the busy field from 0 to 1 to acquire lock. */
final boolean casBusy() {
return UNSAFE.compareAndSwapInt(this, busyOffset, 0, 1);
}
/**
* Computes the function of current and new value. Subclasses should open-code this update
* function for most uses, but the virtualized form is needed within retryUpdate.
*
* @param currentValue the current value (of either base or a cell)
* @param newValue the argument from a user update call
* @return result of the update function
*/
abstract long fn(long currentValue, long newValue);
/**
* Handles cases of updates involving initialization, resizing, creating new Cells, and/or
* contention. See above for explanation. This method suffers the usual non-modularity problems of
* optimistic retry code, relying on rechecked sets of reads.
*
* @param x the value
* @param hc the hash code holder
* @param wasUncontended false if CAS failed before call
*/
final void retryUpdate(long x, int[] hc, boolean wasUncontended) {
int h;
if (hc == null) {
threadHashCode.set(hc = new int[1]); // Initialize randomly
int r = rng.nextInt(); // Avoid zero to allow xorShift rehash
h = hc[0] = (r == 0) ? 1 : r;
} else h = hc[0];
boolean collide = false; // True if last slot nonempty
for (; ; ) {
Cell[] as;
Cell a;
int n;
long v;
if ((as = cells) != null && (n = as.length) > 0) {
if ((a = as[(n - 1) & h]) == null) {
if (busy == 0) { // Try to attach new Cell
Cell r = new Cell(x); // Optimistically create
if (busy == 0 && casBusy()) {
boolean created = false;
try { // Recheck under lock
Cell[] rs;
int m, j;
if ((rs = cells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) {
rs[j] = r;
created = true;
}
} finally {
busy = 0;
}
if (created) break;
continue; // Slot is now non-empty
}
}
collide = false;
} else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
else if (a.cas(v = a.value, fn(v, x))) break;
else if (n >= NCPU || cells != as) collide = false; // At max size or stale
else if (!collide) collide = true;
else if (busy == 0 && casBusy()) {
try {
if (cells == as) { // Expand table unless stale
Cell[] rs = new Cell[n << 1];
for (int i = 0; i < n; ++i) rs[i] = as[i];
cells = rs;
}
} finally {
busy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h ^= h << 13; // Rehash
h ^= h >>> 17;
h ^= h << 5;
hc[0] = h; // Record index for next time
} else if (busy == 0 && cells == as && casBusy()) {
boolean init = false;
try { // Initialize table
if (cells == as) {
Cell[] rs = new Cell[2];
rs[h & 1] = new Cell(x);
cells = rs;
init = true;
}
} finally {
busy = 0;
}
if (init) break;
} else if (casBase(v = base, fn(v, x))) break; // Fall back on using base
}
}
/** Sets base and all cells to the given value. */
final void internalReset(long initialValue) {
Cell[] as = cells;
base = initialValue;
if (as != null) {
int n = as.length;
for (int i = 0; i < n; ++i) {
Cell a = as[i];
if (a != null) a.value = initialValue;
}
}
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long baseOffset;
private static final long busyOffset;
static {
try {
UNSAFE = getUnsafe();
Class<?> sk = Striped64.class;
baseOffset = UNSAFE.objectFieldOffset(sk.getDeclaredField("base"));
busyOffset = UNSAFE.objectFieldOffset(sk.getDeclaredField("busy"));
} catch (Exception e) {
throw new Error(e);
}
}
/**
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple call
* to Unsafe.getUnsafe when integrating into a jdk.
*
* @return a sun.misc.Unsafe
*/
private static sun.misc.Unsafe getUnsafe() {
try {
return sun.misc.Unsafe.getUnsafe();
} catch (SecurityException tryReflectionInstead) {
}
try {
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
@Override
public sun.misc.Unsafe run() throws Exception {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
for (java.lang.reflect.Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x)) return k.cast(x);
}
throw new NoSuchFieldError("the Unsafe");
}
});
} catch (java.security.PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics", e.getCause());
}
}
}
@@ -0,0 +1,36 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.cache;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* Calculates the weights of cache entries.
*
* @author Charles Fry
* @since 11.0
*/
@GwtCompatible
@FunctionalInterface
public interface Weigher<K, V> {
/**
* Returns the weight of a cache entry. There is no unit for entry weights; rather they are simply
* relative to each other.
*
* @return the weight of the entry; must be non-negative
*/
int weigh(K key, V value);
}
@@ -0,0 +1,103 @@
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.com.google.common.collect;
import static org.docx4j.com.google.common.base.Preconditions.checkPositionIndex;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* This class provides a skeletal implementation of the {@link ListIterator} interface across a
* fixed number of elements that may be retrieved by position. It does not support {@link #remove},
* {@link #set}, or {@link #add}.
*
* @author Jared Levy
*/
@GwtCompatible
abstract class AbstractIndexedListIterator<E> extends UnmodifiableListIterator<E> {
private final int size;
private int position;
/** Returns the element with the specified index. This method is called by {@link #next()}. */
protected abstract E get(int index);
/**
* Constructs an iterator across a sequence of the given size whose initial position is 0. That
* is, the first call to {@link #next()} will return the first element (or throw {@link
* NoSuchElementException} if {@code size} is zero).
*
* @throws IllegalArgumentException if {@code size} is negative
*/
protected AbstractIndexedListIterator(int size) {
this(size, 0);
}
/**
* Constructs an iterator across a sequence of the given size with the given initial position.
* That is, the first call to {@link #nextIndex()} will return {@code position}, and the first
* call to {@link #next()} will return the element at that index, if available. Calls to {@link
* #previous()} can retrieve the preceding {@code position} elements.
*
* @throws IndexOutOfBoundsException if {@code position} is negative or is greater than {@code
* size}
* @throws IllegalArgumentException if {@code size} is negative
*/
protected AbstractIndexedListIterator(int size, int position) {
checkPositionIndex(position, size);
this.size = size;
this.position = position;
}
@Override
public final boolean hasNext() {
return position < size;
}
@Override
public final E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return get(position++);
}
@Override
public final int nextIndex() {
return position;
}
@Override
public final boolean hasPrevious() {
return position > 0;
}
@Override
public final E previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
return get(--position);
}
@Override
public final int previousIndex() {
return position - 1;
}
}
@@ -0,0 +1,66 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.com.google.common.collect;
import java.util.Map.Entry;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.base.Objects;
/**
* Implementation of the {@code equals}, {@code hashCode}, and {@code toString} methods of {@code
* Entry}.
*
* @author Jared Levy
*/
@GwtCompatible
abstract class AbstractMapEntry<K, V> implements Entry<K, V> {
@Override
public abstract K getKey();
@Override
public abstract V getValue();
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
return Objects.equal(this.getKey(), that.getKey())
&& Objects.equal(this.getValue(), that.getValue());
}
return false;
}
@Override
public int hashCode() {
K k = getKey();
V v = getValue();
return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
}
/** Returns a string representation of the form {@code {key}={value}}. */
@Override
public String toString() {
return getKey() + "=" + getValue();
}
}
@@ -0,0 +1,78 @@
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.com.google.common.collect;
import java.util.NoSuchElementException;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* This class provides a skeletal implementation of the {@code Iterator} interface for sequences
* whose next element can always be derived from the previous element. Null elements are not
* supported, nor is the {@link #remove()} method.
*
* <p>Example:
*
* <pre>{@code
* Iterator<Integer> powersOfTwo =
* new AbstractSequentialIterator<Integer>(1) {
* protected Integer computeNext(Integer previous) {
* return (previous == 1 << 30) ? null : previous * 2;
* }
* };
* }</pre>
*
* @author Chris Povirk
* @since 12.0 (in Guava as {@code AbstractLinkedIterator} since 8.0)
*/
@GwtCompatible
public abstract class AbstractSequentialIterator<T> extends UnmodifiableIterator<T> {
private @Nullable T nextOrNull;
/**
* Creates a new iterator with the given first element, or, if {@code firstOrNull} is null,
* creates a new empty iterator.
*/
protected AbstractSequentialIterator(@Nullable T firstOrNull) {
this.nextOrNull = firstOrNull;
}
/**
* Returns the element that follows {@code previous}, or returns {@code null} if no elements
* remain. This method is invoked during each call to {@link #next()} in order to compute the
* result of a <i>future</i> call to {@code next()}.
*/
@Nullable
protected abstract T computeNext(T previous);
@Override
public final boolean hasNext() {
return nextOrNull != null;
}
@Override
public final T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return nextOrNull;
} finally {
nextOrNull = computeNext(nextOrNull);
}
}
}
@@ -0,0 +1,108 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.com.google.common.collect;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Map;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as
* that of its keys. This constraint enables bimaps to support an "inverse view", which is another
* bimap containing the same entries as this bimap but with reversed keys and values.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap"> {@code BiMap}</a>.
*
* @author Kevin Bourrillion
* @since 2.0
*/
@GwtCompatible
public interface BiMap<K, V> extends Map<K, V> {
// Modification Operations
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if the given value is already bound to a different key in this
* bimap. The bimap will remain unmodified in this event. To avoid this exception, call {@link
* #forcePut} instead.
*/
@CanIgnoreReturnValue
@Override
@Nullable
V put(@Nullable K key, @Nullable V value);
/**
* An alternate form of {@code put} that silently removes any existing entry with the value {@code
* value} before proceeding with the {@link #put} operation. If the bimap previously contained the
* provided key-value mapping, this method has no effect.
*
* <p>Note that a successful call to this method could cause the size of the bimap to increase by
* one, stay the same, or even decrease by one.
*
* <p><b>Warning:</b> If an existing entry with this value is removed, the key for that entry is
* discarded and not returned.
*
* @param key the key with which the specified value is to be associated
* @param value the value to be associated with the specified key
* @return the value which was previously associated with the key, which may be {@code null}, or
* {@code null} if there was no previous entry
*/
@CanIgnoreReturnValue
@Nullable
V forcePut(@Nullable K key, @Nullable V value);
// Bulk Operations
/**
* {@inheritDoc}
*
* <p><b>Warning:</b> the results of calling this method may vary depending on the iteration order
* of {@code map}.
*
* @throws IllegalArgumentException if an attempt to {@code put} any entry fails. Note that some
* map entries may have been added to the bimap before the exception was thrown.
*/
@Override
void putAll(Map<? extends K, ? extends V> map);
// Views
/**
* {@inheritDoc}
*
* <p>Because a bimap has unique values, this method returns a {@link Set}, instead of the {@link
* java.util.Collection} specified in the {@link Map} interface.
*/
@Override
Set<V> values();
/**
* Returns the inverse view of this bimap, which maps each of this bimap's values to its
* associated key. The two bimaps are backed by the same data; any changes to one will appear in
* the other.
*
* <p><b>Note:</b>There is no guaranteed correspondence between the iteration order of a bimap and
* that of its inverse.
*
* @return the inverse view of this bimap
*/
BiMap<V, K> inverse();
}
@@ -0,0 +1,290 @@
/*
* Copyright (C) 2015 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.com.google.common.collect;
import static org.docx4j.com.google.common.base.Preconditions.checkArgument;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import java.util.Comparator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/** Spliterator utilities for {@code common.collect} internals. */
@GwtCompatible
final class CollectSpliterators {
private CollectSpliterators() {}
static <T> Spliterator<T> indexed(int size, int extraCharacteristics, IntFunction<T> function) {
return indexed(size, extraCharacteristics, function, null);
}
static <T> Spliterator<T> indexed(
int size,
int extraCharacteristics,
IntFunction<T> function,
Comparator<? super T> comparator) {
if (comparator != null) {
checkArgument((extraCharacteristics & Spliterator.SORTED) != 0);
}
class WithCharacteristics implements Spliterator<T> {
private final Spliterator.OfInt delegate;
WithCharacteristics(Spliterator.OfInt delegate) {
this.delegate = delegate;
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
return delegate.tryAdvance((IntConsumer) i -> action.accept(function.apply(i)));
}
@Override
public void forEachRemaining(Consumer<? super T> action) {
delegate.forEachRemaining((IntConsumer) i -> action.accept(function.apply(i)));
}
@Override
public @Nullable Spliterator<T> trySplit() {
Spliterator.OfInt split = delegate.trySplit();
return (split == null) ? null : new WithCharacteristics(split);
}
@Override
public long estimateSize() {
return delegate.estimateSize();
}
@Override
public int characteristics() {
return Spliterator.ORDERED
| Spliterator.SIZED
| Spliterator.SUBSIZED
| extraCharacteristics;
}
@Override
public Comparator<? super T> getComparator() {
if (hasCharacteristics(Spliterator.SORTED)) {
return comparator;
} else {
throw new IllegalStateException();
}
}
}
return new WithCharacteristics(IntStream.range(0, size).spliterator());
}
/**
* Returns a {@code Spliterator} over the elements of {@code fromSpliterator} mapped by {@code
* function}.
*/
static <F, T> Spliterator<T> map(
Spliterator<F> fromSpliterator, Function<? super F, ? extends T> function) {
checkNotNull(fromSpliterator);
checkNotNull(function);
return new Spliterator<T>() {
@Override
public boolean tryAdvance(Consumer<? super T> action) {
return fromSpliterator.tryAdvance(
fromElement -> action.accept(function.apply(fromElement)));
}
@Override
public void forEachRemaining(Consumer<? super T> action) {
fromSpliterator.forEachRemaining(fromElement -> action.accept(function.apply(fromElement)));
}
@Override
public Spliterator<T> trySplit() {
Spliterator<F> fromSplit = fromSpliterator.trySplit();
return (fromSplit != null) ? map(fromSplit, function) : null;
}
@Override
public long estimateSize() {
return fromSpliterator.estimateSize();
}
@Override
public int characteristics() {
return fromSpliterator.characteristics()
& ~(Spliterator.DISTINCT | Spliterator.NONNULL | Spliterator.SORTED);
}
};
}
/** Returns a {@code Spliterator} filtered by the specified predicate. */
static <T> Spliterator<T> filter(Spliterator<T> fromSpliterator, Predicate<? super T> predicate) {
checkNotNull(fromSpliterator);
checkNotNull(predicate);
class Splitr implements Spliterator<T>, Consumer<T> {
T holder = null;
@Override
public void accept(T t) {
this.holder = t;
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
while (fromSpliterator.tryAdvance(this)) {
try {
if (predicate.test(holder)) {
action.accept(holder);
return true;
}
} finally {
holder = null;
}
}
return false;
}
@Override
public Spliterator<T> trySplit() {
Spliterator<T> fromSplit = fromSpliterator.trySplit();
return (fromSplit == null) ? null : filter(fromSplit, predicate);
}
@Override
public long estimateSize() {
return fromSpliterator.estimateSize() / 2;
}
@Override
public Comparator<? super T> getComparator() {
return fromSpliterator.getComparator();
}
@Override
public int characteristics() {
return fromSpliterator.characteristics()
& (Spliterator.DISTINCT
| Spliterator.NONNULL
| Spliterator.ORDERED
| Spliterator.SORTED);
}
}
return new Splitr();
}
/**
* Returns a {@code Spliterator} that iterates over the elements of the spliterators generated by
* applying {@code function} to the elements of {@code fromSpliterator}.
*/
static <F, T> Spliterator<T> flatMap(
Spliterator<F> fromSpliterator,
Function<? super F, Spliterator<T>> function,
int topCharacteristics,
long topSize) {
checkArgument(
(topCharacteristics & Spliterator.SUBSIZED) == 0,
"flatMap does not support SUBSIZED characteristic");
checkArgument(
(topCharacteristics & Spliterator.SORTED) == 0,
"flatMap does not support SORTED characteristic");
checkNotNull(fromSpliterator);
checkNotNull(function);
class FlatMapSpliterator implements Spliterator<T> {
@Nullable Spliterator<T> prefix;
final Spliterator<F> from;
int characteristics;
long estimatedSize;
FlatMapSpliterator(
Spliterator<T> prefix, Spliterator<F> from, int characteristics, long estimatedSize) {
this.prefix = prefix;
this.from = from;
this.characteristics = characteristics;
this.estimatedSize = estimatedSize;
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
while (true) {
if (prefix != null && prefix.tryAdvance(action)) {
if (estimatedSize != Long.MAX_VALUE) {
estimatedSize--;
}
return true;
} else {
prefix = null;
}
if (!from.tryAdvance(fromElement -> prefix = function.apply(fromElement))) {
return false;
}
}
}
@Override
public void forEachRemaining(Consumer<? super T> action) {
if (prefix != null) {
prefix.forEachRemaining(action);
prefix = null;
}
from.forEachRemaining(fromElement -> function.apply(fromElement).forEachRemaining(action));
estimatedSize = 0;
}
@Override
public Spliterator<T> trySplit() {
Spliterator<F> fromSplit = from.trySplit();
if (fromSplit != null) {
int splitCharacteristics = characteristics & ~Spliterator.SIZED;
long estSplitSize = estimateSize();
if (estSplitSize < Long.MAX_VALUE) {
estSplitSize /= 2;
this.estimatedSize -= estSplitSize;
this.characteristics = splitCharacteristics;
}
Spliterator<T> result =
new FlatMapSpliterator(this.prefix, fromSplit, splitCharacteristics, estSplitSize);
this.prefix = null;
return result;
} else if (prefix != null) {
Spliterator<T> result = prefix;
this.prefix = null;
return result;
} else {
return null;
}
}
@Override
public long estimateSize() {
if (prefix != null) {
estimatedSize = Math.max(estimatedSize, prefix.estimateSize());
}
return Math.max(estimatedSize, 0);
}
@Override
public int characteristics() {
return characteristics;
}
}
return new FlatMapSpliterator(null, fromSpliterator, topCharacteristics, topSize);
}
}
@@ -0,0 +1,746 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.docx4j.com.google.common.collect;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import static org.docx4j.com.google.common.base.Preconditions.checkArgument;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import static org.docx4j.com.google.common.collect.Hashing.smearedHash;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.base.Objects;
import org.docx4j.com.google.common.collect.Maps.IteratorBasedAbstractMap;
/**
* A {@link BiMap} backed by two hash tables. This implementation allows null keys and values. A
* {@code HashBiMap} and its inverse are both serializable.
*
* <p>This implementation guarantees insertion-based iteration order of its keys.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap"> {@code BiMap} </a>.
*
* @author Louis Wasserman
* @author Mike Bostock
* @since 2.0
*/
//@GwtCompatible(emulated = true)
public final class HashBiMap<K, V> extends IteratorBasedAbstractMap<K, V>
implements BiMap<K, V>, Serializable {
/** Returns a new, empty {@code HashBiMap} with the default initial capacity (16). */
public static <K, V> HashBiMap<K, V> create() {
return create(16);
}
/**
* Constructs a new, empty bimap with the specified expected size.
*
* @param expectedSize the expected number of entries
* @throws IllegalArgumentException if the specified expected size is negative
*/
public static <K, V> HashBiMap<K, V> create(int expectedSize) {
return new HashBiMap<>(expectedSize);
}
/**
* Constructs a new bimap containing initial values from {@code map}. The bimap is created with an
* initial capacity sufficient to hold the mappings in the specified map.
*/
public static <K, V> HashBiMap<K, V> create(Map<? extends K, ? extends V> map) {
HashBiMap<K, V> bimap = create(map.size());
bimap.putAll(map);
return bimap;
}
private static final class BiEntry<K, V> extends ImmutableEntry<K, V> {
final int keyHash;
final int valueHash;
@Nullable BiEntry<K, V> nextInKToVBucket;
@Nullable BiEntry<K, V> nextInVToKBucket;
@Nullable BiEntry<K, V> nextInKeyInsertionOrder;
@Nullable BiEntry<K, V> prevInKeyInsertionOrder;
BiEntry(K key, int keyHash, V value, int valueHash) {
super(key, value);
this.keyHash = keyHash;
this.valueHash = valueHash;
}
}
private static final double LOAD_FACTOR = 1.0;
private transient BiEntry<K, V>[] hashTableKToV;
private transient BiEntry<K, V>[] hashTableVToK;
private transient @Nullable BiEntry<K, V> firstInKeyInsertionOrder;
private transient @Nullable BiEntry<K, V> lastInKeyInsertionOrder;
private transient int size;
private transient int mask;
private transient int modCount;
private HashBiMap(int expectedSize) {
init(expectedSize);
}
private void init(int expectedSize) {
// checkNonnegative(expectedSize, "expectedSize");
int tableSize = Hashing.closedTableSize(expectedSize, LOAD_FACTOR);
this.hashTableKToV = createTable(tableSize);
this.hashTableVToK = createTable(tableSize);
this.firstInKeyInsertionOrder = null;
this.lastInKeyInsertionOrder = null;
this.size = 0;
this.mask = tableSize - 1;
this.modCount = 0;
}
/**
* Finds and removes {@code entry} from the bucket linked lists in both the key-to-value direction
* and the value-to-key direction.
*/
private void delete(BiEntry<K, V> entry) {
int keyBucket = entry.keyHash & mask;
BiEntry<K, V> prevBucketEntry = null;
for (BiEntry<K, V> bucketEntry = hashTableKToV[keyBucket];
true;
bucketEntry = bucketEntry.nextInKToVBucket) {
if (bucketEntry == entry) {
if (prevBucketEntry == null) {
hashTableKToV[keyBucket] = entry.nextInKToVBucket;
} else {
prevBucketEntry.nextInKToVBucket = entry.nextInKToVBucket;
}
break;
}
prevBucketEntry = bucketEntry;
}
int valueBucket = entry.valueHash & mask;
prevBucketEntry = null;
for (BiEntry<K, V> bucketEntry = hashTableVToK[valueBucket];
true;
bucketEntry = bucketEntry.nextInVToKBucket) {
if (bucketEntry == entry) {
if (prevBucketEntry == null) {
hashTableVToK[valueBucket] = entry.nextInVToKBucket;
} else {
prevBucketEntry.nextInVToKBucket = entry.nextInVToKBucket;
}
break;
}
prevBucketEntry = bucketEntry;
}
if (entry.prevInKeyInsertionOrder == null) {
firstInKeyInsertionOrder = entry.nextInKeyInsertionOrder;
} else {
entry.prevInKeyInsertionOrder.nextInKeyInsertionOrder = entry.nextInKeyInsertionOrder;
}
if (entry.nextInKeyInsertionOrder == null) {
lastInKeyInsertionOrder = entry.prevInKeyInsertionOrder;
} else {
entry.nextInKeyInsertionOrder.prevInKeyInsertionOrder = entry.prevInKeyInsertionOrder;
}
size--;
modCount++;
}
private void insert(BiEntry<K, V> entry, @Nullable BiEntry<K, V> oldEntryForKey) {
int keyBucket = entry.keyHash & mask;
entry.nextInKToVBucket = hashTableKToV[keyBucket];
hashTableKToV[keyBucket] = entry;
int valueBucket = entry.valueHash & mask;
entry.nextInVToKBucket = hashTableVToK[valueBucket];
hashTableVToK[valueBucket] = entry;
if (oldEntryForKey == null) {
entry.prevInKeyInsertionOrder = lastInKeyInsertionOrder;
entry.nextInKeyInsertionOrder = null;
if (lastInKeyInsertionOrder == null) {
firstInKeyInsertionOrder = entry;
} else {
lastInKeyInsertionOrder.nextInKeyInsertionOrder = entry;
}
lastInKeyInsertionOrder = entry;
} else {
entry.prevInKeyInsertionOrder = oldEntryForKey.prevInKeyInsertionOrder;
if (entry.prevInKeyInsertionOrder == null) {
firstInKeyInsertionOrder = entry;
} else {
entry.prevInKeyInsertionOrder.nextInKeyInsertionOrder = entry;
}
entry.nextInKeyInsertionOrder = oldEntryForKey.nextInKeyInsertionOrder;
if (entry.nextInKeyInsertionOrder == null) {
lastInKeyInsertionOrder = entry;
} else {
entry.nextInKeyInsertionOrder.prevInKeyInsertionOrder = entry;
}
}
size++;
modCount++;
}
private BiEntry<K, V> seekByKey(@Nullable Object key, int keyHash) {
for (BiEntry<K, V> entry = hashTableKToV[keyHash & mask];
entry != null;
entry = entry.nextInKToVBucket) {
if (keyHash == entry.keyHash && Objects.equal(key, entry.key)) {
return entry;
}
}
return null;
}
private BiEntry<K, V> seekByValue(@Nullable Object value, int valueHash) {
for (BiEntry<K, V> entry = hashTableVToK[valueHash & mask];
entry != null;
entry = entry.nextInVToKBucket) {
if (valueHash == entry.valueHash && Objects.equal(value, entry.value)) {
return entry;
}
}
return null;
}
@Override
public boolean containsKey(@Nullable Object key) {
return seekByKey(key, smearedHash(key)) != null;
}
@Override
public boolean containsValue(@Nullable Object value) {
return seekByValue(value, smearedHash(value)) != null;
}
@Override
public @Nullable V get(@Nullable Object key) {
return Maps.valueOrNull(seekByKey(key, smearedHash(key)));
}
@CanIgnoreReturnValue
@Override
public V put(@Nullable K key, @Nullable V value) {
return put(key, value, false);
}
private V put(@Nullable K key, @Nullable V value, boolean force) {
int keyHash = smearedHash(key);
int valueHash = smearedHash(value);
BiEntry<K, V> oldEntryForKey = seekByKey(key, keyHash);
if (oldEntryForKey != null
&& valueHash == oldEntryForKey.valueHash
&& Objects.equal(value, oldEntryForKey.value)) {
return value;
}
BiEntry<K, V> oldEntryForValue = seekByValue(value, valueHash);
if (oldEntryForValue != null) {
if (force) {
delete(oldEntryForValue);
} else {
throw new IllegalArgumentException("value already present: " + value);
}
}
BiEntry<K, V> newEntry = new BiEntry<>(key, keyHash, value, valueHash);
if (oldEntryForKey != null) {
delete(oldEntryForKey);
insert(newEntry, oldEntryForKey);
oldEntryForKey.prevInKeyInsertionOrder = null;
oldEntryForKey.nextInKeyInsertionOrder = null;
return oldEntryForKey.value;
} else {
insert(newEntry, null);
rehashIfNecessary();
return null;
}
}
@CanIgnoreReturnValue
@Override
@Nullable
public V forcePut(@Nullable K key, @Nullable V value) {
return put(key, value, true);
}
private @Nullable K putInverse(@Nullable V value, @Nullable K key, boolean force) {
int valueHash = smearedHash(value);
int keyHash = smearedHash(key);
BiEntry<K, V> oldEntryForValue = seekByValue(value, valueHash);
BiEntry<K, V> oldEntryForKey = seekByKey(key, keyHash);
if (oldEntryForValue != null
&& keyHash == oldEntryForValue.keyHash
&& Objects.equal(key, oldEntryForValue.key)) {
return key;
} else if (oldEntryForKey != null && !force) {
throw new IllegalArgumentException("key already present: " + key);
}
/*
* The ordering here is important: if we deleted the key entry and then the value entry,
* the key entry's prev or next pointer might point to the dead value entry, and when we
* put the new entry in the key entry's position in iteration order, it might invalidate
* the linked list.
*/
if (oldEntryForValue != null) {
delete(oldEntryForValue);
}
if (oldEntryForKey != null) {
delete(oldEntryForKey);
}
BiEntry<K, V> newEntry = new BiEntry<>(key, keyHash, value, valueHash);
insert(newEntry, oldEntryForKey);
if (oldEntryForKey != null) {
oldEntryForKey.prevInKeyInsertionOrder = null;
oldEntryForKey.nextInKeyInsertionOrder = null;
}
if (oldEntryForValue != null) {
oldEntryForValue.prevInKeyInsertionOrder = null;
oldEntryForValue.nextInKeyInsertionOrder = null;
}
rehashIfNecessary();
return Maps.keyOrNull(oldEntryForValue);
}
private void rehashIfNecessary() {
BiEntry<K, V>[] oldKToV = hashTableKToV;
if (Hashing.needsResizing(size, oldKToV.length, LOAD_FACTOR)) {
int newTableSize = oldKToV.length * 2;
this.hashTableKToV = createTable(newTableSize);
this.hashTableVToK = createTable(newTableSize);
this.mask = newTableSize - 1;
this.size = 0;
for (BiEntry<K, V> entry = firstInKeyInsertionOrder;
entry != null;
entry = entry.nextInKeyInsertionOrder) {
insert(entry, entry);
}
this.modCount++;
}
}
@SuppressWarnings("unchecked")
private BiEntry<K, V>[] createTable(int length) {
return new BiEntry[length];
}
@CanIgnoreReturnValue
@Override
@Nullable
public V remove(@Nullable Object key) {
BiEntry<K, V> entry = seekByKey(key, smearedHash(key));
if (entry == null) {
return null;
} else {
delete(entry);
entry.prevInKeyInsertionOrder = null;
entry.nextInKeyInsertionOrder = null;
return entry.value;
}
}
@Override
public void clear() {
size = 0;
Arrays.fill(hashTableKToV, null);
Arrays.fill(hashTableVToK, null);
firstInKeyInsertionOrder = null;
lastInKeyInsertionOrder = null;
modCount++;
}
@Override
public int size() {
return size;
}
abstract class Itr<T> implements Iterator<T> {
BiEntry<K, V> next = firstInKeyInsertionOrder;
BiEntry<K, V> toRemove = null;
int expectedModCount = modCount;
int remaining = size();
@Override
public boolean hasNext() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
return next != null && remaining > 0;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
BiEntry<K, V> entry = next;
next = entry.nextInKeyInsertionOrder;
toRemove = entry;
remaining--;
return output(entry);
}
@Override
public void remove() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
// checkRemove(toRemove != null);
delete(toRemove);
expectedModCount = modCount;
toRemove = null;
}
abstract T output(BiEntry<K, V> entry);
}
@Override
public Set<K> keySet() {
return new KeySet();
}
private final class KeySet extends Maps.KeySet<K, V> {
KeySet() {
super(HashBiMap.this);
}
@Override
public Iterator<K> iterator() {
return new Itr<K>() {
@Override
K output(BiEntry<K, V> entry) {
return entry.key;
}
};
}
@Override
public boolean remove(@Nullable Object o) {
BiEntry<K, V> entry = seekByKey(o, smearedHash(o));
if (entry == null) {
return false;
} else {
delete(entry);
entry.prevInKeyInsertionOrder = null;
entry.nextInKeyInsertionOrder = null;
return true;
}
}
}
@Override
public Set<V> values() {
return inverse().keySet();
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return new Itr<Entry<K, V>>() {
@Override
Entry<K, V> output(BiEntry<K, V> entry) {
return new MapEntry(entry);
}
class MapEntry extends AbstractMapEntry<K, V> {
BiEntry<K, V> delegate;
MapEntry(BiEntry<K, V> entry) {
this.delegate = entry;
}
@Override
public K getKey() {
return delegate.key;
}
@Override
public V getValue() {
return delegate.value;
}
@Override
public V setValue(V value) {
V oldValue = delegate.value;
int valueHash = smearedHash(value);
if (valueHash == delegate.valueHash && Objects.equal(value, oldValue)) {
return value;
}
checkArgument(seekByValue(value, valueHash) == null, "value already present: %s", value);
delete(delegate);
BiEntry<K, V> newEntry = new BiEntry<>(delegate.key, delegate.keyHash, value, valueHash);
insert(newEntry, delegate);
delegate.prevInKeyInsertionOrder = null;
delegate.nextInKeyInsertionOrder = null;
expectedModCount = modCount;
if (toRemove == delegate) {
toRemove = newEntry;
}
delegate = newEntry;
return oldValue;
}
}
};
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
checkNotNull(action);
for (BiEntry<K, V> entry = firstInKeyInsertionOrder;
entry != null;
entry = entry.nextInKeyInsertionOrder) {
action.accept(entry.key, entry.value);
}
}
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
checkNotNull(function);
BiEntry<K, V> oldFirst = firstInKeyInsertionOrder;
clear();
for (BiEntry<K, V> entry = oldFirst; entry != null; entry = entry.nextInKeyInsertionOrder) {
put(entry.key, function.apply(entry.key, entry.value));
}
}
@MonotonicNonNull private transient BiMap<V, K> inverse;
@Override
public BiMap<V, K> inverse() {
BiMap<V, K> result = inverse;
return (result == null) ? inverse = new Inverse() : result;
}
private final class Inverse extends IteratorBasedAbstractMap<V, K>
implements BiMap<V, K>, Serializable {
BiMap<K, V> forward() {
return HashBiMap.this;
}
@Override
public int size() {
return size;
}
@Override
public void clear() {
forward().clear();
}
@Override
public boolean containsKey(@Nullable Object value) {
return forward().containsValue(value);
}
@Override
public K get(@Nullable Object value) {
return Maps.keyOrNull(seekByValue(value, smearedHash(value)));
}
@CanIgnoreReturnValue
@Override
@Nullable
public K put(@Nullable V value, @Nullable K key) {
return putInverse(value, key, false);
}
@Override
@Nullable
public K forcePut(@Nullable V value, @Nullable K key) {
return putInverse(value, key, true);
}
@Override
@Nullable
public K remove(@Nullable Object value) {
BiEntry<K, V> entry = seekByValue(value, smearedHash(value));
if (entry == null) {
return null;
} else {
delete(entry);
entry.prevInKeyInsertionOrder = null;
entry.nextInKeyInsertionOrder = null;
return entry.key;
}
}
@Override
public BiMap<K, V> inverse() {
return forward();
}
@Override
public Set<V> keySet() {
return new InverseKeySet();
}
private final class InverseKeySet extends Maps.KeySet<V, K> {
InverseKeySet() {
super(Inverse.this);
}
@Override
public boolean remove(@Nullable Object o) {
BiEntry<K, V> entry = seekByValue(o, smearedHash(o));
if (entry == null) {
return false;
} else {
delete(entry);
return true;
}
}
@Override
public Iterator<V> iterator() {
return new Itr<V>() {
@Override
V output(BiEntry<K, V> entry) {
return entry.value;
}
};
}
}
@Override
public Set<K> values() {
return forward().keySet();
}
@Override
Iterator<Entry<V, K>> entryIterator() {
return new Itr<Entry<V, K>>() {
@Override
Entry<V, K> output(BiEntry<K, V> entry) {
return new InverseEntry(entry);
}
class InverseEntry extends AbstractMapEntry<V, K> {
BiEntry<K, V> delegate;
InverseEntry(BiEntry<K, V> entry) {
this.delegate = entry;
}
@Override
public V getKey() {
return delegate.value;
}
@Override
public K getValue() {
return delegate.key;
}
@Override
public K setValue(K key) {
K oldKey = delegate.key;
int keyHash = smearedHash(key);
if (keyHash == delegate.keyHash && Objects.equal(key, oldKey)) {
return key;
}
checkArgument(seekByKey(key, keyHash) == null, "value already present: %s", key);
delete(delegate);
BiEntry<K, V> newEntry =
new BiEntry<>(key, keyHash, delegate.value, delegate.valueHash);
delegate = newEntry;
insert(newEntry, null);
expectedModCount = modCount;
return oldKey;
}
}
};
}
@Override
public void forEach(BiConsumer<? super V, ? super K> action) {
checkNotNull(action);
HashBiMap.this.forEach((k, v) -> action.accept(v, k));
}
@Override
public void replaceAll(BiFunction<? super V, ? super K, ? extends K> function) {
checkNotNull(function);
BiEntry<K, V> oldFirst = firstInKeyInsertionOrder;
clear();
for (BiEntry<K, V> entry = oldFirst; entry != null; entry = entry.nextInKeyInsertionOrder) {
put(entry.value, function.apply(entry.value, entry.key));
}
}
Object writeReplace() {
return new InverseSerializedForm<>(HashBiMap.this);
}
}
private static final class InverseSerializedForm<K, V> implements Serializable {
private final HashBiMap<K, V> bimap;
InverseSerializedForm(HashBiMap<K, V> bimap) {
this.bimap = bimap;
}
Object readResolve() {
return bimap.inverse();
}
}
// /**
// * @serialData the number of entries, first key, first value, second key, second value, and so on.
// */
//// @GwtIncompatible // java.io.ObjectOutputStream
// private void writeObject(ObjectOutputStream stream) throws IOException {
// stream.defaultWriteObject();
// Serialization.writeMap(this, stream);
// }
//
//// @GwtIncompatible // java.io.ObjectInputStream
// private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
// stream.defaultReadObject();
// int size = Serialization.readCount(stream);
// init(16); // resist hostile attempts to allocate gratuitous heap
// Serialization.populateMap(this, stream, size);
// }
// @GwtIncompatible // Not needed in emulated source
private static final long serialVersionUID = 0;
}
@@ -0,0 +1,75 @@
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.com.google.common.collect;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.primitives.Ints;
/**
* Static methods for implementing hash-based collections.
*
* @author Kevin Bourrillion
* @author Jesse Wilson
* @author Austin Appleby
*/
@GwtCompatible
final class Hashing {
private Hashing() {}
/*
* These should be ints, but we need to use longs to force GWT to do the multiplications with
* enough precision.
*/
private static final long C1 = 0xcc9e2d51;
private static final long C2 = 0x1b873593;
/*
* This method was rewritten in Java from an intermediate step of the Murmur hash function in
* http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which contained the
* following header:
*
* MurmurHash3 was written by Austin Appleby, and is placed in the public domain. The author
* hereby disclaims copyright to this source code.
*/
static int smear(int hashCode) {
return (int) (C2 * Integer.rotateLeft((int) (hashCode * C1), 15));
}
static int smearedHash(@Nullable Object o) {
return smear((o == null) ? 0 : o.hashCode());
}
private static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO;
static int closedTableSize(int expectedEntries, double loadFactor) {
// Get the recommended table size.
// Round down to the nearest power of 2.
expectedEntries = Math.max(expectedEntries, 2);
int tableSize = Integer.highestOneBit(expectedEntries);
// Check to make sure that we will not exceed the maximum load factor.
if (expectedEntries > (int) (loadFactor * tableSize)) {
tableSize <<= 1;
return (tableSize > 0) ? tableSize : MAX_TABLE_SIZE;
}
return tableSize;
}
static boolean needsResizing(int size, int tableSize, double loadFactor) {
return size > loadFactor * tableSize && tableSize < MAX_TABLE_SIZE;
}
}
@@ -0,0 +1,446 @@
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.com.google.common.collect;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Predicate;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/**
* A {@link Collection} whose contents will never change, and which offers a few additional
* guarantees detailed below.
*
* <p><b>Warning:</b> avoid <i>direct</i> usage of {@link ImmutableCollection} as a type (just as
* with {@link Collection} itself). Prefer subtypes such as {@link ImmutableSet} or {@link
* ImmutableList}, which have well-defined {@link #equals} semantics, thus avoiding a common source
* of bugs and confusion.
*
* <h3>About <i>all</i> {@code Immutable-} collections</h3>
*
* <p>The remainder of this documentation applies to every public {@code Immutable-} type in this
* package, whether it is a subtype of {@code ImmutableCollection} or not.
*
* <h4>Guarantees</h4>
*
* <p>Each makes the following guarantees:
*
* <ul>
* <li><b>Shallow immutability.</b> Elements can never be added, removed or replaced in this
* collection. This is a stronger guarantee than that of {@link
* Collections#unmodifiableCollection}, whose contents change whenever the wrapped collection
* is modified.
* <li><b>Null-hostility.</b> This collection will never contain a null element.
* <li><b>Deterministic iteration.</b> The iteration order is always well-defined, depending on
* how the collection was created. Typically this is insertion order unless an explicit
* ordering is otherwise specified (e.g. {@link ImmutableSortedSet#naturalOrder}). See the
* appropriate factory method for details. View collections such as {@link
* ImmutableMultiset#elementSet} iterate in the same order as the parent, except as noted.
* <li><b>Thread safety.</b> It is safe to access this collection concurrently from multiple
* threads.
* <li><b>Integrity.</b> This type cannot be subclassed outside this package (which would allow
* these guarantees to be violated).
* </ul>
*
* <h4>"Interfaces", not implementations</h4>
*
* <p>These are classes instead of interfaces to prevent external subtyping, but should be thought
* of as interfaces in every important sense. Each public class such as {@link ImmutableSet} is a
* <i>type</i> offering meaningful behavioral guarantees. This is substantially different from the
* case of (say) {@link HashSet}, which is an <i>implementation</i>, with semantics that were
* largely defined by its supertype.
*
* <p>For field types and method return types, you should generally use the immutable type (such as
* {@link ImmutableList}) instead of the general collection interface type (such as {@link List}).
* This communicates to your callers all of the semantic guarantees listed above, which is almost
* always very useful information.
*
* <p>On the other hand, a <i>parameter</i> type of {@link ImmutableList} is generally a nuisance to
* callers. Instead, accept {@link Iterable} and have your method or constructor body pass it to the
* appropriate {@code copyOf} method itself.
*
* <p>Expressing the immutability guarantee directly in the type that user code references is a
* powerful advantage. Although Java offers certain immutable collection factory methods, such as
* {@link Collections#singleton(Object)} and <a
* href="https://docs.oracle.com/javase/9/docs/api/java/util/Set.html#immutable">{@code Set.of}</a>,
* we recommend using <i>these</i> classes instead for this reason (as well as for consistency).
*
* <h4>Creation</h4>
*
* <p>Except for logically "abstract" types like {@code ImmutableCollection} itself, each {@code
* Immutable} type provides the static operations you need to obtain instances of that type. These
* usually include:
*
* <ul>
* <li>Static methods named {@code of}, accepting an explicit list of elements or entries.
* <li>Static methods named {@code copyOf} (or {@code copyOfSorted}), accepting an existing
* collection whose contents should be copied.
* <li>A static nested {@code Builder} class which can be used to populate a new immutable
* instance.
* </ul>
*
* <h4>Warnings</h4>
*
* <ul>
* <li><b>Warning:</b> as with any collection, it is almost always a bad idea to modify an element
* (in a way that affects its {@link Object#equals} behavior) while it is contained in a
* collection. Undefined behavior and bugs will result. It's generally best to avoid using
* mutable objects as elements at all, as many users may expect your "immutable" object to be
* <i>deeply</i> immutable.
* </ul>
*
* <h4>Performance notes</h4>
*
* <ul>
* <li>Implementations can be generally assumed to prioritize memory efficiency, then speed of
* access, and lastly speed of creation.
* <li>The {@code copyOf} methods will sometimes recognize that the actual copy operation is
* unnecessary; for example, {@code copyOf(copyOf(anArrayList))} should copy the data only
* once. This reduces the expense of habitually making defensive copies at API boundaries.
* However, the precise conditions for skipping the copy operation are undefined.
* <li><b>Warning:</b> a view collection such as {@link ImmutableMap#keySet} or {@link
* ImmutableList#subList} may retain a reference to the entire data set, preventing it from
* being garbage collected. If some of the data is no longer reachable through other means,
* this constitutes a memory leak. Pass the view collection to the appropriate {@code copyOf}
* method to obtain a correctly-sized copy.
* <li>The performance of using the associated {@code Builder} class can be assumed to be no
* worse, and possibly better, than creating a mutable collection and copying it.
* <li>Implementations generally do not cache hash codes. If your element or key type has a slow
* {@code hashCode} implementation, it should cache it itself.
* </ul>
*
* <h4>Example usage</h4>
*
* <pre>{@code
* class Foo {
* private static final ImmutableSet<String> RESERVED_CODES =
* ImmutableSet.of("AZ", "CQ", "ZX");
*
* private final ImmutableSet<String> codes;
*
* public Foo(Iterable<String> codes) {
* this.codes = ImmutableSet.copyOf(codes);
* checkArgument(Collections.disjoint(this.codes, RESERVED_CODES));
* }
* }
* }</pre>
*
* <h3>See also</h3>
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
*
* @since 2.0
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
// TODO(kevinb): I think we should push everything down to "BaseImmutableCollection" or something,
// just to do everything we can to emphasize the "practically an interface" nature of this class.
public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable {
/*
* We expect SIZED (and SUBSIZED, if applicable) to be added by the spliterator factory methods.
* These are properties of the collection as a whole; SIZED and SUBSIZED are more properties of
* the spliterator implementation.
*/
static final int SPLITERATOR_CHARACTERISTICS =
Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.ORDERED;
ImmutableCollection() {}
/** Returns an unmodifiable iterator across the elements in this collection. */
@Override
public abstract UnmodifiableIterator<E> iterator();
@Override
public Spliterator<E> spliterator() {
return Spliterators.spliterator(this, SPLITERATOR_CHARACTERISTICS);
}
private static final Object[] EMPTY_ARRAY = {};
@Override
public final Object[] toArray() {
return toArray(EMPTY_ARRAY);
}
@CanIgnoreReturnValue
@Override
public final <T> T[] toArray(T[] other) {
checkNotNull(other);
int size = size();
if (other.length < size) {
Object[] internal = internalArray();
if (internal != null) {
return Platform.copy(internal, internalArrayStart(), internalArrayEnd(), other);
}
other = ObjectArrays.newArray(other, size);
} else if (other.length > size) {
other[size] = null;
}
copyIntoArray(other, 0);
return other;
}
/** If this collection is backed by an array of its elements in insertion order, returns it. */
@Nullable
Object[] internalArray() {
return null;
}
/**
* If this collection is backed by an array of its elements in insertion order, returns the offset
* where this collection's elements start.
*/
int internalArrayStart() {
throw new UnsupportedOperationException();
}
/**
* If this collection is backed by an array of its elements in insertion order, returns the offset
* where this collection's elements end.
*/
int internalArrayEnd() {
throw new UnsupportedOperationException();
}
@Override
public abstract boolean contains(@Nullable Object object);
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public final boolean add(E e) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public final boolean remove(Object object) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public final boolean addAll(Collection<? extends E> newElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public final boolean removeAll(Collection<?> oldElements) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public final boolean removeIf(Predicate<? super E> filter) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean retainAll(Collection<?> elementsToKeep) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final void clear() {
throw new UnsupportedOperationException();
}
/**
* Returns {@code true} if this immutable collection's implementation contains references to
* user-created objects that aren't accessible via this collection's methods. This is generally
* used to determine whether {@code copyOf} implementations should make an explicit copy to avoid
* memory leaks.
*/
abstract boolean isPartialView();
/**
* Copies the contents of this immutable collection into the specified array at the specified
* offset. Returns {@code offset + size()}.
*/
@CanIgnoreReturnValue
int copyIntoArray(Object[] dst, int offset) {
for (E e : this) {
dst[offset++] = e;
}
return offset;
}
/**
* Abstract base class for builders of {@link ImmutableCollection} types.
*
* @since 10.0
*/
public abstract static class Builder<E> {
static final int DEFAULT_INITIAL_CAPACITY = 4;
static int expandedCapacity(int oldCapacity, int minCapacity) {
if (minCapacity < 0) {
throw new AssertionError("cannot store more than MAX_VALUE elements");
}
// careful of overflow!
int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
if (newCapacity < minCapacity) {
newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
}
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
// guaranteed to be >= newCapacity
}
return newCapacity;
}
Builder() {}
/**
* Adds {@code element} to the {@code ImmutableCollection} being built.
*
* <p>Note that each builder class covariantly returns its own type from this method.
*
* @param element the element to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code element} is null
*/
@CanIgnoreReturnValue
public abstract Builder<E> add(E element);
/**
* Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
*
* <p>Note that each builder class overrides this method in order to covariantly return its own
* type.
*
* @param elements the elements to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code elements} is null or contains a null element
*/
@CanIgnoreReturnValue
public Builder<E> add(E... elements) {
for (E element : elements) {
add(element);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
*
* <p>Note that each builder class overrides this method in order to covariantly return its own
* type.
*
* @param elements the elements to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code elements} is null or contains a null element
*/
@CanIgnoreReturnValue
public Builder<E> addAll(Iterable<? extends E> elements) {
for (E element : elements) {
add(element);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
*
* <p>Note that each builder class overrides this method in order to covariantly return its own
* type.
*
* @param elements the elements to add
* @return this {@code Builder} instance
* @throws NullPointerException if {@code elements} is null or contains a null element
*/
@CanIgnoreReturnValue
public Builder<E> addAll(Iterator<? extends E> elements) {
while (elements.hasNext()) {
add(elements.next());
}
return this;
}
/**
* Returns a newly-created {@code ImmutableCollection} of the appropriate type, containing the
* elements provided to this builder.
*
* <p>Note that each builder class covariantly returns the appropriate type of {@code
* ImmutableCollection} from this method.
*/
public abstract ImmutableCollection<E> build();
}
}
@@ -0,0 +1,50 @@
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.com.google.common.collect;
import java.io.Serializable;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.GwtCompatible;
/** @see org.docx4j.com.google.common.collect.Maps#immutableEntry(Object, Object) */
@GwtCompatible(serializable = true)
class ImmutableEntry<K, V> extends AbstractMapEntry<K, V> implements Serializable {
final @Nullable K key;
final @Nullable V value;
ImmutableEntry(@Nullable K key, @Nullable V value) {
this.key = key;
this.value = value;
}
@Override
public final @Nullable K getKey() {
return key;
}
@Override
public final @Nullable V getValue() {
return value;
}
@Override
public final V setValue(V value) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
@@ -0,0 +1,926 @@
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.com.google.common.collect;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import static org.docx4j.com.google.common.base.Preconditions.checkState;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.Beta;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.annotations.VisibleForTesting;
/**
* A {@link Map} whose contents will never change, with many other important properties detailed at
* {@link ImmutableCollection}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
* @since 2.0
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
// /**
// * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
// * and values are the result of applying the provided mapping functions to the input elements.
// * Entries appear in the result {@code ImmutableMap} in encounter order.
// *
// * <p>If the mapped keys contain duplicates (according to {@link Object#equals(Object)}, an {@code
// * IllegalArgumentException} is thrown when the collection operation is performed. (This differs
// * from the {@code Collector} returned by {@link Collectors#toMap(Function, Function)}, which
// * throws an {@code IllegalStateException}.)
// *
// * @since 21.0
// */
// public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
// Function<? super T, ? extends K> keyFunction,
// Function<? super T, ? extends V> valueFunction) {
// return CollectCollectors.toImmutableMap(keyFunction, valueFunction);
// }
//
// /**
// * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
// * and values are the result of applying the provided mapping functions to the input elements.
// *
// * <p>If the mapped keys contain duplicates (according to {@link Object#equals(Object)}), the
// * values are merged using the specified merging function. Entries will appear in the encounter
// * order of the first occurrence of the key.
// *
// * @since 21.0
// */
// public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
// Function<? super T, ? extends K> keyFunction,
// Function<? super T, ? extends V> valueFunction,
// BinaryOperator<V> mergeFunction) {
// checkNotNull(keyFunction);
// checkNotNull(valueFunction);
// checkNotNull(mergeFunction);
// return Collectors.collectingAndThen(
// Collectors.toMap(keyFunction, valueFunction, mergeFunction, LinkedHashMap::new),
// ImmutableMap::copyOf);
// }
//
// /**
// * Returns the empty map. This map behaves and performs comparably to {@link
// * Collections#emptyMap}, and is preferable mainly for consistency and maintainability of your
// * code.
// */
// @SuppressWarnings("unchecked")
// public static <K, V> ImmutableMap<K, V> of() {
// return (ImmutableMap<K, V>) RegularImmutableMap.EMPTY;
// }
//
// /**
// * Returns an immutable map containing a single entry. This map behaves and performs comparably to
// * {@link Collections#singletonMap} but will not accept a null key or value. It is preferable
// * mainly for consistency and maintainability of your code.
// */
// public static <K, V> ImmutableMap<K, V> of(K k1, V v1) {
// return ImmutableBiMap.of(k1, v1);
// }
//
// /**
// * Returns an immutable map containing the given entries, in order.
// *
// * @throws IllegalArgumentException if duplicate keys are provided
// */
// public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) {
// return RegularImmutableMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2));
// }
//
// /**
// * Returns an immutable map containing the given entries, in order.
// *
// * @throws IllegalArgumentException if duplicate keys are provided
// */
// public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
// return RegularImmutableMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
// }
//
// /**
// * Returns an immutable map containing the given entries, in order.
// *
// * @throws IllegalArgumentException if duplicate keys are provided
// */
// public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
// return RegularImmutableMap.fromEntries(
// entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
// }
//
// /**
// * Returns an immutable map containing the given entries, in order.
// *
// * @throws IllegalArgumentException if duplicate keys are provided
// */
// public static <K, V> ImmutableMap<K, V> of(
// K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
// return RegularImmutableMap.fromEntries(
// entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
// }
//
// // looking for of() with > 5 entries? Use the builder instead.
//
// /**
// * Verifies that {@code key} and {@code value} are non-null, and returns a new immutable entry
// * with those values.
// *
// * <p>A call to {@link Entry#setValue} on the returned entry will always throw {@link
// * UnsupportedOperationException}.
// */
// static <K, V> Entry<K, V> entryOf(K key, V value) {
// checkEntryNotNull(key, value);
// return new AbstractMap.SimpleImmutableEntry<>(key, value);
// }
//
// /**
// * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
// * Builder} constructor.
// */
// public static <K, V> Builder<K, V> builder() {
// return new Builder<>();
// }
//
// /**
// * Returns a new builder, expecting the specified number of entries to be added.
// *
// * <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link
// * Builder#build} is called, the builder is likely to perform better than an unsized {@link
// * #builder()} would have.
// *
// * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
// * but not exactly, the number of entries added to the builder.
// *
// * @since 23.1
// */
// @Beta
// public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
// checkNonnegative(expectedSize, "expectedSize");
// return new Builder<>(expectedSize);
// }
static void checkNoConflict(
boolean safe, String conflictDescription, Entry<?, ?> entry1, Entry<?, ?> entry2) {
if (!safe) {
throw conflictException(conflictDescription, entry1, entry2);
}
}
static IllegalArgumentException conflictException(
String conflictDescription, Object entry1, Object entry2) {
return new IllegalArgumentException(
"Multiple entries with same " + conflictDescription + ": " + entry1 + " and " + entry2);
}
// /**
// * A builder for creating immutable map instances, especially {@code public static final} maps
// * ("constant maps"). Example:
// *
// * <pre>{@code
// * static final ImmutableMap<String, Integer> WORD_TO_INT =
// * new ImmutableMap.Builder<String, Integer>()
// * .put("one", 1)
// * .put("two", 2)
// * .put("three", 3)
// * .build();
// * }</pre>
// *
// * <p>For <i>small</i> immutable maps, the {@code ImmutableMap.of()} methods are even more
// * convenient.
// *
// * <p>By default, a {@code Builder} will generate maps that iterate over entries in the order they
// * were inserted into the builder, equivalently to {@code LinkedHashMap}. For example, in the
// * above example, {@code WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the
// * order {@code "one"=1, "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect
// * the same order. If you want a different order, consider using {@link ImmutableSortedMap} to
// * sort by keys, or call {@link #orderEntriesByValue(Comparator)}, which changes this builder to
// * sort entries by value.
// *
// * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build
// * multiple maps in series. Each map is a superset of the maps created before it.
// *
// * @since 2.0
// */
// public static class Builder<K, V> {
// @MonotonicNonNull Comparator<? super V> valueComparator;
// Entry<K, V>[] entries;
// int size;
// boolean entriesUsed;
//
// /**
// * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
// * ImmutableMap#builder}.
// */
// public Builder() {
// this(ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY);
// }
//
// @SuppressWarnings("unchecked")
// Builder(int initialCapacity) {
// this.entries = new Entry[initialCapacity];
// this.size = 0;
// this.entriesUsed = false;
// }
//
// private void ensureCapacity(int minCapacity) {
// if (minCapacity > entries.length) {
// entries =
// Arrays.copyOf(
// entries, ImmutableCollection.Builder.expandedCapacity(entries.length, minCapacity));
// entriesUsed = false;
// }
// }
//
// /**
// * Associates {@code key} with {@code value} in the built map. Duplicate keys are not allowed,
// * and will cause {@link #build} to fail.
// */
// @CanIgnoreReturnValue
// public Builder<K, V> put(K key, V value) {
// ensureCapacity(size + 1);
// Entry<K, V> entry = entryOf(key, value);
// // don't inline this: we want to fail atomically if key or value is null
// entries[size++] = entry;
// return this;
// }
//
// /**
// * Adds the given {@code entry} to the map, making it immutable if necessary. Duplicate keys are
// * not allowed, and will cause {@link #build} to fail.
// *
// * @since 11.0
// */
// @CanIgnoreReturnValue
// public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
// return put(entry.getKey(), entry.getValue());
// }
//
// /**
// * Associates all of the given map's keys and values in the built map. Duplicate keys are not
// * allowed, and will cause {@link #build} to fail.
// *
// * @throws NullPointerException if any key or value in {@code map} is null
// */
// @CanIgnoreReturnValue
// public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
// return putAll(map.entrySet());
// }
//
// /**
// * Adds all of the given entries to the built map. Duplicate keys are not allowed, and will
// * cause {@link #build} to fail.
// *
// * @throws NullPointerException if any key, value, or entry is null
// * @since 19.0
// */
// @CanIgnoreReturnValue
// @Beta
// public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
// if (entries instanceof Collection) {
// ensureCapacity(size + ((Collection<?>) entries).size());
// }
// for (Entry<? extends K, ? extends V> entry : entries) {
// put(entry);
// }
// return this;
// }
//
// /**
// * Configures this {@code Builder} to order entries by value according to the specified
// * comparator.
// *
// * <p>The sort order is stable, that is, if two entries have values that compare as equivalent,
// * the entry that was inserted first will be first in the built map's iteration order.
// *
// * @throws IllegalStateException if this method was already called
// * @since 19.0
// */
// @CanIgnoreReturnValue
// @Beta
// public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
// checkState(this.valueComparator == null, "valueComparator was already set");
// this.valueComparator = checkNotNull(valueComparator, "valueComparator");
// return this;
// }
//
// @CanIgnoreReturnValue
// Builder<K, V> combine(Builder<K, V> other) {
// checkNotNull(other);
// ensureCapacity(this.size + other.size);
// System.arraycopy(other.entries, 0, this.entries, this.size, other.size);
// this.size += other.size;
// return this;
// }
//
// /*
// * TODO(kevinb): Should build() and the ImmutableBiMap & ImmutableSortedMap
// * versions throw an IllegalStateException instead?
// */
//
//// /**
//// * Returns a newly-created immutable map. The iteration order of the returned map is the order
//// * in which entries were inserted into the builder, unless {@link #orderEntriesByValue} was
//// * called, in which case entries are sorted by value.
//// *
//// * @throws IllegalArgumentException if duplicate keys were added
//// */
//// public ImmutableMap<K, V> build() {
//// /*
//// * If entries is full, or if hash flooding is detected, then this implementation may end up
//// * using the entries array directly and writing over the entry objects with non-terminal
//// * entries, but this is safe; if this Builder is used further, it will grow the entries array
//// * (so it can't affect the original array), and future build() calls will always copy any
//// * entry objects that cannot be safely reused.
//// */
//// if (valueComparator != null) {
//// if (entriesUsed) {
//// entries = Arrays.copyOf(entries, size);
//// }
//// Arrays.sort(
//// entries, 0, size, Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction()));
//// }
//// switch (size) {
//// case 0:
//// return of();
//// case 1:
//// return of(entries[0].getKey(), entries[0].getValue());
//// default:
//// entriesUsed = true;
//// return RegularImmutableMap.fromEntryArray(size, entries);
//// }
//// }
////
//// @VisibleForTesting // only for testing JDK backed implementation
//// ImmutableMap<K, V> buildJdkBacked() {
//// checkState(
//// valueComparator == null, "buildJdkBacked is only for testing; can't use valueComparator");
//// switch (size) {
//// case 0:
//// return of();
//// case 1:
//// return of(entries[0].getKey(), entries[0].getValue());
//// default:
//// entriesUsed = true;
//// return JdkBackedImmutableMap.create(size, entries);
//// }
//// }
//// }
////
/**
* Returns an immutable map containing the same entries as {@code map}. The returned map iterates
* over entries in the same order as the {@code entrySet} of the original map. If {@code map}
* somehow contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
* comparator is not <i>consistent with equals</i>), the results of this method are undefined.
*
* <p>Despite the method name, this method attempts to avoid actually copying the data when it is
* safe to do so. The exact circumstances under which a copy will or will not be performed are
* undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code map} is null
*/
public static <K, V> ImmutableMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
if ((map instanceof ImmutableMap) && !(map instanceof SortedMap)) {
@SuppressWarnings("unchecked") // safe since map is not writable
ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map;
if (!kvMap.isPartialView()) {
return kvMap;
}
}
// else if (map instanceof EnumMap) {
// @SuppressWarnings("unchecked") // safe since map is not writable
// ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) copyOfEnumMap((EnumMap<?, ?>) map);
// return kvMap;
// }
System.out.println("PANIC!");
return null;
// return copyOf(map.entrySet());
}
// /**
// * Returns an immutable map containing the specified entries. The returned map iterates over
// * entries in the same order as the original iterable.
// *
// * @throws NullPointerException if any key, value, or entry is null
// * @throws IllegalArgumentException if two entries have the same key
// * @since 19.0
// */
// @Beta
// public static <K, V> ImmutableMap<K, V> copyOf(
// Iterable<? extends Entry<? extends K, ? extends V>> entries) {
// @SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant
// Entry<K, V>[] entryArray = (Entry<K, V>[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY);
// switch (entryArray.length) {
// case 0:
// return of();
// case 1:
// Entry<K, V> onlyEntry = entryArray[0];
// return of(onlyEntry.getKey(), onlyEntry.getValue());
// default:
// /*
// * The current implementation will end up using entryArray directly, though it will write
// * over the (arbitrary, potentially mutable) Entry objects actually stored in entryArray.
// */
// return RegularImmutableMap.fromEntries(entryArray);
// }
// }
////
//// private static <K extends Enum<K>, V> ImmutableMap<K, V> copyOfEnumMap(
//// EnumMap<K, ? extends V> original) {
//// EnumMap<K, V> copy = new EnumMap<>(original);
//// for (Entry<?, ?> entry : copy.entrySet()) {
//// checkEntryNotNull(entry.getKey(), entry.getValue());
//// }
//// return ImmutableEnumMap.asImmutable(copy);
//// }
//
// static final Entry<?, ?>[] EMPTY_ENTRY_ARRAY = new Entry<?, ?>[0];
//
//// abstract static class IteratorBasedImmutableMap<K, V> extends ImmutableMap<K, V> {
//// abstract UnmodifiableIterator<Entry<K, V>> entryIterator();
////
//// Spliterator<Entry<K, V>> entrySpliterator() {
//// return Spliterators.spliterator(
//// entryIterator(),
//// size(),
//// Spliterator.DISTINCT | Spliterator.NONNULL | Spliterator.IMMUTABLE | Spliterator.ORDERED);
//// }
////
//// @Override
//// ImmutableSet<K> createKeySet() {
//// return new ImmutableMapKeySet<>(this);
//// }
////
//// @Override
//// ImmutableSet<Entry<K, V>> createEntrySet() {
//// class EntrySetImpl extends ImmutableMapEntrySet<K, V> {
//// @Override
//// ImmutableMap<K, V> map() {
//// return IteratorBasedImmutableMap.this;
//// }
////
//// @Override
//// public UnmodifiableIterator<Entry<K, V>> iterator() {
//// return entryIterator();
//// }
//// }
//// return new EntrySetImpl();
//// }
////
//// @Override
//// ImmutableCollection<V> createValues() {
//// return new ImmutableMapValues<>(this);
//// }
//// }
////
//// ImmutableMap() {}
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @CanIgnoreReturnValue
//// @Deprecated
//// @Override
//// public final V put(K k, V v) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @CanIgnoreReturnValue
//// @Deprecated
//// @Override
//// public final V putIfAbsent(K key, V value) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final boolean replace(K key, V oldValue, V newValue) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final V replace(K key, V value) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final V computeIfPresent(
//// K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final V merge(
//// K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final void putAll(Map<? extends K, ? extends V> map) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final V remove(Object o) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final boolean remove(Object key, Object value) {
//// throw new UnsupportedOperationException();
//// }
////
//// /**
//// * Guaranteed to throw an exception and leave the map unmodified.
//// *
//// * @throws UnsupportedOperationException always
//// * @deprecated Unsupported operation.
//// */
//// @Deprecated
//// @Override
//// public final void clear() {
//// throw new UnsupportedOperationException();
//// }
//
//// @Override
// public boolean isEmpty() {
// return size() == 0;
// }
//
//// @Override
// public boolean containsKey(@Nullable Object key) {
// return get(key) != null;
// }
//
//// @Override
// public boolean containsValue(@Nullable Object value) {
// return values().contains(value);
// }
//
// // Overriding to mark it Nullable
// @Override
// public abstract V get(@Nullable Object key);
//
// /**
// * @since 21.0 (but only since 23.5 in the Android <a
// * href="https://github.com/google/guava#guava-google-core-libraries-for-java">flavor</a>).
// * Note, however, that Java 8 users can call this method with any version and flavor of Guava.
// */
// @Override
// public final V getOrDefault(@Nullable Object key, @Nullable V defaultValue) {
// V result = get(key);
// return (result != null) ? result : defaultValue;
// }
//
// @LazyInit @RetainedWith private transient ImmutableSet<Entry<K, V>> entrySet;
//
// /**
// * Returns an immutable set of the mappings in this map. The iteration order is specified by the
// * method used to create this map. Typically, this is insertion order.
// */
// @Override
// public ImmutableSet<Entry<K, V>> entrySet() {
// ImmutableSet<Entry<K, V>> result = entrySet;
// return (result == null) ? entrySet = createEntrySet() : result;
// }
//
// abstract ImmutableSet<Entry<K, V>> createEntrySet();
//
// @LazyInit @RetainedWith private transient ImmutableSet<K> keySet;
//
// /**
// * Returns an immutable set of the keys in this map, in the same order that they appear in {@link
// * #entrySet}.
// */
// @Override
// public ImmutableSet<K> keySet() {
// ImmutableSet<K> result = keySet;
// return (result == null) ? keySet = createKeySet() : result;
// }
//
// /*
// * This could have a good default implementation of return new ImmutableKeySet<K, V>(this),
// * but ProGuard can't figure out how to eliminate that default when RegularImmutableMap
// * overrides it.
// */
// abstract ImmutableSet<K> createKeySet();
//
// UnmodifiableIterator<K> keyIterator() {
// final UnmodifiableIterator<Entry<K, V>> entryIterator = entrySet().iterator();
// return new UnmodifiableIterator<K>() {
// @Override
// public boolean hasNext() {
// return entryIterator.hasNext();
// }
//
// @Override
// public K next() {
// return entryIterator.next().getKey();
// }
// };
// }
//
// Spliterator<K> keySpliterator() {
// return CollectSpliterators.map(entrySet().spliterator(), Entry::getKey);
// }
//
// @LazyInit @RetainedWith private transient ImmutableCollection<V> values;
//
// /**
// * Returns an immutable collection of the values in this map, in the same order that they appear
// * in {@link #entrySet}.
// */
//// @Override
// public ImmutableCollection<V> values() {
// ImmutableCollection<V> result = values;
// return (result == null) ? values = createValues() : result;
// }
//
// /*
// * This could have a good default implementation of {@code return new
// * ImmutableMapValues<K, V>(this)}, but ProGuard can't figure out how to eliminate that default
// * when RegularImmutableMap overrides it.
// */
// abstract ImmutableCollection<V> createValues();
//
// // cached so that this.multimapView().inverse() only computes inverse once
// @LazyInit private transient ImmutableSetMultimap<K, V> multimapView;
//
// /**
// * Returns a multimap view of the map.
// *
// * @since 14.0
// */
// public ImmutableSetMultimap<K, V> asMultimap() {
// if (isEmpty()) {
// return ImmutableSetMultimap.of();
// }
// ImmutableSetMultimap<K, V> result = multimapView;
// return (result == null)
// ? (multimapView =
// new ImmutableSetMultimap<>(new MapViewOfValuesAsSingletonSets(), size(), null))
// : result;
// }
//
// @WeakOuter
// private final class MapViewOfValuesAsSingletonSets
// extends IteratorBasedImmutableMap<K, ImmutableSet<V>> {
//
// @Override
// public int size() {
// return ImmutableMap.this.size();
// }
//
// @Override
// ImmutableSet<K> createKeySet() {
// return ImmutableMap.this.keySet();
// }
//
// @Override
// public boolean containsKey(@Nullable Object key) {
// return ImmutableMap.this.containsKey(key);
// }
//
// @Override
// public ImmutableSet<V> get(@Nullable Object key) {
// V outerValue = ImmutableMap.this.get(key);
// return (outerValue == null) ? null : ImmutableSet.of(outerValue);
// }
//
// @Override
// boolean isPartialView() {
// return ImmutableMap.this.isPartialView();
// }
//
// @Override
// public int hashCode() {
// // ImmutableSet.of(value).hashCode() == value.hashCode(), so the hashes are the same
// return ImmutableMap.this.hashCode();
// }
//
// @Override
// boolean isHashCodeFast() {
// return ImmutableMap.this.isHashCodeFast();
// }
//
// @Override
// UnmodifiableIterator<Entry<K, ImmutableSet<V>>> entryIterator() {
// final Iterator<Entry<K, V>> backingIterator = ImmutableMap.this.entrySet().iterator();
// return new UnmodifiableIterator<Entry<K, ImmutableSet<V>>>() {
// @Override
// public boolean hasNext() {
// return backingIterator.hasNext();
// }
//
// @Override
// public Entry<K, ImmutableSet<V>> next() {
// final Entry<K, V> backingEntry = backingIterator.next();
// return new AbstractMapEntry<K, ImmutableSet<V>>() {
// @Override
// public K getKey() {
// return backingEntry.getKey();
// }
//
// @Override
// public ImmutableSet<V> getValue() {
// return ImmutableSet.of(backingEntry.getValue());
// }
// };
// }
// };
// }
// }
//
// @Override
// public boolean equals(@Nullable Object object) {
// return Maps.equalsImpl(this, object);
// }
//
abstract boolean isPartialView();
//
// @Override
// public int hashCode() {
// return Sets.hashCodeImpl(entrySet());
// }
//
// boolean isHashCodeFast() {
// return false;
// }
//
// @Override
// public String toString() {
// return Maps.toStringImpl(this);
// }
//
// /**
// * Serialized type for all ImmutableMap instances. It captures the logical contents and they are
// * reconstructed using public factory methods. This ensures that the implementation types remain
// * as implementation details.
// */
// static class SerializedForm implements Serializable {
// private final Object[] keys;
// private final Object[] values;
//
// SerializedForm(ImmutableMap<?, ?> map) {
// keys = new Object[map.size()];
// values = new Object[map.size()];
// int i = 0;
// for (Entry<?, ?> entry : map.entrySet()) {
// keys[i] = entry.getKey();
// values[i] = entry.getValue();
// i++;
// }
// }
//
// Object readResolve() {
// Builder<Object, Object> builder = new Builder<>(keys.length);
// return createMap(builder);
// }
//
// Object createMap(Builder<Object, Object> builder) {
// for (int i = 0; i < keys.length; i++) {
// builder.put(keys[i], values[i]);
// }
// return builder.build();
// }
//
// private static final long serialVersionUID = 0;
// }
//
// Object writeReplace() {
// return new SerializedForm(this);
// }
}
@@ -0,0 +1,879 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.docx4j.com.google.common.collect;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import static org.docx4j.com.google.common.base.Preconditions.checkArgument;
import static org.docx4j.com.google.common.base.Preconditions.checkNotNull;
import java.io.Serializable;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Collector;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.docx4j.com.google.common.annotations.Beta;
import org.docx4j.com.google.common.annotations.GwtCompatible;
import org.docx4j.com.google.common.annotations.VisibleForTesting;
import org.docx4j.com.google.common.math.IntMath;
import org.docx4j.com.google.common.primitives.Ints;
/**
* A {@link Set} whose contents will never change, with many other important properties detailed at
* {@link ImmutableCollection}.
*
* @since 2.0
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> {
static final int SPLITERATOR_CHARACTERISTICS =
ImmutableCollection.SPLITERATOR_CHARACTERISTICS | Spliterator.DISTINCT;
// /**
// * Returns a {@code Collector} that accumulates the input elements into a new {@code
// * ImmutableSet}. Elements appear in the resulting set in the encounter order of the stream; if
// * the stream contains duplicates (according to {@link Object#equals(Object)}), only the first
// * duplicate in encounter order will appear in the result.
// *
// * @since 21.0
// */
// public static <E> Collector<E, ?, ImmutableSet<E>> toImmutableSet() {
// return CollectCollectors.toImmutableSet();
// }
/**
* Returns the empty immutable set. Preferred over {@link Collections#emptySet} for code
* consistency, and because the return type conveys the immutability guarantee.
*/
@SuppressWarnings({"unchecked"}) // fully variant implementation (never actually produces any Es)
public static <E> ImmutableSet<E> of() {
return (ImmutableSet<E>) RegularImmutableSet.EMPTY;
}
/**
* Returns an immutable set containing {@code element}. Preferred over {@link
* Collections#singleton} for code consistency, {@code null} rejection, and because the return
* type conveys the immutability guarantee.
*/
public static <E> ImmutableSet<E> of(E element) {
return new SingletonImmutableSet<E>(element);
}
/**
* Returns an immutable set containing the given elements, minus duplicates, in the order each was
* first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
* the first are ignored.
*/
public static <E> ImmutableSet<E> of(E e1, E e2) {
return construct(2, 2, e1, e2);
}
/**
* Returns an immutable set containing the given elements, minus duplicates, in the order each was
* first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
* the first are ignored.
*/
public static <E> ImmutableSet<E> of(E e1, E e2, E e3) {
return construct(3, 3, e1, e2, e3);
}
/**
* Returns an immutable set containing the given elements, minus duplicates, in the order each was
* first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
* the first are ignored.
*/
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) {
return construct(4, 4, e1, e2, e3, e4);
}
/**
* Returns an immutable set containing the given elements, minus duplicates, in the order each was
* first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
* the first are ignored.
*/
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) {
return construct(5, 5, e1, e2, e3, e4, e5);
}
/**
* Returns an immutable set containing the given elements, minus duplicates, in the order each was
* first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
* the first are ignored.
*
* <p>The array {@code others} must not be longer than {@code Integer.MAX_VALUE - 6}.
*
* @since 3.0 (source-compatible since 2.0)
*/
@SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
checkArgument(
others.length <= Integer.MAX_VALUE - 6, "the total number of elements must fit in an int");
final int paramCount = 6;
Object[] elements = new Object[paramCount + others.length];
elements[0] = e1;
elements[1] = e2;
elements[2] = e3;
elements[3] = e4;
elements[4] = e5;
elements[5] = e6;
System.arraycopy(others, 0, elements, paramCount, others.length);
return construct(elements.length, elements.length, elements);
}
/**
* Constructs an {@code ImmutableSet} from the first {@code n} elements of the specified array,
* which we have no particular reason to believe does or does not contain duplicates. If {@code k}
* is the size of the returned {@code ImmutableSet}, then the unique elements of {@code elements}
* will be in the first {@code k} positions, and {@code elements[i] == null} for {@code k <= i <
* n}.
*
* <p>This may modify {@code elements}. Additionally, if {@code n == elements.length} and {@code
* elements} contains no duplicates, {@code elements} may be used without copying in the returned
* {@code ImmutableSet}, in which case the caller must not modify it.
*
* <p>{@code elements} may contain only values of type {@code E}.
*
* @throws NullPointerException if any of the first {@code n} elements of {@code elements} is null
*/
private static <E> ImmutableSet<E> constructUnknownDuplication(int n, Object... elements) {
// Guess the size is "halfway between" all duplicates and no duplicates, on a log scale.
return construct(
n,
Math.max(
ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY,
IntMath.sqrt(n, RoundingMode.CEILING)),
elements);
}
/**
* Constructs an {@code ImmutableSet} from the first {@code n} elements of the specified array. If
* {@code k} is the size of the returned {@code ImmutableSet}, then the unique elements of {@code
* elements} will be in the first {@code k} positions, and {@code elements[i] == null} for {@code
* k <= i < n}.
*
* <p>This may modify {@code elements}. Additionally, if {@code n == elements.length} and {@code
* elements} contains no duplicates, {@code elements} may be used without copying in the returned
* {@code ImmutableSet}, in which case it may no longer be modified.
*
* <p>{@code elements} may contain only values of type {@code E}.
*
* @throws NullPointerException if any of the first {@code n} elements of {@code elements} is null
*/
private static <E> ImmutableSet<E> construct(int n, int expectedSize, Object... elements) {
switch (n) {
case 0:
return of();
case 1:
@SuppressWarnings("unchecked") // safe; elements contains only E's
E elem = (E) elements[0];
return of(elem);
default:
SetBuilderImpl<E> builder = new RegularSetBuilderImpl<E>(expectedSize);
for (int i = 0; i < n; i++) {
@SuppressWarnings("unchecked")
E e = (E) checkNotNull(elements[i]);
builder = builder.add(e);
}
return builder.review().build();
}
}
/**
* Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
* each appears first in the source collection.
*
* <p><b>Performance note:</b> This method will sometimes recognize that the actual copy operation
* is unnecessary; for example, {@code copyOf(copyOf(anArrayList))} will copy the data only once.
* This reduces the expense of habitually making defensive copies at API boundaries. However, the
* precise conditions for skipping the copy operation are undefined.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 7.0 (source-compatible since 2.0)
*/
public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) {
/*
* TODO(lowasser): consider checking for ImmutableAsList here
* TODO(lowasser): consider checking for Multiset here
*/
// Don't refer to ImmutableSortedSet by name so it won't pull in all that code
if (elements instanceof ImmutableSet && !(elements instanceof SortedSet)) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableSet<E> set = (ImmutableSet<E>) elements;
if (!set.isPartialView()) {
return set;
}
}
// else if (elements instanceof EnumSet) {
// return copyOfEnumSet((EnumSet) elements);
// }
Object[] array = elements.toArray();
if (elements instanceof Set) {
// assume probably no duplicates (though it might be using different equality semantics)
return construct(array.length, array.length, array);
} else {
return constructUnknownDuplication(array.length, array);
}
}
/**
* Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
* each appears first in the source iterable. This method iterates over {@code elements} only
* once.
*
* <p><b>Performance note:</b> This method will sometimes recognize that the actual copy operation
* is unnecessary; for example, {@code copyOf(copyOf(anArrayList))} should copy the data only
* once. This reduces the expense of habitually making defensive copies at API boundaries.
* However, the precise conditions for skipping the copy operation are undefined.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) {
return (elements instanceof Collection)
? copyOf((Collection<? extends E>) elements)
: copyOf(elements.iterator());
}
/**
* Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
* each appears first in the source iterator.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) {
// We special-case for 0 or 1 elements, but anything further is madness.
if (!elements.hasNext()) {
return of();
}
E first = elements.next();
if (!elements.hasNext()) {
return of(first);
} else {
return new ImmutableSet.Builder<E>().add(first).addAll(elements).build();
}
}
/**
* Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
* each appears first in the source array.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 3.0
*/
public static <E> ImmutableSet<E> copyOf(E[] elements) {
switch (elements.length) {
case 0:
return of();
case 1:
return of(elements[0]);
default:
return constructUnknownDuplication(elements.length, elements.clone());
}
}
// @SuppressWarnings("rawtypes") // necessary to compile against Java 8
// private static ImmutableSet copyOfEnumSet(EnumSet enumSet) {
// return ImmutableEnumSet.asImmutable(EnumSet.copyOf(enumSet));
// }
ImmutableSet() {}
/** Returns {@code true} if the {@code hashCode()} method runs quickly. */
boolean isHashCodeFast() {
return false;
}
@Override
public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
} else if (object instanceof ImmutableSet
&& isHashCodeFast()
&& ((ImmutableSet<?>) object).isHashCodeFast()
&& hashCode() != object.hashCode()) {
return false;
}
return Sets.equalsImpl(this, object);
}
@Override
public int hashCode() {
return Sets.hashCodeImpl(this);
}
// This declaration is needed to make Set.iterator() and
// ImmutableCollection.iterator() consistent.
@Override
public abstract UnmodifiableIterator<E> iterator();
// @LazyInit @RetainedWith private transient @Nullable ImmutableList<E> asList;
//
// @Override
// public ImmutableList<E> asList() {
// ImmutableList<E> result = asList;
// return (result == null) ? asList = createAsList() : result;
// }
//
// ImmutableList<E> createAsList() {
// return new RegularImmutableAsList<E>(this, toArray());
// }
//
// abstract static class Indexed<E> extends ImmutableSet<E> {
// abstract E get(int index);
//
// @Override
// public UnmodifiableIterator<E> iterator() {
// return asList().iterator();
// }
//
// @Override
// public Spliterator<E> spliterator() {
// return CollectSpliterators.indexed(size(), SPLITERATOR_CHARACTERISTICS, this::get);
// }
//
// @Override
// public void forEach(Consumer<? super E> consumer) {
// checkNotNull(consumer);
// int n = size();
// for (int i = 0; i < n; i++) {
// consumer.accept(get(i));
// }
// }
//
// @Override
// int copyIntoArray(Object[] dst, int offset) {
// return asList().copyIntoArray(dst, offset);
// }
//
// @Override
// ImmutableList<E> createAsList() {
// return new ImmutableAsList<E>() {
// @Override
// public E get(int index) {
// return Indexed.this.get(index);
// }
//
// @Override
// Indexed<E> delegateCollection() {
// return Indexed.this;
// }
// };
// }
// }
/*
* This class is used to serialize all ImmutableSet instances, except for
* ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It
* captures their "logical contents" and they are reconstructed using public
* static factories. This is necessary to ensure that the existence of a
* particular implementation type is an implementation detail.
*/
private static class SerializedForm implements Serializable {
final Object[] elements;
SerializedForm(Object[] elements) {
this.elements = elements;
}
Object readResolve() {
return copyOf(elements);
}
private static final long serialVersionUID = 0;
}
// @Override
Object writeReplace() {
return new SerializedForm(toArray());
}
/**
* Returns a new builder. The generated builder is equivalent to the builder created by the {@link
* Builder} constructor.
*/
public static <E> Builder<E> builder() {
return new Builder<E>();
}
/**
* Returns a new builder, expecting the specified number of distinct elements to be added.
*
* <p>If {@code expectedSize} is exactly the number of distinct elements added to the builder
* before {@link Builder#build} is called, the builder is likely to perform better than an unsized
* {@link #builder()} would have.
*
* <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
* but not exactly, the number of distinct elements added to the builder.
*
* @since 23.1
*/
@Beta
public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
// checkNonnegative(expectedSize, "expectedSize");
return new Builder<E>(expectedSize);
}
/** Builds a new open-addressed hash table from the first n objects in elements. */
static Object[] rebuildHashTable(int newTableSize, Object[] elements, int n) {
Object[] hashTable = new Object[newTableSize];
int mask = hashTable.length - 1;
for (int i = 0; i < n; i++) {
Object e = elements[i];
int j0 = Hashing.smear(e.hashCode());
for (int j = j0; ; j++) {
int index = j & mask;
if (hashTable[index] == null) {
hashTable[index] = e;
break;
}
}
}
return hashTable;
}
/**
* A builder for creating {@code ImmutableSet} instances. Example:
*
* <pre>{@code
* static final ImmutableSet<Color> GOOGLE_COLORS =
* ImmutableSet.<Color>builder()
* .addAll(WEBSAFE_COLORS)
* .add(new Color(0, 191, 255))
* .build();
* }</pre>
*
* <p>Elements appear in the resulting set in the same order they were first added to the builder.
*
* <p>Building does not change the state of the builder, so it is still possible to add more
* elements and to build again.
*
* @since 2.0
*/
public static class Builder<E> extends ImmutableCollection.Builder<E> {
private SetBuilderImpl<E> impl;
boolean forceCopy;
public Builder() {
this(DEFAULT_INITIAL_CAPACITY);
}
Builder(int capacity) {
impl = new RegularSetBuilderImpl<E>(capacity);
}
Builder(@SuppressWarnings("unused") boolean subclass) {
this.impl = null; // unused
}
@VisibleForTesting
void forceJdk() {
this.impl = new JdkBackedSetBuilderImpl<E>(impl);
}
final void copyIfNecessary() {
if (forceCopy) {
copy();
forceCopy = false;
}
}
void copy() {
impl = impl.copy();
}
@Override
@CanIgnoreReturnValue
public Builder<E> add(E element) {
checkNotNull(element);
copyIfNecessary();
impl = impl.add(element);
return this;
}
@Override
@CanIgnoreReturnValue
public Builder<E> add(E... elements) {
super.add(elements);
return this;
}
@Override
/**
* Adds each element of {@code elements} to the {@code ImmutableSet}, ignoring duplicate
* elements (only the first duplicate element is added).
*
* @param elements the elements to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a null element
*/
@CanIgnoreReturnValue
public Builder<E> addAll(Iterable<? extends E> elements) {
super.addAll(elements);
return this;
}
@Override
@CanIgnoreReturnValue
public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
Builder<E> combine(Builder<E> other) {
copyIfNecessary();
this.impl = this.impl.combine(other.impl);
return this;
}
@Override
public ImmutableSet<E> build() {
forceCopy = true;
impl = impl.review();
return impl.build();
}
}
/** Swappable internal implementation of an ImmutableSet.Builder. */
private abstract static class SetBuilderImpl<E> {
E[] dedupedElements;
int distinct;
@SuppressWarnings("unchecked")
SetBuilderImpl(int expectedCapacity) {
this.dedupedElements = (E[]) new Object[expectedCapacity];
this.distinct = 0;
}
/** Initializes this SetBuilderImpl with a copy of the deduped elements array from toCopy. */
SetBuilderImpl(SetBuilderImpl<E> toCopy) {
this.dedupedElements = Arrays.copyOf(toCopy.dedupedElements, toCopy.dedupedElements.length);
this.distinct = toCopy.distinct;
}
/**
* Resizes internal data structures if necessary to store the specified number of distinct
* elements.
*/
private void ensureCapacity(int minCapacity) {
if (minCapacity > dedupedElements.length) {
int newCapacity =
ImmutableCollection.Builder.expandedCapacity(dedupedElements.length, minCapacity);
dedupedElements = Arrays.copyOf(dedupedElements, newCapacity);
}
}
/** Adds e to the insertion-order array of deduplicated elements. Calls ensureCapacity. */
final void addDedupedElement(E e) {
ensureCapacity(distinct + 1);
dedupedElements[distinct++] = e;
}
/**
* Adds e to this SetBuilderImpl, returning the updated result. Only use the returned
* SetBuilderImpl, since we may switch implementations if e.g. hash flooding is detected.
*/
abstract SetBuilderImpl<E> add(E e);
/** Adds all the elements from the specified SetBuilderImpl to this SetBuilderImpl. */
final SetBuilderImpl<E> combine(SetBuilderImpl<E> other) {
SetBuilderImpl<E> result = this;
for (int i = 0; i < other.distinct; i++) {
result = result.add(other.dedupedElements[i]);
}
return result;
}
/**
* Creates a new copy of this SetBuilderImpl. Modifications to that SetBuilderImpl will not
* affect this SetBuilderImpl or sets constructed from this SetBuilderImpl via build().
*/
abstract SetBuilderImpl<E> copy();
/**
* Call this before build(). Does a final check on the internal data structures, e.g. shrinking
* unnecessarily large structures or detecting previously unnoticed hash flooding.
*/
SetBuilderImpl<E> review() {
return this;
}
abstract ImmutableSet<E> build();
}
// We use power-of-2 tables, and this is the highest int that's a power of 2
static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO;
// Represents how tightly we can pack things, as a maximum.
private static final double DESIRED_LOAD_FACTOR = 0.7;
// If the set has this many elements, it will "max out" the table size
private static final int CUTOFF = (int) (MAX_TABLE_SIZE * DESIRED_LOAD_FACTOR);
/**
* Returns an array size suitable for the backing array of a hash table that uses open addressing
* with linear probing in its implementation. The returned size is the smallest power of two that
* can hold setSize elements with the desired load factor. Always returns at least setSize + 2.
*/
@VisibleForTesting
static int chooseTableSize(int setSize) {
setSize = Math.max(setSize, 2);
// Correct the size for open addressing to match desired load factor.
if (setSize < CUTOFF) {
// Round up to the next highest power of 2.
int tableSize = Integer.highestOneBit(setSize - 1) << 1;
while (tableSize * DESIRED_LOAD_FACTOR < setSize) {
tableSize <<= 1;
}
return tableSize;
}
// The table can't be completely full or we'll get infinite reprobes
checkArgument(setSize < MAX_TABLE_SIZE, "collection too large");
return MAX_TABLE_SIZE;
}
/**
* We attempt to detect deliberate hash flooding attempts, and if one is detected, fall back to a
* wrapper around j.u.HashSet, which has built in flooding protection. HASH_FLOODING_FPP is the
* maximum allowed probability of falsely detecting a hash flooding attack if the input is
* randomly generated.
*
* <p>MAX_RUN_MULTIPLIER was determined experimentally to match this FPP.
*/
static final double HASH_FLOODING_FPP = 0.001;
// NB: yes, this is surprisingly high, but that's what the experiments said was necessary
// The higher it is, the worse constant factors we are willing to accept.
static final int MAX_RUN_MULTIPLIER = 13;
/**
* Checks the whole hash table for poor hash distribution. Takes O(n) in the worst case, O(n / log
* n) on average.
*
* <p>The online hash flooding detecting in RegularSetBuilderImpl.add can detect e.g. many exactly
* matching hash codes, which would cause construction to take O(n^2), but can't detect e.g. hash
* codes adversarially designed to go into ascending table locations, which keeps construction
* O(n) (as desired) but then can have O(n) queries later.
*
* <p>If this returns false, then no query can take more than O(log n).
*
* <p>Note that for a RegularImmutableSet with elements with truly random hash codes, contains
* operations take expected O(1) time but with high probability take O(log n) for at least some
* element. (https://en.wikipedia.org/wiki/Linear_probing#Analysis)
*
* <p>This method may return {@code true} up to {@link #HASH_FLOODING_FPP} of the time even on
* truly random input.
*
* <p>If this method returns false, there are definitely no runs of length at least {@code
* maxRunBeforeFallback(hashTable.length)} nonnull elements. If there are no runs of length at
* least {@code maxRunBeforeFallback(hashTable.length) / 2} nonnull elements, this method
* definitely returns false. In between those constraints, the result of this method is undefined,
* subject to the above {@link #HASH_FLOODING_FPP} constraint.
*/
static boolean hashFloodingDetected(Object[] hashTable) {
int maxRunBeforeFallback = maxRunBeforeFallback(hashTable.length);
// Test for a run wrapping around the end of the table of length at least maxRunBeforeFallback.
int endOfStartRun;
for (endOfStartRun = 0; endOfStartRun < hashTable.length; ) {
if (hashTable[endOfStartRun] == null) {
break;
}
endOfStartRun++;
if (endOfStartRun > maxRunBeforeFallback) {
return true;
}
}
int startOfEndRun;
for (startOfEndRun = hashTable.length - 1; startOfEndRun > endOfStartRun; startOfEndRun--) {
if (hashTable[startOfEndRun] == null) {
break;
}
if (endOfStartRun + (hashTable.length - 1 - startOfEndRun) > maxRunBeforeFallback) {
return true;
}
}
// Now, break the remainder of the table into blocks of maxRunBeforeFallback/2 elements and
// check that each has at least one null.
int testBlockSize = maxRunBeforeFallback / 2;
blockLoop:
for (int i = endOfStartRun + 1; i + testBlockSize <= startOfEndRun; i += testBlockSize) {
for (int j = 0; j < testBlockSize; j++) {
if (hashTable[i + j] == null) {
continue blockLoop;
}
}
return true;
}
return false;
}
/**
* If more than this many consecutive positions are filled in a table of the specified size,
* report probable hash flooding. ({@link #hashFloodingDetected} may also report hash flooding if
* fewer consecutive positions are filled; see that method for details.)
*/
private static int maxRunBeforeFallback(int tableSize) {
return MAX_RUN_MULTIPLIER * IntMath.log2(tableSize, RoundingMode.UNNECESSARY);
}
/**
* Default implementation of the guts of ImmutableSet.Builder, creating an open-addressed hash
* table and deduplicating elements as they come, so it only allocates O(max(distinct,
* expectedCapacity)) rather than O(calls to add).
*
* <p>This implementation attempts to detect hash flooding, and if it's identified, falls back to
* JdkBackedSetBuilderImpl.
*/
private static final class RegularSetBuilderImpl<E> extends SetBuilderImpl<E> {
private Object[] hashTable;
private int maxRunBeforeFallback;
private int expandTableThreshold;
private int hashCode;
RegularSetBuilderImpl(int expectedCapacity) {
super(expectedCapacity);
int tableSize = chooseTableSize(expectedCapacity);
this.hashTable = new Object[tableSize];
this.maxRunBeforeFallback = maxRunBeforeFallback(tableSize);
this.expandTableThreshold = (int) (DESIRED_LOAD_FACTOR * tableSize);
}
RegularSetBuilderImpl(RegularSetBuilderImpl<E> toCopy) {
super(toCopy);
this.hashTable = Arrays.copyOf(toCopy.hashTable, toCopy.hashTable.length);
this.maxRunBeforeFallback = toCopy.maxRunBeforeFallback;
this.expandTableThreshold = toCopy.expandTableThreshold;
this.hashCode = toCopy.hashCode;
}
void ensureTableCapacity(int minCapacity) {
if (minCapacity > expandTableThreshold && hashTable.length < MAX_TABLE_SIZE) {
int newTableSize = hashTable.length * 2;
hashTable = rebuildHashTable(newTableSize, dedupedElements, distinct);
maxRunBeforeFallback = maxRunBeforeFallback(newTableSize);
expandTableThreshold = (int) (DESIRED_LOAD_FACTOR * newTableSize);
}
}
@Override
SetBuilderImpl<E> add(E e) {
checkNotNull(e);
int eHash = e.hashCode();
int i0 = Hashing.smear(eHash);
int mask = hashTable.length - 1;
for (int i = i0; i - i0 < maxRunBeforeFallback; i++) {
int index = i & mask;
Object tableEntry = hashTable[index];
if (tableEntry == null) {
addDedupedElement(e);
hashTable[index] = e;
hashCode += eHash;
ensureTableCapacity(distinct); // rebuilds table if necessary
return this;
} else if (tableEntry.equals(e)) { // not a new element, ignore
return this;
}
}
// we fell out of the loop due to a long run; fall back to JDK impl
return new JdkBackedSetBuilderImpl<E>(this).add(e);
}
@Override
SetBuilderImpl<E> copy() {
return new RegularSetBuilderImpl<E>(this);
}
@Override
SetBuilderImpl<E> review() {
int targetTableSize = chooseTableSize(distinct);
if (targetTableSize * 2 < hashTable.length) {
hashTable = rebuildHashTable(targetTableSize, dedupedElements, distinct);
}
return hashFloodingDetected(hashTable) ? new JdkBackedSetBuilderImpl<E>(this) : this;
}
@Override
ImmutableSet<E> build() {
switch (distinct) {
case 0:
return of();
case 1:
return of(dedupedElements[0]);
default:
Object[] elements =
(distinct == dedupedElements.length)
? dedupedElements
: Arrays.copyOf(dedupedElements, distinct);
return new RegularImmutableSet<E>(elements, hashCode, hashTable, hashTable.length - 1);
}
}
}
/**
* SetBuilderImpl version that uses a JDK HashSet, which has built in hash flooding protection.
*/
private static final class JdkBackedSetBuilderImpl<E> extends SetBuilderImpl<E> {
private final Set<Object> delegate;
JdkBackedSetBuilderImpl(SetBuilderImpl<E> toCopy) {
super(toCopy); // initializes dedupedElements and distinct
delegate = Sets.newHashSetWithExpectedSize(distinct);
for (int i = 0; i < distinct; i++) {
delegate.add(dedupedElements[i]);
}
}
@Override
SetBuilderImpl<E> add(E e) {
checkNotNull(e);
if (delegate.add(e)) {
addDedupedElement(e);
}
return this;
}
@Override
SetBuilderImpl<E> copy() {
return new JdkBackedSetBuilderImpl<>(this);
}
@Override
ImmutableSet<E> build() {
switch (distinct) {
case 0:
return of();
case 1:
return of(dedupedElements[0]);
default:
return null;
// return new JdkBackedImmutableSet<E>(
// delegate, ImmutableList.asImmutableList(dedupedElements, distinct));
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More