529 changes: 254 additions & 275 deletions build.xml

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions doap_POI.rdf
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@
<programming-language>Java</programming-language>
<category rdf:resource="https://projects.apache.org/category/content" />
<category rdf:resource="https://projects.apache.org/category/library" />
<release>
<Version>
<name>Apache POI 4.0.1</name>
<created>2018-12-03</created>
<revision>4.0.1</revision>
</Version>
</release>
<release>
<Version>
<name>Apache POI 4.0.0</name>
Expand Down
25 changes: 19 additions & 6 deletions file-leak-detector.exclude
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,28 @@ org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter.getDocument

# JVM
sun.security.jca.ProviderConfig.doLoadProvider
javax.xml.parsers.FactoryFinder.findJarServiceProvider
com.sun.org.apache.xerces.internal.utils.SecuritySupport.getResourceBundle
java.util.ResourceBundle.getBundle

# Codepage support loads classes
java.nio.charset.Charset.lookupViaProviders

# Ant
org.apache.tools.ant.Main.getAntVersion
javax.xml.parsers.FactoryFinder.findJarServiceProvider
org.apache.tools.ant.taskdefs.Antlib.createAntlib

# XML Parser
com.sun.org.apache.xerces.internal.utils.SecuritySupport.getResourceBundle
com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory.loadPropertiesFile
com.sun.xml.internal.bind.v2.runtime.property.ArrayElementNodeProperty.<init>
com.sun.xml.internal.bind.v2.runtime.property.AttributeProperty.<init>
com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.<init>
javax.xml.parsers.FactoryFinder.findJarServiceProvider
javax.xml.stream.FactoryFinder.findJarServiceProvider

# XMLBeans
org.apache.xmlbeans.impl.regex.RegexParser.setLocale
org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl$XsbReader.getLoaderStream
com.sun.xml.internal.bind.v2.runtime.property.ArrayElementNodeProperty.<init>
com.sun.xml.internal.bind.v2.runtime.property.AttributeProperty.<init>
com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.<init>
com.sun.xml.bind.v2.runtime.reflect.opt.AccessorInjector.tailor

# JCA
sun.security.jca.ProviderConfig.getProvider
Expand All @@ -38,6 +38,18 @@ javax.crypto.Cipher.getMaxAllowedKeyLength
# IntelliJ
com.intellij.junit4.JUnit4TestRunnerUtil.<clinit>

# OpenJPA/Derby (regression testing)
org.apache.derby.impl.services.stream.SingleStream.PBmakeFileHPW
org.apache.derby.impl.io.DirFile.getExclusiveFileLock
org.apache.derby.impl.store.raw.data.RAFContainer.run
org.apache.derby.impl.store.raw.log.LogToFile.run
org.apache.derby.client.net.OpenSocketAction.run
org.apache.openjpa.enhance.InstrumentationFactory.loadVMClass
org.apache.openjpa.enhance.PCEnhancer.<init>
org.apache.openjpa.lib.util.J2DoPrivHelper$7.run
serp.bytecode.BCClass.read
serp.util.Strings.toClass

# Java
sun.util.resources.LocaleData.getBundle
sun.util.LocaleServiceProviderPool.<init>
Expand All @@ -53,3 +65,4 @@ java.util.logging.Logger.findSystemResourceBundle
java.text.BreakIterator.getBundle
sun.java2d.SunGraphicsEnvironment.<init>
org.kohsuke.file_leak_detector.AgentMain.runHttpServer
org.apache.log4j.FileAppender.setFile
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
159 changes: 93 additions & 66 deletions jenkins/create_jobs.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -25,54 +25,25 @@ def poijobs = [
// the JDK is missing on some slaves so builds are unstable
skipcigame: true
],
[ name: 'POI-DSL-1.10', jdk: '1.10', trigger: triggerSundays,
properties: ['-Djava9addmods=--add-modules=java.xml.bind',
'-Djavadoc9addmods=--add-modules=java.xml.bind',
'-Djava9addmodsvalue=-Dsun.reflect.debugModuleAccessChecks=true',
'-Djava9addopens1=--add-opens=java.xml/com.sun.org.apache.xerces.internal.util=ALL-UNNAMED',
'-Djava9addopens2=--add-opens=java.base/java.io=ALL-UNNAMED',
'-Djava9addopens3=--add-opens=java.base/java.nio=ALL-UNNAMED',
'-Djava9addopens4=--add-opens=java.base/java.lang=ALL-UNNAMED',
'-Djava9addopens5=--add-opens=java.base/jdk.internal.ref=ALL-UNNAMED',
'-Djava9addopens6=--add-opens=java.base/java.lang=java.xml.bind',
'-Djava.locale.providers=JRE,CLDR'],
skipcigame: true
[ name: 'POI-DSL-1.10', jdk: '1.10', trigger: triggerSundays, skipcigame: true
],
[ name: 'POI-DSL-1.11', jdk: '1.11', trigger: triggerSundays,
[ name: 'POI-DSL-1.11', jdk: '1.11', trigger: triggerSundays, skipcigame: true,
// Nodes beam* do not yet have JDK 11 installed
slaveAdd: '&&!beam1&&!beam2&&!beam3&&!beam4&&!beam6&&!beam7&&!beam8&&!beam9&&!beam10&&!beam11&&!beam12&&!beam13&&!beam14&&!beam15&&!beam16',
properties: ['-Djava9addmods=-Dthis.is.a.dummy=true',
'-Djavadoc9addmods=-Dthis.is.a.dummy=true',
'-Djava9addmodsvalue=-Dsun.reflect.debugModuleAccessChecks=true',
'-Djava9addopens1=--add-opens=java.xml/com.sun.org.apache.xerces.internal.util=ALL-UNNAMED',
'-Djava9addopens2=--add-opens=java.base/java.io=ALL-UNNAMED',
'-Djava9addopens3=--add-opens=java.base/java.nio=ALL-UNNAMED',
'-Djava9addopens4=--add-opens=java.base/java.lang=ALL-UNNAMED',
'-Djava9addopens5=--add-opens=java.base/jdk.internal.ref=ALL-UNNAMED',
'-Djava9addopens6=-Dthis.is.a.dummy=true',
'-Djava.locale.providers=JRE,CLDR'],
skipcigame: true
slaveAdd: '&&!beam1&&!beam2&&!beam3&&!beam4&&!beam6&&!beam7&&!beam8&&!beam9&&!beam10&&!beam11&&!beam12&&!beam13&&!beam14&&!beam15&&!beam16'
],
[ name: 'POI-DSL-1.12', jdk: '1.12', trigger: '''
# do not run this via a schedule for now
''',
[ name: 'POI-DSL-1.12', jdk: '1.12', trigger: triggerSundays, skipcigame: true,
// Nodes beam* do not yet have JDK 12 installed
// H43 has outdated JDK12 installed
slaveAdd: '&&!beam1&&!beam2&&!beam3&&!beam4&&!beam6&&!beam7&&!beam8&&!beam9&&!beam10&&!beam11&&!beam12&&!beam13&&!beam14&&!beam15&&!beam16&&!H43'
],
[ name: 'POI-DSL-1.13', jdk: '1.13', trigger: triggerSundays, skipcigame: true,
// Nodes beam* do not yet have JDK 13 installed
slaveAdd: '&&!beam1&&!beam2&&!beam3&&!beam4&&!beam6&&!beam7&&!beam8&&!beam9&&!beam10&&!beam11&&!beam12&&!beam13&&!beam14&&!beam15&&!beam16',
properties: ['-Djava9addmods=-Dthis.is.a.dummy=true',
'-Djavadoc9addmods=-Dthis.is.a.dummy=true',
'-Djava9addmodsvalue=-Dsun.reflect.debugModuleAccessChecks=true',
'-Djava9addopens1=--add-opens=java.xml/com.sun.org.apache.xerces.internal.util=ALL-UNNAMED',
'-Djava9addopens2=--add-opens=java.base/java.io=ALL-UNNAMED',
'-Djava9addopens3=--add-opens=java.base/java.nio=ALL-UNNAMED',
'-Djava9addopens4=--add-opens=java.base/java.lang=ALL-UNNAMED',
'-Djava9addopens5=--add-opens=java.base/jdk.internal.ref=ALL-UNNAMED',
'-Djava9addopens6=-Dthis.is.a.dummy=true',
'-Djava.locale.providers=JRE,CLDR'],
skipcigame: true
properties: [// JaCoCo currently fails with "java.lang.NoSuchFieldException: $jacocoAccess",
// need to review/check with newer JDK 13 builds or when at least JaCoCo 0.8.3
'-Dcoverage.enabled=false']
],
[ name: 'POI-DSL-IBM-JDK', jdk: 'IBMJDK', trigger: triggerSundays,
// some OOXML tests fail with strange XML parsing errors and missing JCE unlimited strength requirements
disabled: true, skipcigame: true
[ name: 'POI-DSL-IBM-JDK', jdk: 'IBMJDK', trigger: triggerSundays, skipcigame: true
],
[ name: 'POI-DSL-old-Xerces', trigger: triggerSundays,
shell: "test -f ${xercesLib} || wget -O ${xercesLib} ${xercesUrl}\n",
Expand All @@ -83,8 +54,7 @@ def poijobs = [
],
[ name: 'POI-DSL-regenerate-javadoc', trigger: triggerSundays, javadoc: true
],
// disabled for 4.0.0 because we break compatibility on-purpose in a few places, e.g. for Java 9 compatibility
[ name: 'POI-DSL-API-Check', trigger: '@daily', apicheck: true, disabled: true
[ name: 'POI-DSL-API-Check', trigger: '@daily', apicheck: true
],
[ name: 'POI-DSL-Gradle', trigger: triggerSundays, email: 'centic@apache.org', gradle: true,
// Gradle will not run any tests if the code is up-to-date, therefore manually mark the files as updated
Expand All @@ -99,10 +69,25 @@ def poijobs = [
],
[ name: 'POI-DSL-Windows-1.8', trigger: 'H */12 * * *', windows: true, slaves: 'Windows'
],
[ name: 'POI-DSL-Windows-1.12', jdk: '1.12', trigger: triggerSundays, windows: true, slaves: 'Windows', skipcigame: true
],
[ name: 'POI-DSL-Github-PullRequests', trigger: '', githubpr: true, skipcigame: true,
// ensure the file which is needed from the separate documentation module does exist
// as we are checking out from git, we do not have the reference checked out here
addShell: 'mkdir src/documentation\ntouch src/documentation/RELEASE-NOTES.txt'
],
]

def xmlbeansjobs = [
[ name: 'POI-XMLBeans-DSL-1.6', jdk: '1.6', trigger: 'H */12 * * *', skipcigame: true
[ name: 'POI-XMLBeans-DSL-1.6', jdk: '1.6', trigger: 'H */12 * * *', skipcigame: true,
],
[ name: 'POI-XMLBeans-DSL-1.8', jdk: '1.8', trigger: triggerSundays, skipcigame: true,
],
[ name: 'POI-XMLBeans-DSL-1.11', jdk: '1.11', trigger: triggerSundays, skipcigame: true,
disabled: true // XMLBeans does not yet compile with Java 11
],
[ name: 'POI-XMLBeans-DSL-1.12', jdk: '1.12', trigger: triggerSundays, skipcigame: true,
disabled: true // XMLBeans does not yet compile with Java 11
]
]

Expand All @@ -123,6 +108,7 @@ def jdkMapping = [
'1.10': 'JDK 10 (latest)',
'1.11': 'JDK 11 (latest)',
'1.12': 'JDK 12 (latest)',
'1.13': 'JDK 13 (latest)',
'OpenJDK': 'OpenJDK 8 (on Ubuntu only) ', // blank is required here until the name in the Jenkins instance is fixed!
'IBMJDK': 'IBM 1.8 64-bit (on Ubuntu only)',
]
Expand Down Expand Up @@ -185,6 +171,12 @@ echo which javac
which javac
javac -version
echo Ant-Home: $ANT_HOME
ls -al $ANT_HOME
echo which ant
which ant
ant -version
echo '<project default="test"><target name="test"><echo>Java ${ant.java.version}/${java.version}</echo><exec executable="javac"><arg value="-version"/></exec></target></project>' > build.javacheck.xml
ant -f build.javacheck.xml -v
Expand Down Expand Up @@ -252,15 +244,49 @@ poijobs.each { poijob ->
}
jdk(jdkMapping.get(jdkKey))
scm {
svn(svnBase) { svnNode ->
svnNode / browser(class: 'hudson.scm.browsers.ViewSVN') /
url << 'http://svn.apache.org/viewcvs.cgi/?root=Apache-SVN'
if (poijob.githubpr) {
git {
remote {
github('apache/poi')
refspec('+refs/pull/*:refs/remotes/origin/pr/*')
}
branch('${sha1}')
}
} else {
svn(svnBase) { svnNode ->
svnNode / browser(class: 'hudson.scm.browsers.ViewSVN') /
url << 'http://svn.apache.org/viewcvs.cgi/?root=Apache-SVN'
}
}
}
checkoutRetryCount(3)

triggers {
scm(trigger)
if (poijob.githubpr) {
throttleConcurrentBuilds {
maxPerNode(1)
maxTotal(1)
}
parameters {
/* plugin not available:
gitParam('sha1') {
description('Pull request')
type('BRANCH')
}*/
stringParam('sha1', 'origin/pr/9/head', 'Provide a branch-spec, e.g. origin/pr/9/head')
}
triggers {
githubPullRequest {
admins(['centic9', 'poi-benchmark', 'tballison', 'gagravarr', 'onealj', 'pjfanning', 'Alain-Bearez'])
userWhitelist(['centic9', 'poi-benchmark', 'tballison', 'gagravarr', 'onealj', 'pjfanning', 'Alain-Bearez'])
orgWhitelist(['apache'])
cron('H/5 * * * *')
triggerPhrase('OK to test')
}
}
} else {
triggers {
scm(trigger)
}
}

def shellcmds = (poijob.windows ? shellCmdsWin : shellCmdsUnix).replace('POIJOBSHELL', poijob.shell ?: '')
Expand Down Expand Up @@ -461,7 +487,10 @@ xmlbeansjobs.each { xjob ->
// when using JDK 9/10 for running Ant, we need to provide more modules for the forbidden-api-checks task
// on JDK 11 and newer there is no such module any more, so do not add it here
env('ANT_OPTS', '--add-modules=java.xml.bind --add-opens=java.xml/com.sun.org.apache.xerces.internal.util=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED')
} else if (jdkKey == '1.11' || jdkKey == '1.12' || jdkKey == '1.13') {
env('ANT_OPTS', '--add-opens=java.xml/com.sun.org.apache.xerces.internal.util=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED')
}
// will be needed for forbidden-apis-check: env('ANT_HOME', xjob.windows ? 'f:\\jenkins\\tools\\ant\\latest' : '/usr/share/ant')
env('FORREST_HOME', xjob.windows ? 'f:\\jenkins\\tools\\forrest\\latest' : '/home/jenkins/tools/forrest/latest')
}
wrappers {
Expand Down Expand Up @@ -497,21 +526,21 @@ xmlbeansjobs.each { xjob ->
antInstallation(antRT)
}
ant {
targets(['checkintest'])
antInstallation(antRT)
}
ant {
targets(['dist'])
targets(['jenkins'])
antInstallation(antRT)
}
}
publishers {
archiveArtifacts('build/private/**')
//archiveJunit('build/test/reports/*.xml') {
// testDataPublishers {
// publishTestStabilityData()
// }
//}
archiveArtifacts('build/**')

warnings(['Java Compiler (javac)', 'JavaDoc Tool'], null) {
resolveRelativePaths()
}
archiveJunit('build/test-results/TEST-*.xml') {
testDataPublishers {
publishTestStabilityData()
}
}

if (!xjob.skipcigame) {
configure { project ->
Expand Down Expand Up @@ -551,14 +580,12 @@ Unfortunately we often see builds break because of changes/new machines...''')
'IBM 1.8 64-bit (on Ubuntu only)',

'JDK 10 (latest)',
'JDK 10 b46 (Windows Only)',
'OpenJDK 10.0.2 (on Ubuntu only)',

'JDK 11 (latest)',
'JDK 11 b23 (early access build) (Windows Only)',

'JDK 12 (latest)',
'OpenJDK 12 b18 (early access build)'

'JDK 13 (latest)'
)
elasticAxis {
name('Nodes')
Expand Down Expand Up @@ -597,7 +624,7 @@ where javac.exe
echo .
javac -version
echo .
echo ^<?xml version=^"1.0^"?^>^<project name=^"POI Build^" default=^"test^"^>^<target name=^"test^"^>^<echo^>Using Ant: ${ant.version} from ${ant.home}^</echo^>^</target^>^</project^> > build.xml
echo ^<?xml version=^"1.0^"?^>^<project name=^"POI Build^" default=^"test^"^>^<target name=^"test^"^>^<echo^>Using Ant: ${ant.version} from ${ant.home}, ant detected Java ${ant.java.version} (may be different than actual Java sometimes...), using Java: ${java.version}/${java.runtime.version}/${java.vm.version}/${java.vm.name} from ${java.vm.vendor} on ${os.name}: ${os.version}^</echo^>^</target^>^</project^> > build.xml
''')
}
ant {
Expand Down
2 changes: 1 addition & 1 deletion legal/NOTICE
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Apache POI
Copyright 2003-2018 The Apache Software Foundation
Copyright 2003-2019 The Apache Software Foundation

This product includes software developed at
The Apache Software Foundation (https://www.apache.org/).
Expand Down
10 changes: 9 additions & 1 deletion maven/poi-ooxml-schemas.pom
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@
<url>http://poi.apache.org/</url>
<description>Apache POI - Java API To Access Microsoft Format Files</description>

<repositories>
<repository>
<id>apache-releases-repo</id>
<name>apache releases repo</name>
<url>https://repository.apache.org/content/repositories/releases</url>
</repository>
</repositories>

<mailingLists>
<mailingList>
<name>POI Users List</name>
Expand Down Expand Up @@ -62,7 +70,7 @@
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>3.0.2</version>
<version>3.1.0</version>
</dependency>
</dependencies>
</project>
2 changes: 1 addition & 1 deletion maven/poi-ooxml.pom
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
<dependency>
<groupId>com.github.virtuald</groupId>
<artifactId>curvesapi</artifactId>
<version>1.05</version>
<version>1.06</version>
</dependency>
</dependencies>
</project>
4 changes: 2 additions & 2 deletions maven/poi.pom
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,12 @@
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
<version>1.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.2</version>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
Expand Down
2 changes: 1 addition & 1 deletion sonar/examples/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.apache.poi</groupId>
<artifactId>poi-parent</artifactId>
<version>4.0.2-SNAPSHOT</version>
<version>4.1.1-SNAPSHOT</version>
</parent>
<artifactId>poi-examples</artifactId>
<packaging>jar</packaging>
Expand Down
2 changes: 1 addition & 1 deletion sonar/excelant/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.apache.poi</groupId>
<artifactId>poi-parent</artifactId>
<version>4.0.2-SNAPSHOT</version>
<version>4.1.1-SNAPSHOT</version>
</parent>
<artifactId>poi-excelant</artifactId>
<packaging>jar</packaging>
Expand Down
6 changes: 3 additions & 3 deletions sonar/main/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.apache.poi</groupId>
<artifactId>poi-parent</artifactId>
<version>4.0.2-SNAPSHOT</version>
<version>4.1.1-SNAPSHOT</version>
</parent>
<artifactId>poi-main</artifactId>
<packaging>jar</packaging>
Expand Down Expand Up @@ -113,7 +113,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.2</version>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
Expand All @@ -123,7 +123,7 @@
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
<version>1.12</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
Expand Down
2 changes: 1 addition & 1 deletion sonar/ooxml-schema-encryption/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.apache.poi</groupId>
<artifactId>poi-parent</artifactId>
<version>4.0.2-SNAPSHOT</version>
<version>4.1.1-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>poi-ooxml-schema-encryption</artifactId>
Expand Down
2 changes: 1 addition & 1 deletion sonar/ooxml-schema-security/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.apache.poi</groupId>
<artifactId>poi-parent</artifactId>
<version>4.0.2-SNAPSHOT</version>
<version>4.1.1-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>poi-ooxml-schema-security</artifactId>
Expand Down
2 changes: 1 addition & 1 deletion sonar/ooxml-schema/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.apache.poi</groupId>
<artifactId>poi-parent</artifactId>
<version>4.0.2-SNAPSHOT</version>
<version>4.1.1-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>poi-ooxml-schema</artifactId>
Expand Down
17 changes: 12 additions & 5 deletions sonar/ooxml/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.apache.poi</groupId>
<artifactId>poi-parent</artifactId>
<version>4.0.2-SNAPSHOT</version>
<version>4.1.1-SNAPSHOT</version>
</parent>
<artifactId>poi-ooxml</artifactId>
<packaging>jar</packaging>
Expand Down Expand Up @@ -137,17 +137,17 @@
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.60</version>
<version>1.61</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.60</version>
<version>1.61</version>
</dependency>
<dependency>
<groupId>org.apache.santuario</groupId>
<artifactId>xmlsec</artifactId>
<version>2.1.0</version>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
Expand All @@ -157,7 +157,7 @@
<dependency>
<groupId>com.github.virtuald</groupId>
<artifactId>curvesapi</artifactId>
<version>1.05</version>
<version>1.06</version>
</dependency>

<dependency>
Expand Down Expand Up @@ -185,5 +185,12 @@
<version>1.19</version>
<scope>test</scope>
</dependency>

<dependency>
<!-- don't add it to the distribution -->
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-all</artifactId>
<version>1.11</version>
</dependency>
</dependencies>
</project>
23 changes: 11 additions & 12 deletions sonar/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<groupId>org.apache.poi</groupId>
<artifactId>poi-parent</artifactId>
<packaging>pom</packaging>
<version>4.0.2-SNAPSHOT</version>
<version>4.1.1-SNAPSHOT</version>
<name>Apache POI - the Java API for Microsoft Documents</name>
<description>Maven build of Apache POI for Sonar checks</description>
<url>http://poi.apache.org/</url>
Expand Down Expand Up @@ -72,7 +72,7 @@
<sonar.scm.disabled>true</sonar.scm.disabled>

<!-- define some of the third-party or plugin-versions globally to use the same in all modules -->
<xmlbeans.version>3.0.2</xmlbeans.version>
<xmlbeans.version>3.1.0</xmlbeans.version>
<junit.version>4.12</junit.version>
<xmlunit.version>2.5.1</xmlunit.version>
<mockito.version>2.13.0</mockito.version>
Expand Down Expand Up @@ -268,9 +268,7 @@
</goals>
<configuration>
<target>
<property name="xmlbean.sources.dir"
location="${basedir}/target/generated-sources/xmlbeans"/>

<!-- the space between "public static" is on purpose to prevent double execution -->
<property name="loaderMethod"><![CDATA[
private static java.lang.ref.SoftReference<org.apache.xmlbeans.SchemaTypeLoader> typeLoader;
Expand All @@ -283,25 +281,26 @@
return stl;
}
public static \2 newInstance\(\) \{]]></property>
public static \2 newInstance\(\) \{]]></property>

<fileset id="xsrc" dir="${basedir}/target/generated-sources/xmlbeans" includes="**/*.java" excludes="**/impl/**"/>

<replaceregexp byline="true"
match="(\s*)public static ([^ ]+) newInstance\(\) \{"
replace="${loaderMethod}">
<fileset dir="${xmlbean.sources.dir}" includes="**/*.java"
excludes="**/impl/**"/>
<fileset refid="xsrc"/>
</replaceregexp>

<replace dir="${xmlbean.sources.dir}" includes="**/*.java"
excludes="**/impl/**">
<replace>
<fileset refid="xsrc"/>
<replacetoken>org.apache.xmlbeans.XmlBeans.getContextTypeLoader
</replacetoken>
<replacevalue>getTypeLoader</replacevalue>
</replace>

<!-- remove deprecated warnings, as we prefer the array methods - see #56854 -->
<replace dir="${xmlbean.sources.dir}" includes="**/*.java"
excludes="**/impl/**">
<replace>
<fileset refid="xsrc"/>
<replacetoken><![CDATA[ * @deprecated
]]></replacetoken>
</replace>
Expand Down
2 changes: 1 addition & 1 deletion sonar/scratchpad/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.apache.poi</groupId>
<artifactId>poi-parent</artifactId>
<version>4.0.2-SNAPSHOT</version>
<version>4.1.1-SNAPSHOT</version>
</parent>
<artifactId>poi-scratchpad</artifactId>
<packaging>jar</packaging>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more
*/
public final class DataExtraction {

public static void main(String args[]) throws Exception {
public static void main(String[] args) throws Exception {

if (args.length == 0) {
usage();
Expand Down
71 changes: 4 additions & 67 deletions src/examples/src/org/apache/poi/hslf/examples/PPT2PNG.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,82 +26,19 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;

import javax.imageio.ImageIO;

import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.sl.draw.Drawable;
import org.apache.poi.xslf.util.PPTX2PNG;

/**
* Demonstrates how you can use HSLF to convert each slide into a PNG image
*/
public final class PPT2PNG {

public static void main(String args[]) throws IOException {

if (args.length == 0) {
usage();
return;
}

int slidenum = -1;
float scale = 1;
String file = null;

for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("-")) {
if ("-scale".equals(args[i])){
scale = Float.parseFloat(args[++i]);
} else if ("-slide".equals(args[i])) {
slidenum = Integer.parseInt(args[++i]);
}
} else {
file = args[i];
}
}
if(file == null){
usage();
return;
}

FileInputStream is = new FileInputStream(file);
HSLFSlideShow ppt = new HSLFSlideShow(is);
is.close();

Dimension pgsize = ppt.getPageSize();
int width = (int)(pgsize.width*scale);
int height = (int)(pgsize.height*scale);

for (HSLFSlide slide : ppt.getSlides()) {
if (slidenum != -1 && slidenum != slide.getSlideNumber()) {
continue;
}

String title = slide.getTitle();
System.out.println("Rendering slide "+slide.getSlideNumber() + (title == null ? "" : ": " + title));

BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);

graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, width, height));

graphics.scale((double)width/pgsize.width, (double)height/pgsize.height);

slide.draw(graphics);

String fname = file.replaceAll("\\.ppt", "-" + slide.getSlideNumber() + ".png");
FileOutputStream out = new FileOutputStream(fname);
ImageIO.write(img, "png", out);
out.close();
}

ppt.close();
}
public final class PPT2PNG extends PPTX2PNG {

private static void usage(){
System.out.println("Usage: PPT2PNG [-scale <scale> -slide <num>] ppt");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FormulaError;

public class CellTypes {
public static void main(String[] args) throws IOException {
Expand All @@ -35,7 +35,7 @@ public static void main(String[] args) throws IOException {
row.createCell(1).setCellValue(new Date());
row.createCell(2).setCellValue("a string");
row.createCell(3).setCellValue(true);
row.createCell(4).setCellType(CellType.ERROR);
row.createCell(4).setCellErrorValue(FormulaError.NUM);

// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;

/**
* Test if hyperlink formula, with url that got more than 127 characters, works
Expand All @@ -36,7 +35,6 @@ public static void main(String[] args) throws IOException {
HSSFRow row = sheet.createRow(0);

HSSFCell cell = row.createCell(0);
cell.setCellType(CellType.FORMULA);
cell.setCellFormula("HYPERLINK(\"http://127.0.0.1:8080/toto/truc/index.html?test=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"test\")");

try (FileOutputStream fileOut = new FileOutputStream("workbook.xls")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;

/**
* Demonstrates how to use newlines in cells.
Expand All @@ -46,7 +45,6 @@ public static void main( String[] args ) throws IOException {
HSSFRow r = s.createRow(2);
r.setHeight((short) 0x349);
HSSFCell c = r.createCell(2);
c.setCellType(CellType.STRING);
c.setCellValue("Use \n with word wrap on to create a new line");
c.setCellStyle(cs);
s.setColumnWidth(2, (int) ((50 * 8) / ((double) 1 / 20)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.CellType;

/**
* This example demonstrates opening a workbook, modifying it and writing
Expand All @@ -46,7 +45,6 @@ public static void main(String[] args) throws IOException {
HSSFCell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(CellType.STRING);
cell.setCellValue("a test");

// Write the output to a file
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ private static class Locator {

List<String> listOfDifferences = new ArrayList<>();

public static void main(String args[]) throws Exception {
public static void main(String[] args) throws Exception {
if (args.length != 2 || !(new File(args[0]).exists()) || !(new File(args[1]).exists())) {
System.err.println("java -cp <classpath> "+ExcelComparator.class.getCanonicalName()+" <workbook1.xls/x> <workbook2.xls/x");
System.exit(-1);
Expand Down Expand Up @@ -144,8 +144,8 @@ private void compareDataInAllSheets(Locator loc1, Locator loc2) {
}

private void compareDataInSheet(Locator loc1, Locator loc2) {
for (int j = 0; j < loc1.sheet.getPhysicalNumberOfRows(); j++) {
if (loc2.sheet.getPhysicalNumberOfRows() <= j) return;
for (int j = 0; j < loc1.sheet.getLastRowNum(); j++) {
if (loc2.sheet.getLastRowNum() <= j) return;

loc1.row = loc1.sheet.getRow(j);
loc2.row = loc2.sheet.getRow(j);
Expand All @@ -160,7 +160,7 @@ private void compareDataInSheet(Locator loc1, Locator loc2) {

private void compareDataInRow(Locator loc1, Locator loc2) {
for (int k = 0; k < loc1.row.getLastCellNum(); k++) {
if (loc2.row.getPhysicalNumberOfCells() <= k) return;
if (loc2.row.getLastCellNum() <= k) return;

loc1.cell = loc1.row.getCell(k);
loc2.cell = loc2.row.getCell(k);
Expand Down
145 changes: 145 additions & 0 deletions src/examples/src/org/apache/poi/xslf/usermodel/ChartFromScratch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.poi.xslf.usermodel;

import java.awt.geom.Rectangle2D;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xddf.usermodel.chart.AxisCrosses;
import org.apache.poi.xddf.usermodel.chart.AxisPosition;
import org.apache.poi.xddf.usermodel.chart.BarDirection;
import org.apache.poi.xddf.usermodel.chart.ChartTypes;
import org.apache.poi.xddf.usermodel.chart.LegendPosition;
import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData;
import org.apache.poi.xddf.usermodel.chart.XDDFChart;
import org.apache.poi.xddf.usermodel.chart.XDDFChartAxis;
import org.apache.poi.xddf.usermodel.chart.XDDFChartLegend;
import org.apache.poi.xddf.usermodel.chart.XDDFDataSource;
import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory;
import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource;
import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis;

/**
* Build a chart without reading template file
*/
public class ChartFromScratch {
private static void usage(){
System.out.println("Usage: BarChartExample <bar-chart-data.txt>");
System.out.println(" bar-chart-data.txt the model to set. First line is chart title, " +
"then go pairs {axis-label value}");
}

public static void main(String[] args) throws Exception {
if(args.length < 1) {
usage();
return;
}

try (BufferedReader modelReader = new BufferedReader(new FileReader(args[0]))) {

String chartTitle = modelReader.readLine(); // first line is chart title
String[] series = modelReader.readLine().split(",");

// Category Axis Data
List<String> listLanguages = new ArrayList<>(10);

// Values
List<Double> listCountries = new ArrayList<>(10);
List<Double> listSpeakers = new ArrayList<>(10);

// set model
String ln;
while((ln = modelReader.readLine()) != null) {
String[] vals = ln.split(",");
listCountries.add(Double.valueOf(vals[0]));
listSpeakers.add(Double.valueOf(vals[1]));
listLanguages.add(vals[2]);
}

String[] categories = listLanguages.toArray(new String[listLanguages.size()]);
Double[] values1 = listCountries.toArray(new Double[listCountries.size()]);
Double[] values2 = listSpeakers.toArray(new Double[listSpeakers.size()]);

try {

XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide slide = ppt.createSlide();
XSLFChart chart = ppt.createChart();
Rectangle2D rect2D = new java.awt.Rectangle(XDDFChart.DEFAULT_X, XDDFChart.DEFAULT_Y,
XDDFChart.DEFAULT_WIDTH, XDDFChart.DEFAULT_HEIGHT);
slide.addChart(chart, rect2D);
setBarData(chart, chartTitle, series, categories, values1, values2);
// save the result
try (OutputStream out = new FileOutputStream("bar-chart-demo-output.pptx")) {
ppt.write(out);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println("Done");
}

private static void setBarData(XSLFChart chart, String chartTitle, String[] series, String[] categories, Double[] values1, Double[] values2) {
// Use a category axis for the bottom axis.
XDDFChartAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setTitle(series[2]);
XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
leftAxis.setTitle(series[0]+","+series[1]);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

final int numOfPoints = categories.length;
final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 1, 1));
final String valuesDataRange2 = chart.formatRange(new CellRangeAddress(1, numOfPoints, 2, 2));
final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, 0);
final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(values1, valuesDataRange, 1);
values1[6] = 16.0; // if you ever want to change the underlying data
final XDDFNumericalDataSource<? extends Number> valuesData2 = XDDFDataSourcesFactory.fromArray(values2, valuesDataRange2, 2);


XDDFBarChartData bar = (XDDFBarChartData) chart.createData(ChartTypes.BAR, bottomAxis, leftAxis);
XDDFBarChartData.Series series1 = (XDDFBarChartData.Series) bar.addSeries(categoriesData, valuesData);
series1.setTitle(series[0], chart.setSheetTitle(series[0], 1));

XDDFBarChartData.Series series2 = (XDDFBarChartData.Series) bar.addSeries(categoriesData, valuesData2);
series2.setTitle(series[1], chart.setSheetTitle(series[1], 2));

bar.setVaryColors(true);
bar.setBarDirection(BarDirection.COL);
chart.plot(bar);

XDDFChartLegend legend = chart.getOrAddLegend();
legend.setPosition(LegendPosition.LEFT);
legend.setOverlay(false);

chart.setTitleText(chartTitle);
chart.setTitleOverlay(false);
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
*/
public final class DataExtraction {

public static void main(String args[]) throws IOException, OpenXML4JException {
public static void main(String[] args) throws IOException, OpenXML4JException {

PrintStream out = System.out;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
*/
public final class MergePresentations {

public static void main(String args[]) throws Exception {
public static void main(String[] args) throws Exception {
try (XMLSlideShow ppt = new XMLSlideShow()) {
for (String arg : args) {
try (FileInputStream is = new FileInputStream(arg);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public void processAllSheets(String filename) throws Exception {
InputSource sheetSource = new InputSource(sheet);
parser.parse(sheetSource);
}
System.out.println("");
System.out.println();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.poi.xwpf.usermodel.examples;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xddf.usermodel.chart.AxisCrosses;
import org.apache.poi.xddf.usermodel.chart.AxisPosition;
import org.apache.poi.xddf.usermodel.chart.BarDirection;
import org.apache.poi.xddf.usermodel.chart.ChartTypes;
import org.apache.poi.xddf.usermodel.chart.LegendPosition;
import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData;
import org.apache.poi.xddf.usermodel.chart.XDDFChart;
import org.apache.poi.xddf.usermodel.chart.XDDFChartAxis;
import org.apache.poi.xddf.usermodel.chart.XDDFChartLegend;
import org.apache.poi.xddf.usermodel.chart.XDDFDataSource;
import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory;
import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource;
import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

/**
* Build a chart without reading template file
*/
public class ChartFromScratch {
private static void usage(){
System.out.println("Usage: BarChartExample <bar-chart-data.txt>");
System.out.println(" bar-chart-data.txt the model to set. First line is chart title, " +
"then go pairs {axis-label value}");
}

public static void main(String[] args) throws Exception {
if(args.length < 1) {
usage();
return;
}

try (BufferedReader modelReader = new BufferedReader(new FileReader(args[0]))) {

String chartTitle = modelReader.readLine(); // first line is chart title
String[] series = modelReader.readLine().split(",");

// Category Axis Data
List<String> listLanguages = new ArrayList<>(10);

// Values
List<Double> listCountries = new ArrayList<>(10);
List<Double> listSpeakers = new ArrayList<>(10);

// set model
String ln;
while((ln = modelReader.readLine()) != null) {
String[] vals = ln.split(",");
listCountries.add(Double.valueOf(vals[0]));
listSpeakers.add(Double.valueOf(vals[1]));
listLanguages.add(vals[2]);
}

String[] categories = listLanguages.toArray(new String[listLanguages.size()]);
Double[] values1 = listCountries.toArray(new Double[listCountries.size()]);
Double[] values2 = listSpeakers.toArray(new Double[listSpeakers.size()]);

try (XWPFDocument doc = new XWPFDocument()) {
XWPFChart chart = doc.createChart(XDDFChart.DEFAULT_WIDTH, XDDFChart.DEFAULT_HEIGHT);
setBarData(chart, chartTitle, series, categories, values1, values2);
// save the result
try (OutputStream out = new FileOutputStream("bar-chart-demo-output.docx")) {
doc.write(out);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println("Done");
}

private static void setBarData(XWPFChart chart, String chartTitle, String[] series, String[] categories, Double[] values1, Double[] values2) {
// Use a category axis for the bottom axis.
XDDFChartAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setTitle(series[2]);
XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
leftAxis.setTitle(series[0]+","+series[1]);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

final int numOfPoints = categories.length;
final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 1, 1));
final String valuesDataRange2 = chart.formatRange(new CellRangeAddress(1, numOfPoints, 2, 2));
final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, 0);
final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(values1, valuesDataRange, 1);
values1[6] = 16.0; // if you ever want to change the underlying data
final XDDFNumericalDataSource<? extends Number> valuesData2 = XDDFDataSourcesFactory.fromArray(values2, valuesDataRange2, 2);


XDDFBarChartData bar = (XDDFBarChartData) chart.createData(ChartTypes.BAR, bottomAxis, leftAxis);
XDDFBarChartData.Series series1 = (XDDFBarChartData.Series) bar.addSeries(categoriesData, valuesData);
series1.setTitle(series[0], chart.setSheetTitle(series[0], 1));

XDDFBarChartData.Series series2 = (XDDFBarChartData.Series) bar.addSeries(categoriesData, valuesData2);
series2.setTitle(series[1], chart.setSheetTitle(series[1], 2));

bar.setVaryColors(true);
bar.setBarDirection(BarDirection.COL);
chart.plot(bar);

XDDFChartLegend legend = chart.getOrAddLegend();
legend.setPosition(LegendPosition.LEFT);
legend.setOverlay(false);

chart.setTitleText(chartTitle);
chart.setTitleOverlay(false);
}
}

120 changes: 72 additions & 48 deletions src/integrationtest/org/apache/poi/BaseIntegrationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,6 @@ Licensed to the Apache Software Foundation (ASF) under one or more
==================================================================== */
package org.apache.poi;

import static org.junit.Assert.assertNotNull;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipException;

import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.stress.FileHandler;
import org.apache.poi.stress.HSLFFileHandler;
Expand All @@ -35,6 +26,15 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import org.apache.poi.stress.XWPFFileHandler;
import org.junit.Assume;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipException;

import static org.junit.Assert.assertNotNull;

public class BaseIntegrationTest {
private final File rootDir;
private String file;
Expand All @@ -48,73 +48,95 @@ public BaseIntegrationTest(File rootDir, String file, FileHandler handler) {

public void test() throws Exception {
assertNotNull("Unknown file extension for file: " + file + ": " + TestAllFiles.getExtension(file), handler);
testOneFile(new File(rootDir, file));
}

File inputFile = new File(rootDir, file);
try {
handleFile(inputFile);
} catch (OfficeXmlFileException e) {
// check if the file-extension is wrong
if(!e.getMessage().contains("data appears to be in the Office 2007")) {
throw e;
}

// use XWPF instead of HWPF and XSSF instead of HSSF as the file seems to have the wrong extension
handleWrongExtension(inputFile, e);
} catch (OldFileFormatException e) {
if (e.getClass().equals(OldFileFormatException.class)) {
protected void testOneFile(File inputFile) throws Exception {
try {
handleFile(inputFile);
} catch (OfficeXmlFileException e) {
// switch XWPF and HWPF and so forth depending on the error message
handleWrongOLE2XMLExtension(inputFile, e);
} catch (OldFileFormatException e) {
if (e.getClass().equals(OldFileFormatException.class)) {
// Not even text extraction is supported for these: handler.handleExtracting(inputFile);
//noinspection ConstantConditions
Assume.assumeFalse("File " + file + " excluded because it is unsupported old Excel format", true);
}
// otherwise try at least to perform extracting tests on these old files
} catch (EncryptedDocumentException e) {
// Do not try to read encrypted files
//noinspection ConstantConditions
} catch (EncryptedDocumentException e) {
// Do not try to read encrypted files
Assume.assumeFalse("File " + file + " excluded because it is password-encrypted", true);
} catch (ZipException e) {
} catch (ZipException e) {
// some files are corrupted
if (e.getMessage().equals("unexpected EOF")) {
//noinspection ConstantConditions
if (e.getMessage().equals("unexpected EOF") || e.getMessage().equals("Truncated ZIP file")) {
Assume.assumeFalse("File " + file + " excluded because the Zip file is incomplete", true);
}

throw e;
} catch (IOException e) {
// ignore some other ways of corrupted files
if(e.getMessage().contains("Truncated ZIP file")) {
Assume.assumeFalse("File " + file + " excluded because the Zip file is incomplete", true);
}

// sometimes binary format has XML-format-extension...
if(e.getMessage().contains("rong file format or file extension for OO XML file")) {
handleWrongExtension(inputFile, e);
} else {
throw e;
handleWrongOLE2XMLExtension(inputFile, e);
return;
}
} catch (IllegalArgumentException e) {
// ignore errors for documents with incorrect extension
String message = e.getMessage();

throw e;
} catch (IllegalArgumentException e) {
// ignore errors for documents with incorrect extension
String message = e.getMessage();
if(message != null && (message.equals("The document is really a RTF file") ||
message.equals("The document is really a PDF file") ||
message.equals("The document is really a PDF file") ||
message.equals("The document is really a HTML file"))) {
//noinspection ConstantConditions
Assume.assumeFalse("File " + file + " excluded because it is actually a PDF/RTF file", true);
Assume.assumeFalse("File " + file + " excluded because it is actually a PDF/RTF/HTML file", true);
}

if(e.getMessage().equals("The document is really a OOXML file")) {
handleWrongExtension(inputFile, e);
} else {
throw e;
if(message != null && message.equals("The document is really a OOXML file")) {
handleWrongOLE2XMLExtension(inputFile, e);
return;
}
}

try {
handler.handleExtracting(inputFile);
throw e;
}

try {
handler.handleExtracting(inputFile);
} catch (EncryptedDocumentException e) {
// Do not try to read encrypted files
//noinspection ConstantConditions
Assume.assumeFalse("File " + file + " excluded because it is password-encrypted", true);
}
}

void handleWrongExtension(File inputFile, Exception e) throws Exception {
void handleWrongOLE2XMLExtension(File inputFile, Exception e) throws Exception {
// we sometimes have wrong extensions, so for some exceptions we try to handle it
// with the correct FileHandler instead
String message = e.getMessage();

// ignore some file-types that we do not want to handle here
Assume.assumeFalse("File " + file + " excluded because it is actually a PDF/RTF/HTML file",
message != null && (message.equals("The document is really a RTF file") ||
message.equals("The document is really a PDF file") ||
message.equals("The document is really a HTML file")));

if(message != null && (message.equals("The document is really a XLS file"))) {
handler = TestAllFiles.HANDLERS.get(".xls");
handleFile(inputFile);
} else if(message != null && (message.equals("The document is really a PPT file"))) {
handler = TestAllFiles.HANDLERS.get(".ppt");
handleFile(inputFile);
} else if(message != null && (message.equals("The document is really a DOC file"))) {
handler = TestAllFiles.HANDLERS.get(".doc");
handleFile(inputFile);
} else if(message != null && (message.equals("The document is really a VSD file"))) {
handler = TestAllFiles.HANDLERS.get(".vsd");
handleFile(inputFile);

// use XWPF instead of HWPF and XSSF instead of HSSF as the file seems to have the wrong extension
if (handler instanceof HWPFFileHandler) {
} else if (handler instanceof HWPFFileHandler) {
handler = TestAllFiles.HANDLERS.get(".docx");
handleFile(inputFile);
} else if (handler instanceof HSSFFileHandler) {
Expand All @@ -123,6 +145,7 @@ void handleWrongExtension(File inputFile, Exception e) throws Exception {
} else if (handler instanceof HSLFFileHandler) {
handler = TestAllFiles.HANDLERS.get(".pptx");
handleFile(inputFile);

// and the other way around, use HWPF instead of XWPF and so forth
} else if(handler instanceof XWPFFileHandler) {
handler = TestAllFiles.HANDLERS.get(".doc");
Expand All @@ -134,6 +157,7 @@ void handleWrongExtension(File inputFile, Exception e) throws Exception {
handler = TestAllFiles.HANDLERS.get(".ppt");
handleFile(inputFile);
} else {
// nothing matched => throw the exception to the outside
throw e;
}
}
Expand Down
19 changes: 14 additions & 5 deletions src/integrationtest/org/apache/poi/TestAllFiles.java
Original file line number Diff line number Diff line change
Expand Up @@ -187,11 +187,11 @@ public class TestAllFiles {
HANDLERS.put(".tif", new NullFileHandler());
HANDLERS.put(".tiff", new NullFileHandler());
HANDLERS.put(".wav", new NullFileHandler());
HANDLERS.put(".pfx", new NullFileHandler());
HANDLERS.put(".xml", new NullFileHandler());
HANDLERS.put(".csv", new NullFileHandler());
HANDLERS.put(".ods", new NullFileHandler());
HANDLERS.put(".ttf", new NullFileHandler());
HANDLERS.put(".fntdata", new NullFileHandler());
// VBA source files
HANDLERS.put(".vba", new NullFileHandler());
HANDLERS.put(".bas", new NullFileHandler());
Expand All @@ -211,7 +211,13 @@ public class TestAllFiles {
HANDLERS.put("spreadsheet/BigSSTRecord2CR7", new NullFileHandler());
HANDLERS.put("spreadsheet/BigSSTRecordCR", new NullFileHandler());
HANDLERS.put("spreadsheet/test_properties1", new NullFileHandler());


// keystore files
HANDLERS.put(".pfx", new NullFileHandler());
HANDLERS.put(".pem", new NullFileHandler());
HANDLERS.put(".jks", new NullFileHandler());
HANDLERS.put(".pkcs12", new NullFileHandler());

Map<String,String> passmap = new HashMap<>();
passmap.put("slideshow/Password_Protected-hello.ppt", "hello");
passmap.put("slideshow/Password_Protected-56-hello.ppt", "hello");
Expand Down Expand Up @@ -325,6 +331,9 @@ private static Set<String> hashSet(String... a) {
"spreadsheet/sample.strict.xlsx",
"spreadsheet/57914.xlsx",

// files with XML entities
"openxml4j/ContentTypeHasEntities.ooxml",

// non-TNEF files
"ddf/Container.dat",
"ddf/47143.dat",
Expand Down Expand Up @@ -465,15 +474,15 @@ public static String getExtension(String file) {

public static class NullFileHandler implements FileHandler {
@Override
public void handleFile(InputStream stream, String path) throws Exception {
public void handleFile(InputStream stream, String path) {
}

@Override
public void handleExtracting(File file) throws Exception {
public void handleExtracting(File file) {
}

@Override
public void handleAdditional(File file) throws Exception {
public void handleAdditional(File file) {
}
}
}
27 changes: 25 additions & 2 deletions src/integrationtest/org/apache/poi/stress/AbstractFileHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,18 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.extractor.POIOLE2TextExtractor;
import org.apache.poi.extractor.POITextExtractor;
import org.apache.poi.hssf.extractor.EventBasedExcelExtractor;
import org.apache.poi.ooxml.extractor.ExtractorFactory;
import org.apache.poi.hpsf.extractor.HPSFPropertiesExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.ss.extractor.ExcelExtractor;
import org.apache.poi.util.IOUtils;
import org.apache.xmlbeans.XmlException;

/**
* Base class with things that can be run for any supported file handler
* in the integration tests, mostly text-extraction related at the moment.
*/
public abstract class AbstractFileHandler implements FileHandler {
public static final Set<String> EXPECTED_EXTRACTOR_FAILURES = new HashSet<>();
static {
Expand Down Expand Up @@ -79,6 +85,7 @@ private void handleExtractingInternal(File file) throws Exception {
long modified = file.lastModified();

POITextExtractor extractor = null;
String fileAndParentName = file.getParentFile().getName() + "/" + file.getName();
try {
extractor = ExtractorFactory.createExtractor(file);
assertNotNull("Should get a POITextExtractor but had none for file " + file, extractor);
Expand All @@ -91,7 +98,7 @@ private void handleExtractingInternal(File file) throws Exception {
assertNotNull(metadataExtractor.getText());

assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!",
EXPECTED_EXTRACTOR_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName()));
EXPECTED_EXTRACTOR_FAILURES.contains(fileAndParentName));

assertEquals("File should not be modified by extractor", length, file.length());
assertEquals("File should not be modified by extractor", modified, file.lastModified());
Expand All @@ -107,8 +114,24 @@ private void handleExtractingInternal(File file) throws Exception {
assertNotNull(text);
}
}

// test again with including formulas and cell-comments as this caused some bugs
if(extractor instanceof ExcelExtractor &&
// comment-extraction and formula extraction are not well supported in event based extraction
!(extractor instanceof EventBasedExcelExtractor)) {
((ExcelExtractor)extractor).setFormulasNotResults(true);

String text = extractor.getText();
assertNotNull(text);
// */

((ExcelExtractor) extractor).setIncludeCellComments(true);

text = extractor.getText();
assertNotNull(text);
}
} catch (IllegalArgumentException e) {
if(!EXPECTED_EXTRACTOR_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
if(!EXPECTED_EXTRACTOR_FAILURES.contains(fileAndParentName)) {
throw e;
}
} catch (EncryptedDocumentException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ public void handleFile(InputStream stream, String path) throws Exception {
}
}
}

HSSFOptimiser.optimiseFonts(wb);
}

private static final Set<String> EXPECTED_ADDITIONAL_FAILURES = new HashSet<>();
Expand All @@ -85,21 +87,22 @@ public void handleFile(InputStream stream, String path) throws Exception {
public void handleAdditional(File file) throws Exception {
// redirect stdout as the examples often write lots of text
PrintStream oldOut = System.out;
String fileWithParent = file.getParentFile().getName() + "/" + file.getName();
try {
System.setOut(new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
public void write(int b) {
}
}));

BiffViewer.main(new String[]{file.getAbsolutePath()});

assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!",
EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName()));
EXPECTED_ADDITIONAL_FAILURES.contains(fileWithParent));
} catch (OldExcelFormatException e) {
// old excel formats are not supported here
} catch (RuntimeException e) {
if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
if(!EXPECTED_ADDITIONAL_FAILURES.contains(fileWithParent)) {
throw e;
}
} finally {
Expand Down
83 changes: 58 additions & 25 deletions src/integrationtest/org/apache/poi/stress/SlideShowHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,18 @@ Licensed to the Apache Software Foundation (ASF) under one or more
==================================================================== */
package org.apache.poi.stress;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.apache.poi.sl.draw.Drawable;
import org.apache.poi.sl.usermodel.GroupShape;
import org.apache.poi.sl.usermodel.Notes;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.Shape;
import org.apache.poi.sl.usermodel.SimpleShape;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.sl.usermodel.TextRun;
import org.apache.poi.sl.usermodel.TextShape;

import java.awt.Dimension;
import java.awt.Graphics2D;
Expand All @@ -26,17 +36,10 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;

import org.apache.poi.sl.draw.DrawFactory;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.Shape;
import org.apache.poi.sl.usermodel.ShapeContainer;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.sl.usermodel.TextRun;
import org.apache.poi.sl.usermodel.TextShape;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public abstract class SlideShowHandler extends POIFSFileHandler {
public void handleSlideShow(SlideShow<?,?> ss) throws IOException {
Expand Down Expand Up @@ -72,20 +75,50 @@ private ByteArrayOutputStream writeToArray(SlideShow<?,?> ss) throws IOException
private void readContent(SlideShow<?,?> ss) {
for (Slide<?,?> s : ss.getSlides()) {
s.getTitle();
readText(s);
readText(s.getNotes());
readText(s.getMasterSheet());

for (Shape<?,?> shape : s) {
readShapes(shape);
}

Notes<?, ?> notes = s.getNotes();
if(notes != null) {
for (Shape<?, ?> shape : notes) {
readShapes(shape);
}
}

for (Shape<?,?> shape : s.getMasterSheet()) {
readShapes(shape);
}
}
}

private void readText(ShapeContainer<?,?> sc) {
if (sc == null) return;
for (Shape<?,?> s : sc) {
if (s instanceof TextShape) {
for (TextParagraph<?,?,?> tp : (TextShape<?,?>)s) {
for (TextRun tr : tp) {
tr.getRawText();
}

private void readShapes(Shape<?,?> s) {
// recursively walk group-shapes
if(s instanceof GroupShape) {
GroupShape<? extends Shape, ?> shapes = (GroupShape<? extends Shape, ?>) s;
for (Shape<? extends Shape, ?> shape : shapes) {
readShapes(shape);
}
}

if(s instanceof SimpleShape) {
SimpleShape<?, ?> simpleShape = (SimpleShape<?, ?>) s;

simpleShape.getFillColor();
simpleShape.getFillStyle();
simpleShape.getStrokeStyle();
simpleShape.getLineDecoration();
}

readText(s);
}

private void readText(Shape<?,?> s) {
if (s instanceof TextShape) {
for (TextParagraph<?,?,?> tp : (TextShape<?,?>)s) {
for (TextRun tr : tp) {
tr.getRawText();
}
}
}
Expand All @@ -105,13 +138,13 @@ private void renderSlides(SlideShow<?,?> ss) {
for (Slide<?,?> s : ss.getSlides()) {
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = img.createGraphics();
DrawFactory.getInstance(graphics).fixFonts(graphics);

// default rendering options
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setRenderingHint(Drawable.BUFFERED_IMAGE, new WeakReference<>(img));

// draw stuff
s.draw(graphics);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.extractor.EmbeddedData;
import org.apache.poi.ss.extractor.EmbeddedExtractor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
Expand Down Expand Up @@ -91,6 +91,13 @@ private void readContent(Workbook wb) {
}
}
}

for (Name name : wb.getAllNames()) {
// this sometimes caused exceptions
if(!name.isFunctionName()) {
name.getRefersToFormula();
}
}
}

private void extractEmbedded(Workbook wb) throws IOException {
Expand Down
10 changes: 5 additions & 5 deletions src/java/org/apache/poi/POIDocument.java
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ protected PropertySet getPropertySet(String setName, EncryptionInfo encryptionIn

/**
* Writes out the updated standard Document Information Properties (HPSF)
* into the currently open NPOIFSFileSystem
* into the currently open POIFSFileSystem
*
* @throws IOException if an error when writing to the open
* {@link POIFSFileSystem} occurs
Expand All @@ -258,7 +258,7 @@ protected void writeProperties(POIFSFileSystem outFS) throws IOException {
}
/**
* Writes out the standard Document Information Properties (HPSF)
* @param outFS the NPOIFSFileSystem to write the properties into
* @param outFS the {@link POIFSFileSystem} to write the properties into
* @param writtenEntries a list of POIFS entries to add the property names too
*
* @throws IOException if an error when writing to the
Expand Down Expand Up @@ -314,7 +314,7 @@ private void writePropertySet(String name, PropertySet ps, POIFSFileSystem outFS
*
* @param name the (POIFS Level) name of the property to write
* @param set the PropertySet to write out
* @param outFS the NPOIFSFileSystem to write the property into
* @param outFS the {@link POIFSFileSystem} to write the property into
*
* @throws IOException if an error when writing to the
* {@link POIFSFileSystem} occurs
Expand Down Expand Up @@ -418,8 +418,8 @@ protected void validateInPlaceWritePossible() throws IllegalStateException {
@Override
public void close() throws IOException {
if (directory != null) {
if (directory.getNFileSystem() != null) {
directory.getNFileSystem().close();
if (directory.getFileSystem() != null) {
directory.getFileSystem().close();
clearDirectory();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public enum FontCharset {
/** Specifies the Russian Cyrillic character set. */
RUSSIAN(0x000000CC, "Cp1251"),
/** Specifies the Thai character set. */
THAI_(0x000000DE, "x-windows-874"),
THAI(0x000000DE, "x-windows-874"),
/** Specifies a Eastern European character set. */
EASTEUROPE(0x000000EE, "Cp1250"),
/**
Expand Down
75 changes: 75 additions & 0 deletions src/java/org/apache/poi/common/usermodel/fonts/FontFacet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.apache.poi.common.usermodel.fonts;

import org.apache.poi.util.Beta;

/**
* A FontFacet holds the font data for a shape of a font, i.e. a regular,
* italic, bold or bold-italic version of a Font.
*/
@SuppressWarnings("unused")
@Beta
public interface FontFacet {
/**
* Get the font weight.<p>
*
* The weight of the font in the range 0 through 1000.
* For example, 400 is normal and 700 is bold.
* If this value is zero, a default weight is used.
*
* @return the font weight
*
* @since POI 4.1.0
*/
default int getWeight() {
return FontHeader.REGULAR_WEIGHT;
}

/**
* Set the font weight
*
* @param weight the font weight
*/
default void setWeight(int weight) {
throw new UnsupportedOperationException("FontFacet is read-only.");
}

/**
* @return {@code true}, if the font is italic
*/
default boolean isItalic() {
return false;
}

/**
* Set the font posture
*
* @param italic {@code true} for italic, {@code false} for regular
*/
default void setItalic(boolean italic) {
throw new UnsupportedOperationException("FontFacet is read-only.");
}

/**
* @return the wrapper object holding the font data
*/
default Object getFontData() {
return null;
}
}
227 changes: 227 additions & 0 deletions src/java/org/apache/poi/common/usermodel/fonts/FontHeader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.apache.poi.common.usermodel.fonts;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndianByteArrayInputStream;
import org.apache.poi.util.LittleEndianInput;
import org.apache.poi.util.LittleEndianInputStream;


/**
* The header data of an EOT font.<p>
*
* Currently only version 1 fields are read to identify a stream to be embedded.
*
* @see <a href="http://www.w3.org/Submission/EOT">Embedded OpenType (EOT) File Format</a>
*/
@SuppressWarnings({"FieldCanBeLocal", "unused", "Duplicates"})
public class FontHeader implements FontInfo {
/**
* Fonts with a font weight of 400 are regarded as regular weighted.
* Higher font weights (up to 1000) are bold - lower weights are thin.
*/
public static final int REGULAR_WEIGHT = 400;

private int eotSize;
private int fontDataSize;
private int version;
private int flags;
private final byte[] panose = new byte[10];
private byte charset;
private byte italic;
private int weight;
private int fsType;
private int magic;
private int unicodeRange1;
private int unicodeRange2;
private int unicodeRange3;
private int unicodeRange4;
private int codePageRange1;
private int codePageRange2;
private int checkSumAdjustment;
private String familyName;
private String styleName;
private String versionName;
private String fullName;

public void init(byte[] source, int offset, int length) {
init(new LittleEndianByteArrayInputStream(source, offset, length));
}

public void init(LittleEndianInput leis) {
eotSize = leis.readInt();
fontDataSize = leis.readInt();
version = leis.readInt();
if (version != 0x00010000 && version != 0x00020001 && version != 0x00020002) {
throw new RuntimeException("not a EOT font data stream");
}
flags = leis.readInt();
leis.readFully(panose);
charset = leis.readByte();
italic = leis.readByte();
weight = leis.readInt();
fsType = leis.readUShort();
magic = leis.readUShort();
if (magic != 0x504C) {
throw new RuntimeException("not a EOT font data stream");
}
unicodeRange1 = leis.readInt();
unicodeRange2 = leis.readInt();
unicodeRange3 = leis.readInt();
unicodeRange4 = leis.readInt();
codePageRange1 = leis.readInt();
codePageRange2 = leis.readInt();
checkSumAdjustment = leis.readInt();
int reserved1 = leis.readInt();
int reserved2 = leis.readInt();
int reserved3 = leis.readInt();
int reserved4 = leis.readInt();
familyName = readName(leis);
styleName = readName(leis);
versionName = readName(leis);
fullName = readName(leis);

}

public InputStream bufferInit(InputStream fontStream) throws IOException {
LittleEndianInputStream is = new LittleEndianInputStream(fontStream);
is.mark(1000);
init(is);
is.reset();
return is;
}

private String readName(LittleEndianInput leis) {
// padding
leis.readShort();
int nameSize = leis.readUShort();
byte[] nameBuf = IOUtils.safelyAllocate(nameSize, 1000);
leis.readFully(nameBuf);
// may be 0-terminated, just trim it away
return new String(nameBuf, 0, nameSize, StandardCharsets.UTF_16LE).trim();
}

public boolean isItalic() {
return italic != 0;
}

public int getWeight() {
return weight;
}

public boolean isBold() {
return getWeight() > REGULAR_WEIGHT;
}

public byte getCharsetByte() {
return charset;
}

public FontCharset getCharset() {
return FontCharset.valueOf(getCharsetByte());
}

public FontPitch getPitch() {
byte familyKind = panose[0];
switch (familyKind) {
default:
// Any
case 0:
// No Fit
case 1:
return FontPitch.VARIABLE;

// Latin Text
case 2:
// Latin Decorative
case 4:
byte proportion = panose[3];
return proportion == 9 ? FontPitch.FIXED : FontPitch.VARIABLE;

// Latin Hand Written
case 3:
// Latin Symbol
case 5:
byte spacing = panose[3];
return spacing == 3 ? FontPitch.FIXED : FontPitch.VARIABLE;
}

}

public FontFamily getFamily() {
switch (panose[0]) {
// Any
case 0:
// No Fit
case 1:
return FontFamily.FF_DONTCARE;
// Latin Text
case 2:
byte serifStyle = panose[1];
return (10 <= serifStyle && serifStyle <= 15)
? FontFamily.FF_SWISS : FontFamily.FF_ROMAN;
// Latin Hand Written
case 3:
return FontFamily.FF_SCRIPT;
// Latin Decorative
default:
case 4:
return FontFamily.FF_DECORATIVE;
// Latin Symbol
case 5:
return FontFamily.FF_MODERN;
}
}

public String getFamilyName() {
return familyName;
}

public String getStyleName() {
return styleName;
}

public String getVersionName() {
return versionName;
}

public String getFullName() {
return fullName;
}

public byte[] getPanose() {
return panose;
}

@Override
public String getTypeface() {
return getFamilyName();
}

public int getFlags() {
return flags;
}
}



68 changes: 59 additions & 9 deletions src/java/org/apache/poi/common/usermodel/fonts/FontInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ Licensed to the Apache Software Foundation (ASF) under one or more

package org.apache.poi.common.usermodel.fonts;

import java.util.Collections;
import java.util.List;

import org.apache.poi.util.Beta;

/**
* A FontInfo object holds information about a font configuration.
* It is roughly an equivalent to the LOGFONT structure in Windows GDI.<p>
Expand All @@ -30,14 +35,17 @@ Licensed to the Apache Software Foundation (ASF) under one or more
*
* @see <a href="https://msdn.microsoft.com/en-us/library/dd145037.aspx">LOGFONT structure</a>
*/
@SuppressWarnings("unused")
public interface FontInfo {

/**
* Get the index within the collection of Font objects
* @return unique index number of the underlying record this Font represents
* (probably you don't care unless you're comparing which one is which)
*/
Integer getIndex();
default Integer getIndex() {
return null;
}

/**
* Sets the index within the collection of Font objects
Expand All @@ -46,7 +54,9 @@ public interface FontInfo {
*
* @throws UnsupportedOperationException if unsupported
*/
void setIndex(int index);
default void setIndex(int index) {
throw new UnsupportedOperationException("FontInfo is read-only.");
}


/**
Expand All @@ -60,36 +70,48 @@ public interface FontInfo {
* @param typeface the full name of the font, when {@code null} removes the font definition -
* removal is implementation specific
*/
void setTypeface(String typeface);
default void setTypeface(String typeface) {
throw new UnsupportedOperationException("FontInfo is read-only.");
}

/**
* @return the font charset
*/
FontCharset getCharset();
default FontCharset getCharset() {
return FontCharset.ANSI;
}

/**
* Sets the charset
*
* @param charset the charset
*/
void setCharset(FontCharset charset);
default void setCharset(FontCharset charset) {
throw new UnsupportedOperationException("FontInfo is read-only.");
}

/**
* @return the family class
*/
FontFamily getFamily();
default FontFamily getFamily() {
return FontFamily.FF_DONTCARE;
}

/**
* Sets the font family class
*
* @param family the font family class
*/
void setFamily(FontFamily family);
default void setFamily(FontFamily family) {
throw new UnsupportedOperationException("FontInfo is read-only.");
}

/**
* @return the font pitch or {@code null} if unsupported
*/
FontPitch getPitch();
default FontPitch getPitch() {
return null;
}

/**
* Set the font pitch
Expand All @@ -98,5 +120,33 @@ public interface FontInfo {
*
* @throws UnsupportedOperationException if unsupported
*/
void setPitch(FontPitch pitch);
default void setPitch(FontPitch pitch) {
throw new UnsupportedOperationException("FontInfo is read-only.");
}

/**
* @return panose info in binary form or {@code null} if unknown
*/
default byte[] getPanose() {
return null;
}

/**
* Set the panose in binary form
* @param panose the panose bytes
*/
default void setPanose(byte[] panose) {
throw new UnsupportedOperationException("FontInfo is read-only.");
}


/**
* If font facets are embedded in the document, return the list of embedded facets.
* The font embedding is experimental, therefore the API can change.
* @return the list of embedded EOT font data
*/
@Beta
default List<? extends FontFacet> getFacets() {
return Collections.emptyList();
}
}
6 changes: 1 addition & 5 deletions src/java/org/apache/poi/ddf/DefaultEscherRecordFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,7 @@ protected static Map<Short, Constructor<? extends EscherRecord>> recordsToMap(Cl
short sid;
try {
sid = recCls.getField("RECORD_ID").getShort(null);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
} catch (IllegalArgumentException | NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
Constructor<? extends EscherRecord> constructor;
Expand Down
2 changes: 1 addition & 1 deletion src/java/org/apache/poi/ddf/EscherBitmapBlip.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public int serialize( int offset, byte[] data, EscherSerializationListener liste

System.arraycopy( field_1_UID, 0, data, pos, 16 );
data[pos + 16] = field_2_marker;
byte pd[] = getPicturedata();
byte[] pd = getPicturedata();
System.arraycopy( pd, 0, data, pos + 17, pd.length );

listener.afterRecordSerialize(offset + getRecordSize(), getRecordId(), getRecordSize(), this);
Expand Down
30 changes: 26 additions & 4 deletions src/java/org/apache/poi/ddf/EscherProperties.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more
*
* @author Glen Stampoultzis (glens at apache.org)
*/
@SuppressWarnings("WeakerAccess")
public final class EscherProperties {

// Property constants
Expand Down Expand Up @@ -117,6 +118,15 @@ public final class EscherProperties {
public static final short GEOMETRY__ADJUST8VALUE = 334;
public static final short GEOMETRY__ADJUST9VALUE = 335;
public static final short GEOMETRY__ADJUST10VALUE = 336;
public static final short GEOMETRY__PCONNECTIONSITES = 337;
public static final short GEOMETRY__PCONNECTIONSITESDIR = 338;
public static final short GEOMETRY__XLIMO = 339;
public static final short GEOMETRY__YLIMO = 340;
public static final short GEOMETRY__PADJUSTHANDLES = 341;
public static final short GEOMETRY__PGUIDES = 342;
public static final short GEOMETRY__PINSCRIBE = 343;
public static final short GEOMETRY__CXK = 344;
public static final short GEOMETRY__PFRAGMENTS = 345;
public static final short GEOMETRY__SHADOWok = 378;
public static final short GEOMETRY__3DOK = 379;
public static final short GEOMETRY__LINEOK = 380;
Expand Down Expand Up @@ -333,6 +343,9 @@ public final class EscherProperties {

private static final Map<Short, EscherPropertyMetaData> properties = initProps();

private EscherProperties() {
}

private static Map<Short, EscherPropertyMetaData> initProps() {
Map<Short, EscherPropertyMetaData> m = new HashMap<>();
addProp(m, TRANSFORM__ROTATION, "transform.rotation");
Expand Down Expand Up @@ -423,6 +436,15 @@ private static Map<Short, EscherPropertyMetaData> initProps() {
addProp(m, GEOMETRY__ADJUST8VALUE, "geometry.adjust8value");
addProp(m, GEOMETRY__ADJUST9VALUE, "geometry.adjust9value");
addProp(m, GEOMETRY__ADJUST10VALUE, "geometry.adjust10value");
addProp(m, GEOMETRY__PCONNECTIONSITES, "geometry.pConnectionSites");
addProp(m, GEOMETRY__PCONNECTIONSITESDIR, "geometry.pConnectionSitesDir");
addProp(m, GEOMETRY__XLIMO, "geometry.xLimo");
addProp(m, GEOMETRY__YLIMO, "geometry.yLimo");
addProp(m, GEOMETRY__PADJUSTHANDLES, "geometry.pAdjustHandles");
addProp(m, GEOMETRY__PGUIDES, "geometry.pGuides");
addProp(m, GEOMETRY__PINSCRIBE, "geometry.pInscribe");
addProp(m, GEOMETRY__CXK, "geometry.cxk");
addProp(m, GEOMETRY__PFRAGMENTS, "geometry.pFragments");
addProp(m, GEOMETRY__SHADOWok, "geometry.shadowOK");
addProp(m, GEOMETRY__3DOK, "geometry.3dok");
addProp(m, GEOMETRY__LINEOK, "geometry.lineok");
Expand Down Expand Up @@ -641,20 +663,20 @@ private static Map<Short, EscherPropertyMetaData> initProps() {
}

private static void addProp(Map<Short, EscherPropertyMetaData> m, int s, String propName) {
m.put(Short.valueOf((short) s), new EscherPropertyMetaData(propName));
m.put((short) s, new EscherPropertyMetaData(propName));
}

private static void addProp(Map<Short, EscherPropertyMetaData> m, int s, String propName, byte type) {
m.put(Short.valueOf((short) s), new EscherPropertyMetaData(propName, type));
m.put((short) s, new EscherPropertyMetaData(propName, type));
}

public static String getPropertyName(short propertyId) {
EscherPropertyMetaData o = properties.get(Short.valueOf(propertyId));
EscherPropertyMetaData o = properties.get(propertyId);
return o == null ? "unknown" : o.getDescription();
}

public static byte getPropertyType(short propertyId) {
EscherPropertyMetaData escherPropertyMetaData = properties.get(Short.valueOf(propertyId));
EscherPropertyMetaData escherPropertyMetaData = properties.get(propertyId);
return escherPropertyMetaData == null ? 0 : escherPropertyMetaData.getType();
}
}
2 changes: 1 addition & 1 deletion src/java/org/apache/poi/ddf/EscherRecord.java
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ protected int readHeader( byte[] data, int offset ) {
* @param offset the offset to start reading from
* @return value of instance part of options field
*/
protected static short readInstance( byte data[], int offset ) {
protected static short readInstance(byte[] data, int offset ) {
final short options = LittleEndian.getShort( data, offset );
return fInstance.getShortValue( options );
}
Expand Down
6 changes: 3 additions & 3 deletions src/java/org/apache/poi/hpsf/Section.java
Original file line number Diff line number Diff line change
Expand Up @@ -831,7 +831,7 @@ private boolean readDictionary(LittleEndianByteArrayInputStream leis, final int
}

try {
byte buf[] = IOUtils.safelyAllocate(nrBytes, MAX_RECORD_LENGTH);
byte[] buf = IOUtils.safelyAllocate(nrBytes, MAX_RECORD_LENGTH);
leis.readFully(buf, 0, nrBytes);
final String str = CodePageUtil.getStringFromCodePage(buf, 0, nrBytes, cp);

Expand Down Expand Up @@ -862,7 +862,7 @@ private boolean readDictionary(LittleEndianByteArrayInputStream leis, final int
*/
private void writeDictionary(final OutputStream out, final int codepage)
throws IOException {
final byte padding[] = new byte[4];
final byte[] padding = new byte[4];
final Map<Long,String> dic = getDictionary();

LittleEndian.putUInt(dic.size(), out);
Expand All @@ -873,7 +873,7 @@ private void writeDictionary(final OutputStream out, final int codepage)
length += LittleEndianConsts.INT_SIZE;

final String value = ls.getValue()+"\0";
final byte bytes[] = CodePageUtil.getBytesInCodePage(value, codepage);
final byte[] bytes = CodePageUtil.getBytesInCodePage(value, codepage);
final int len = (codepage == CodePageUtil.CP_UNICODE) ? value.length() : bytes.length;

LittleEndian.putUInt( len, out );
Expand Down
4 changes: 2 additions & 2 deletions src/java/org/apache/poi/hpsf/UnicodeString.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,15 @@ public String toJavaString() {
final int terminator = result.indexOf( '\0' );
if ( terminator == -1 ) {
String msg =
"String terminator (\\0) for UnicodeString property value not found."+
"String terminator (\\0) for UnicodeString property value not found. " +
"Continue without trimming and hope for the best.";
LOG.log(POILogger.WARN, msg);
return result;
}

if ( terminator != result.length() - 1 ) {
String msg =
"String terminator (\\0) for UnicodeString property value occured before the end of string. "+
"String terminator (\\0) for UnicodeString property value occured before the end of string. " +
"Trimming and hope for the best.";
LOG.log(POILogger.WARN, msg);
}
Expand Down
82 changes: 41 additions & 41 deletions src/java/org/apache/poi/hpsf/Variant.java
Original file line number Diff line number Diff line change
Expand Up @@ -342,47 +342,47 @@ public class Variant
*/
public static final Integer LENGTH_8 = 8;

private static final Object NUMBER_TO_NAME_LIST[][] = {
{ 0L, "VT_EMPTY", LENGTH_0 },
{ 1L, "VT_NULL", LENGTH_UNKNOWN },
{ 2L, "VT_I2", LENGTH_2 },
{ 3L, "VT_I4", LENGTH_4 },
{ 4L, "VT_R4", LENGTH_4 },
{ 5L, "VT_R8", LENGTH_8 },
{ 6L, "VT_CY", LENGTH_UNKNOWN },
{ 7L, "VT_DATE", LENGTH_UNKNOWN },
{ 8L, "VT_BSTR", LENGTH_UNKNOWN },
{ 9L, "VT_DISPATCH", LENGTH_UNKNOWN },
{ 10L, "VT_ERROR", LENGTH_UNKNOWN },
{ 11L, "VT_BOOL", LENGTH_UNKNOWN },
{ 12L, "VT_VARIANT", LENGTH_UNKNOWN },
{ 13L, "VT_UNKNOWN", LENGTH_UNKNOWN },
{ 14L, "VT_DECIMAL", LENGTH_UNKNOWN },
{ 16L, "VT_I1", LENGTH_UNKNOWN },
{ 17L, "VT_UI1", LENGTH_UNKNOWN },
{ 18L, "VT_UI2", LENGTH_UNKNOWN },
{ 19L, "VT_UI4", LENGTH_UNKNOWN },
{ 20L, "VT_I8", LENGTH_UNKNOWN },
{ 21L, "VT_UI8", LENGTH_UNKNOWN },
{ 22L, "VT_INT", LENGTH_UNKNOWN },
{ 23L, "VT_UINT", LENGTH_UNKNOWN },
{ 24L, "VT_VOID", LENGTH_UNKNOWN },
{ 25L, "VT_HRESULT", LENGTH_UNKNOWN },
{ 26L, "VT_PTR", LENGTH_UNKNOWN },
{ 27L, "VT_SAFEARRAY", LENGTH_UNKNOWN },
{ 28L, "VT_CARRAY", LENGTH_UNKNOWN },
{ 29L, "VT_USERDEFINED", LENGTH_UNKNOWN },
{ 30L, "VT_LPSTR", LENGTH_VARIABLE },
{ 31L, "VT_LPWSTR", LENGTH_UNKNOWN },
{ 64L, "VT_FILETIME", LENGTH_8 },
{ 65L, "VT_BLOB", LENGTH_UNKNOWN },
{ 66L, "VT_STREAM", LENGTH_UNKNOWN },
{ 67L, "VT_STORAGE", LENGTH_UNKNOWN },
{ 68L, "VT_STREAMED_OBJECT", LENGTH_UNKNOWN },
{ 69L, "VT_STORED_OBJECT", LENGTH_UNKNOWN },
{ 70L, "VT_BLOB_OBJECT", LENGTH_UNKNOWN },
{ 71L, "VT_CF", LENGTH_UNKNOWN },
{ 72L, "VT_CLSID", LENGTH_UNKNOWN }
private static final Object[][] NUMBER_TO_NAME_LIST = {
{0L, "VT_EMPTY", LENGTH_0},
{1L, "VT_NULL", LENGTH_UNKNOWN},
{2L, "VT_I2", LENGTH_2},
{3L, "VT_I4", LENGTH_4},
{4L, "VT_R4", LENGTH_4},
{5L, "VT_R8", LENGTH_8},
{6L, "VT_CY", LENGTH_UNKNOWN},
{7L, "VT_DATE", LENGTH_UNKNOWN},
{8L, "VT_BSTR", LENGTH_UNKNOWN},
{9L, "VT_DISPATCH", LENGTH_UNKNOWN},
{10L, "VT_ERROR", LENGTH_UNKNOWN},
{11L, "VT_BOOL", LENGTH_UNKNOWN},
{12L, "VT_VARIANT", LENGTH_UNKNOWN},
{13L, "VT_UNKNOWN", LENGTH_UNKNOWN},
{14L, "VT_DECIMAL", LENGTH_UNKNOWN},
{16L, "VT_I1", LENGTH_UNKNOWN},
{17L, "VT_UI1", LENGTH_UNKNOWN},
{18L, "VT_UI2", LENGTH_UNKNOWN},
{19L, "VT_UI4", LENGTH_UNKNOWN},
{20L, "VT_I8", LENGTH_UNKNOWN},
{21L, "VT_UI8", LENGTH_UNKNOWN},
{22L, "VT_INT", LENGTH_UNKNOWN},
{23L, "VT_UINT", LENGTH_UNKNOWN},
{24L, "VT_VOID", LENGTH_UNKNOWN},
{25L, "VT_HRESULT", LENGTH_UNKNOWN},
{26L, "VT_PTR", LENGTH_UNKNOWN},
{27L, "VT_SAFEARRAY", LENGTH_UNKNOWN},
{28L, "VT_CARRAY", LENGTH_UNKNOWN},
{29L, "VT_USERDEFINED", LENGTH_UNKNOWN},
{30L, "VT_LPSTR", LENGTH_VARIABLE},
{31L, "VT_LPWSTR", LENGTH_UNKNOWN},
{64L, "VT_FILETIME", LENGTH_8},
{65L, "VT_BLOB", LENGTH_UNKNOWN},
{66L, "VT_STREAM", LENGTH_UNKNOWN},
{67L, "VT_STORAGE", LENGTH_UNKNOWN},
{68L, "VT_STREAMED_OBJECT", LENGTH_UNKNOWN},
{69L, "VT_STORED_OBJECT", LENGTH_UNKNOWN},
{70L, "VT_BLOB_OBJECT", LENGTH_UNKNOWN},
{71L, "VT_CF", LENGTH_UNKNOWN},
{72L, "VT_CLSID", LENGTH_UNKNOWN}
};

/* Initialize the number-to-name and number-to-length map: */
Expand Down
2 changes: 2 additions & 0 deletions src/java/org/apache/poi/hpsf/wellknown/PropertyIDMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,8 @@ public static synchronized PropertyIDMap getDocumentSummaryInformationProperties
/**
* Returns a property map, which is only used as a fallback, i.e. if available, the correct map
* for {@link DocumentSummaryInformation} or {@link SummaryInformation} should be used.
*
* @return the resulting property map
*/
public static synchronized PropertyIDMap getFallbackProperties() {
if (fallbackProperties == null) {
Expand Down
14 changes: 5 additions & 9 deletions src/java/org/apache/poi/hssf/dev/BiffViewer.java
Original file line number Diff line number Diff line change
Expand Up @@ -527,20 +527,16 @@ public int read() throws IOException {
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (b == null || off < 0 || len < 0 || b.length < off+len) {
throw new IllegalArgumentException();
}
if (_currentPos >= _currentSize) {
fillNextBuffer();
}
if (_currentPos >= _currentSize) {
return -1;
}
int availSize = _currentSize - _currentPos;
int result;
if (len > availSize) {
System.err.println("Unexpected request to read past end of current biff record");
result = availSize;
} else {
result = len;
}
final int result = Math.min(len, _currentSize - _currentPos);
System.arraycopy(_data, _currentPos, b, off, result);
_currentPos += result;
_overallStreamPos += result;
Expand Down Expand Up @@ -703,7 +699,7 @@ private static char getPrintableChar(byte b) {
return ib;
}

private static void writeHex(char buf[], int startInBuf, int value, int nDigits) {
private static void writeHex(char[] buf, int startInBuf, int value, int nDigits) {
int acc = value;
for(int i=nDigits-1; i>=0; i--) {
int digit = acc & 0x0F;
Expand Down
2 changes: 1 addition & 1 deletion src/java/org/apache/poi/hssf/dev/FormulaViewer.java
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ public void setList(boolean list) {
* @param args pass one argument with the filename or --help
* @throws IOException if the file can't be read or contained errors
*/
public static void main(String args[]) throws IOException
public static void main(String[] args) throws IOException
{
if ((args == null) || (args.length >2 )
|| args[ 0 ].equals("--help"))
Expand Down
6 changes: 3 additions & 3 deletions src/java/org/apache/poi/hssf/extractor/ExcelExtractor.java
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ public void setIncludeHeadersFooters(boolean includeHeadersFooters) {

@Override
public String getText() {
StringBuffer text = new StringBuffer();
StringBuilder text = new StringBuilder();

// We don't care about the difference between
// null (missing) and blank cells
Expand Down Expand Up @@ -374,7 +374,7 @@ public String getText() {
// Replace any newlines with spaces, otherwise it
// breaks the output
String commentText = comment.getString().getString().replace('\n', ' ');
text.append(" Comment by "+comment.getAuthor()+": "+commentText);
text.append(" Comment by ").append(comment.getAuthor()).append(": ").append(commentText);
}
}

Expand All @@ -398,7 +398,7 @@ public String getText() {
}

public static String _extractHeaderFooter(HeaderFooter hf) {
StringBuffer text = new StringBuffer();
StringBuilder text = new StringBuilder();

if(hf.getLeft() != null) {
text.append(hf.getLeft());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ private void open(DirectoryNode directory) throws IOException {
DocumentNode book;
try {
book = (DocumentNode)directory.getEntry(OLD_WORKBOOK_DIR_ENTRY_NAME);
} catch (FileNotFoundException e) {
} catch (FileNotFoundException | IllegalArgumentException e) {
// some files have "Workbook" instead
book = (DocumentNode)directory.getEntry(WORKBOOK_DIR_ENTRY_NAMES[0]);
}
Expand Down
8 changes: 5 additions & 3 deletions src/java/org/apache/poi/hssf/model/InternalWorkbook.java
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,8 @@ public void setSheetHidden(int sheetnum, boolean hidden) {
* @since 3.16 beta 2
*/
public void setSheetHidden(int sheetnum, SheetVisibility visibility) {
checkSheets(sheetnum);

BoundSheetRecord bsr = getBoundSheetRec(sheetnum);
bsr.setHidden(visibility == SheetVisibility.HIDDEN);
bsr.setVeryHidden(visibility == SheetVisibility.VERY_HIDDEN);
Expand Down Expand Up @@ -1338,7 +1340,7 @@ private static FontRecord createFont() {
*/
private static FormatRecord createFormat(int id) {
// we'll need multiple editions for the different formats
final int mappings[] = { 5, 6, 7, 8, 0x2a, 0x29, 0x2c, 0x2b };
final int[] mappings = {5, 6, 7, 8, 0x2a, 0x29, 0x2c, 0x2b};
if (id < 0 || id >= mappings.length) {
throw new IllegalArgumentException("Unexpected id " + id);
}
Expand Down Expand Up @@ -1433,8 +1435,8 @@ private static ExtendedFormatRecord createExtendedFormat() {
*/
private static StyleRecord createStyle(int id) {
// we'll need multiple editions
final int mappings[][] = {
{ 0x010, 3 }, { 0x011, 6 }, { 0x012, 4 }, { 0x013, 7 }, { 0x000, 0 }, { 0x014, 5 }
final int[][] mappings = {
{0x010, 3}, {0x011, 6}, {0x012, 4}, {0x013, 7}, {0x000, 0}, {0x014, 5}
};
if (id < 0 || id >= mappings.length) {
throw new IllegalArgumentException("Unexpected style id " + id);
Expand Down
2 changes: 1 addition & 1 deletion src/java/org/apache/poi/hssf/record/BoundSheetRecord.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public BoundSheetRecord(String sheetname) {
* @param in the record stream to read from
*/
public BoundSheetRecord(RecordInputStream in) {
byte buf[] = new byte[LittleEndianConsts.INT_SIZE];
byte[] buf = new byte[LittleEndianConsts.INT_SIZE];
in.readPlain(buf, 0, buf.length);
field_1_position_of_BOF = LittleEndian.getInt(buf);
field_2_option_flags = in.readUShort();
Expand Down
Loading