View | Details | Raw Unified | Return to bug 57003
Collapse All | Expand All

(-)a/.classpath (-5 / +1 lines)
Lines 23-33 Link Here
23
	<classpathentry kind="lib" path="lib/hamcrest-core-1.3.jar"/>
23
	<classpathentry kind="lib" path="lib/hamcrest-core-1.3.jar"/>
24
	<classpathentry kind="lib" path="lib/junit-4.11.jar"/>
24
	<classpathentry kind="lib" path="lib/junit-4.11.jar"/>
25
	<classpathentry kind="lib" path="ooxml-lib/ooxml-schemas-1.1.jar" sourcepath="ooxml-lib/ooxml-schemas-src-1.1.jar"/>
25
	<classpathentry kind="lib" path="ooxml-lib/ooxml-schemas-1.1.jar" sourcepath="ooxml-lib/ooxml-schemas-src-1.1.jar"/>
26
	<classpathentry kind="lib" path="ooxml-lib/ooxml-security-1.0.jar" sourcepath="ooxml-lib/ooxml-security-src-1.0.jar"/>
26
	<classpathentry kind="lib" path="ooxml-lib/ooxml-encryption-1.1.jar" sourcepath="ooxml-lib/ooxml-encryption-src-1.1.jar"/>
27
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
27
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
28
	<classpathentry kind="lib" path="compile-lib/slf4j-api-1.7.7.jar"/>
29
	<classpathentry kind="lib" path="compile-lib/bcpkix-jdk15on-1.51.jar"/>
30
	<classpathentry kind="lib" path="compile-lib/bcprov-ext-jdk15on-1.51.jar"/>
31
	<classpathentry kind="lib" path="compile-lib/xmlsec-2.0.1.jar"/>
32
	<classpathentry kind="output" path="build/eclipse"/>
28
	<classpathentry kind="output" path="build/eclipse"/>
33
</classpath>
29
</classpath>
(-)a/build.xml (-170 / +79 lines)
Lines 30-42 under the License. Link Here
30
        Yegor Kozlov        yegor at apache.org
30
        Yegor Kozlov        yegor at apache.org
31
        Dominik Stadler     centic at apache.org
31
        Dominik Stadler     centic at apache.org
32
32
33
    This build was tested with ant 1.9.4 although it will probably work with
33
    This build was tested with ant 1.6.2 although it will probably work with
34
    other versions, however at least 1.8.0 is required.  The following jar 
34
    other versions.  The following jar files should be available on the 
35
	files should be available on the classpath when running ant:
35
    classpath when running ant:
36
36
37
    LIBRARY         LOCATION
37
    LIBRARY         LOCATION
38
    =======         ========
38
    =======         ========
39
    junit(4.11+)     http://www.junit.org
39
    junit(3.8+)     http://www.junit.org
40
40
41
    To build the documentation you will need to install forrest and set
41
    To build the documentation you will need to install forrest and set
42
    the FORREST_HOME environment variable.  Forrest 0.5.1 required.
42
    the FORREST_HOME environment variable.  Forrest 0.5.1 required.
Lines 61-67 under the License. Link Here
61
61
62
    <property name="main.lib" location="lib"/>
62
    <property name="main.lib" location="lib"/>
63
    <property name="ooxml.lib" location="ooxml-lib"/>
63
    <property name="ooxml.lib" location="ooxml-lib"/>
64
	<property name="compile.lib" location="compile-lib"/>
65
    <property name="forrest.home" value="${env.FORREST_HOME}"/>
64
    <property name="forrest.home" value="${env.FORREST_HOME}"/>
66
65
67
    <!-- compiler options options -->
66
    <!-- compiler options options -->
Lines 86-92 under the License. Link Here
86
    <property name="poi.test.locale" value="-Duser.language=en -Duser.country=US"/>
85
    <property name="poi.test.locale" value="-Duser.language=en -Duser.country=US"/>
87
    <property name="POI.testdata.path" value="test-data"/>
86
    <property name="POI.testdata.path" value="test-data"/>
88
    <property name="java.awt.headless" value="true"/>
87
    <property name="java.awt.headless" value="true"/>
89
	<property name="additionaljar" value=""/>
90
    
88
    
91
    <!-- Main: -->
89
    <!-- Main: -->
92
    <property name="main.resource1.dir" value="src/resources/main"/>
90
    <property name="main.resource1.dir" value="src/resources/main"/>
Lines 120-125 under the License. Link Here
120
    <property name="ooxml.output.test.dir" location="build/ooxml-test-classes"/>
118
    <property name="ooxml.output.test.dir" location="build/ooxml-test-classes"/>
121
    <property name="ooxml.testokfile" location="build/ooxml-testokfile.txt"/>
119
    <property name="ooxml.testokfile" location="build/ooxml-testokfile.txt"/>
122
    <property name="ooxml.lite.output.dir" location="build/ooxml-lite-classes"/>
120
    <property name="ooxml.lite.output.dir" location="build/ooxml-lite-classes"/>
121
    <property name="ooxml.encryption.xsd.dir" location="src/ooxml/resources/org/apache/poi/poifs/crypt"/>
123
122
124
    <!-- Excelant: -->
123
    <!-- Excelant: -->
125
    <property name="excelant.resource.dir" value="src/excelant/resources"/>
124
    <property name="excelant.resource.dir" value="src/excelant/resources"/>
Lines 148-164 under the License. Link Here
148
    <property name="main.antlauncher.jar" location="${main.lib}/ant-launcher-1.9.4.jar"/>
147
    <property name="main.antlauncher.jar" location="${main.lib}/ant-launcher-1.9.4.jar"/>
149
    <property name="main.antlauncher.url" value="${repository.m2}/maven2/org/apache/ant/ant-launcher/1.9.4/ant-launcher-1.9.4.jar"/>
148
    <property name="main.antlauncher.url" value="${repository.m2}/maven2/org/apache/ant/ant-launcher/1.9.4/ant-launcher-1.9.4.jar"/>
150
149
151
	<!-- xml signature libs -->
150
    <!-- jars in the lib-ooxml directory, see the fetch-ooxml-jars target-->
152
	<property name="dsig.xmlsec.jar" location="${compile.lib}/xmlsec-2.0.1.jar"/>
153
	<property name="dsig.xmlsec.url" value="${repository.m2}/maven2/org/apache/santuario/xmlsec/2.0.1/xmlsec-2.0.1.jar"/>
154
	<property name="dsig.bouncycastle-prov.jar" location="${compile.lib}/bcprov-ext-jdk15on-1.51.jar"/>
155
	<property name="dsig.bouncycastle-prov.url" value="${repository.m2}/maven2/org/bouncycastle/bcprov-ext-jdk15on/1.51/bcprov-ext-jdk15on-1.51.jar"/>
156
	<property name="dsig.bouncycastle-pkix.jar" location="${compile.lib}/bcpkix-jdk15on-1.51.jar"/>
157
	<property name="dsig.bouncycastle-pkix.url" value="${repository.m2}/maven2/org/bouncycastle/bcpkix-jdk15on/1.51/bcpkix-jdk15on-1.51.jar"/>
158
	<property name="dsig.sl4j-api.jar" location="${compile.lib}/slf4j-api-1.7.7.jar"/>
159
	<property name="dsig.sl4j-api.url" value="${repository.m2}/maven2/org/slf4j/slf4j-api/1.7.7/slf4j-api-1.7.7.jar"/>
160
161
	<!-- jars in the lib-ooxml directory, see the fetch-ooxml-jars target-->
162
    <property name="ooxml.xmlbeans23.jar" location="${ooxml.lib}/xmlbeans-2.3.0.jar"/>
151
    <property name="ooxml.xmlbeans23.jar" location="${ooxml.lib}/xmlbeans-2.3.0.jar"/>
163
    <property name="ooxml.xmlbeans23.url"
152
    <property name="ooxml.xmlbeans23.url"
164
              value="${repository.m2}/maven2/org/apache/xmlbeans/xmlbeans/2.3.0/xmlbeans-2.3.0.jar"/>
153
              value="${repository.m2}/maven2/org/apache/xmlbeans/xmlbeans/2.3.0/xmlbeans-2.3.0.jar"/>
Lines 171-207 under the License. Link Here
171
    <property name="jacoco.url" value="${repository.m2}/maven2/org/jacoco/jacoco/0.7.1.201405082137/jacoco-0.7.1.201405082137.zip"/>
160
    <property name="jacoco.url" value="${repository.m2}/maven2/org/jacoco/jacoco/0.7.1.201405082137/jacoco-0.7.1.201405082137.zip"/>
172
    <property name="asm.jar" location="${main.lib}/asm-all-5.0.3.jar"/>
161
    <property name="asm.jar" location="${main.lib}/asm-all-5.0.3.jar"/>
173
    <property name="asm.url" value="${repository.m2}/maven2/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar"/>
162
    <property name="asm.url" value="${repository.m2}/maven2/org/ow2/asm/asm-all/5.0.3/asm-all-5.0.3.jar"/>
174
	
163
164
	<!-- for testing with older Xerces implementation -->
165
    <property name="xerces.jar" location="${main.lib}/xercesImpl-2.6.1.jar"/>
166
    <property name="xerces.url" value="${repository.m2}/maven2/xerces/xercesImpl/2.6.1//xercesImpl-2.6.1.jar"/>
167
175
    <!-- license checks -->
168
    <!-- license checks -->
176
    <property name="rat.jar" location="${main.lib}/apache-rat-0.11.jar"/>
169
    <property name="rat.jar" location="${main.lib}/apache-rat-0.10.jar"/>
177
    <property name="rat.url" value="${repository.m2}/maven2/org/apache/rat/apache-rat/0.11/apache-rat-0.11.jar"/>
170
    <property name="rat.url" value="${repository.m2}/maven2/org/apache/rat/apache-rat/0.10/apache-rat-0.10.jar"/>
178
171
179
    <!-- See http://www.ecma-international.org/publications/standards/Ecma-376.htm -->
172
    <!-- See http://www.ecma-international.org/publications/standards/Ecma-376.htm -->
180
    <!-- "Copy these file(s), free of charge" -->
173
    <!-- "Copy these file(s), free of charge" -->
181
    <property name="ooxml.xsds.ozip.1" value="OfficeOpenXML-Part4.zip"/>
174
    <property name="ooxml.xsds.ozip" location="${ooxml.lib}/OfficeOpenXML-Part4.zip"/>
182
    <property name="ooxml.xsds.izip.1" value="OfficeOpenXML-XMLSchema.zip"/>
175
    <property name="ooxml.xsds.izip" location="${ooxml.lib}/OfficeOpenXML-XMLSchema.zip"/>
183
    <property name="ooxml.xsds.url.1"
176
    <property name="ooxml.xsds.url"
184
              value="http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%204%20(PDF).zip"/>
177
              value="http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%204%20(PDF).zip"/>
185
    <property name="ooxml.xsds.src.dir" location="build/ooxml-xsds-src"/>
178
    <property name="ooxml.xsds.src.dir" location="build/ooxml-xsds-src"/>
186
    <property name="ooxml.xsds.src.jar" location="${ooxml.lib}/ooxml-schemas-src-1.1.jar"/>
179
    <property name="ooxml.xsds.src.jar" location="${ooxml.lib}/ooxml-schemas-src-1.1.jar"/>
187
    <property name="ooxml.xsds.jar" location="${ooxml.lib}/ooxml-schemas-1.1.jar"/>
180
    <property name="ooxml.xsds.jar" location="${ooxml.lib}/ooxml-schemas-1.1.jar"/>
188
181
189
	<!-- additional schemas are packed into the poi schemas jar, -->
182
    <property name="ooxml.encryption.src.dir" location="build/ooxml-encryption-src"/>
190
	<!-- so we don't have to care about a seperate versioning of the original ooxml schemas -->
183
    <property name="ooxml.encryption.src.jar" location="${ooxml.lib}/ooxml-encryption-src-1.1.jar"/>
191
	<property name="ooxml.xsds.dc.1" value="http://dublincore.org/schemas/xmls/qdc/2003/04/02/dc.xsd"/>
184
    <property name="ooxml.encryption.jar" location="${ooxml.lib}/ooxml-encryption-1.1.jar"/>
192
	<property name="ooxml.xsds.dc.2" value="http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcterms.xsd"/>
193
	<property name="ooxml.xsds.dc.3" value="http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcmitype.xsd"/>
194
	<property name="ooxml.xsds.dsig.1" value="http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd"/>
195
	<property name="ooxml.xsds.dsig.2" value="http://uri.etsi.org/01903/v1.3.2/XAdES.xsd"/>
196
	<property name="ooxml.xsds.dsig.3" value="http://uri.etsi.org/01903/v1.4.1/XAdESv141.xsd"/>
197
    <property name="ooxml.xsds.ozip.2" value="OfficeOpenXML-Part2.zip"/>
198
    <property name="ooxml.xsds.izip.2" value="OpenPackagingConventions-XMLSchema.zip"/>
199
    <property name="ooxml.xsds.url.2"
200
              value="http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%202%20(PDF).zip"/>
201
    <property name="ooxml.security.src.dir" location="build/ooxml-security-src"/>
202
    <property name="ooxml.security.src.jar" location="${ooxml.lib}/ooxml-security-src-1.0.jar"/>
203
    <property name="ooxml.security.jar" location="${ooxml.lib}/ooxml-security-1.0.jar"/>
204
    <property name="ooxml.security.xsd.dir" location="src/ooxml/resources/org/apache/poi/poifs/crypt"/>
205
185
206
    <property name="maven.ooxml.xsds.version.id" value="1.0"/>
186
    <property name="maven.ooxml.xsds.version.id" value="1.0"/>
207
    <property name="maven.ooxml.xsds.jar" value="ooxml-schemas-${maven.ooxml.xsds.version.id}.jar"/>
187
    <property name="maven.ooxml.xsds.jar" value="ooxml-schemas-${maven.ooxml.xsds.version.id}.jar"/>
Lines 242-263 under the License. Link Here
242
        <pathelement location="${main.output.dir}"/>
222
        <pathelement location="${main.output.dir}"/>
243
    </path>
223
    </path>
244
224
245
    <path id="ooxml.xmlsec.classpath">
246
        <pathelement location="${dsig.xmlsec.jar}"/>
247
        <pathelement location="${dsig.bouncycastle-prov.jar}"/>
248
        <pathelement location="${dsig.bouncycastle-pkix.jar}"/>
249
        <pathelement location="${dsig.sl4j-api.jar}"/>
250
    </path>
251
252
    <path id="ooxml.classpath">
225
    <path id="ooxml.classpath">
253
        <pathelement location="${ooxml.xmlbeans26.jar}"/>
226
        <pathelement location="${ooxml.xmlbeans26.jar}"/>
254
        <pathelement location="${ooxml.xsds.jar}"/>
227
        <pathelement location="${ooxml.xsds.jar}"/>
255
        <path refid="main.classpath"/>
228
        <path refid="main.classpath"/>
256
        <pathelement location="${main.output.dir}"/>
229
        <pathelement location="${main.output.dir}"/>
257
        <pathelement location="${scratchpad.output.dir}"/>
230
        <pathelement location="${scratchpad.output.dir}"/>
258
        <pathelement location="${ooxml.security.jar}"/>
231
        <pathelement location="${ooxml.encryption.jar}"/>
259
    	<!-- classes are omitted on test cases outside the xml-dsign area to avoid classpath poisioning -->
260
        <!--path refid="ooxml.xmlsec.classpath"/-->
261
    </path>
232
    </path>
262
233
263
    <path id="test.classpath">
234
    <path id="test.classpath">
Lines 360-367 under the License. Link Here
360
        <mkdir dir="${examples.output.dir}"/>
331
        <mkdir dir="${examples.output.dir}"/>
361
        <mkdir dir="${dist.dir}"/>
332
        <mkdir dir="${dist.dir}"/>
362
        <mkdir dir="${build.site}"/>
333
        <mkdir dir="${build.site}"/>
363
364
		<echo message="Using Java: ${java.version}/${java.runtime.version}/${java.vm.version}/${java.vm.name} from ${java.vm.vendor} on ${os.name}: ${os.version}" />		
365
    </target>
334
    </target>
366
335
367
    <target name="clean">
336
    <target name="clean">
Lines 389-400 under the License. Link Here
389
				<include name="log4j-1.2.13*"/>
358
				<include name="log4j-1.2.13*"/>
390
				<include name="org.jacoco.*-0.6.*"/>
359
				<include name="org.jacoco.*-0.6.*"/>
391
				<include name="dom4j*"/>
360
				<include name="dom4j*"/>
392
				<include name="apache-rat-0.10*"/>
393
				<include name="xercesImpl-*.jar"/> 
394
			</fileset>
361
			</fileset>
395
		</delete>
362
		</delete>
396
363
397
        <condition property="jars.present">
364
		<condition property="jars.present">
398
            <or>
365
            <or>
399
                <and>
366
                <and>
400
                    <available file="${main.commons-logging.jar}"/>
367
                    <available file="${main.commons-logging.jar}"/>
Lines 407-416 under the License. Link Here
407
                    <available file="${asm.jar}"/>
374
                    <available file="${asm.jar}"/>
408
                    <available file="${jacoco.zip}"/>
375
                    <available file="${jacoco.zip}"/>
409
                    <available file="${rat.jar}"/>
376
                    <available file="${rat.jar}"/>
410
                    <available file="${dsig.bouncycastle-prov.jar}"/>
377
                    <available file="${xerces.jar}"/>
411
                    <available file="${dsig.bouncycastle-pkix.jar}"/>
412
                    <available file="${dsig.xmlsec.jar}"/>
413
                    <available file="${dsig.sl4j-api.jar}"/>
414
                </and>
378
                </and>
415
                <isset property="disconnected"/>
379
                <isset property="disconnected"/>
416
            </or>
380
            </or>
Lines 462-485 under the License. Link Here
462
            </patternset>
426
            </patternset>
463
        </unzip>
427
        </unzip>
464
        <antcall target="downloadfile">
428
        <antcall target="downloadfile">
465
            <param name="sourcefile" value="${rat.url}"/>
429
            <param name="sourcefile" value="${xerces.url}"/>
466
            <param name="destfile" value="${rat.jar}"/>
430
            <param name="destfile" value="${xerces.jar}"/>
467
        </antcall>
468
        <antcall target="downloadfile">
469
            <param name="sourcefile" value="${dsig.bouncycastle-prov.url}"/>
470
            <param name="destfile" value="${dsig.bouncycastle-prov.jar}"/>
471
        </antcall>
472
        <antcall target="downloadfile">
473
            <param name="sourcefile" value="${dsig.bouncycastle-pkix.url}"/>
474
            <param name="destfile" value="${dsig.bouncycastle-pkix.jar}"/>
475
        </antcall>
476
        <antcall target="downloadfile">
477
            <param name="sourcefile" value="${dsig.xmlsec.url}"/>
478
            <param name="destfile" value="${dsig.xmlsec.jar}"/>
479
        </antcall>
431
        </antcall>
480
        <antcall target="downloadfile">
432
        <antcall target="downloadfile">
481
            <param name="sourcefile" value="${dsig.sl4j-api.url}"/>
433
            <param name="sourcefile" value="${rat.url}"/>
482
            <param name="destfile" value="${dsig.sl4j-api.jar}"/>
434
            <param name="destfile" value="${rat.jar}"/>
483
        </antcall>
435
        </antcall>
484
    </target>
436
    </target>
485
437
Lines 489-494 under the License. Link Here
489
                <and>
441
                <and>
490
                    <available file="${ooxml.xmlbeans23.jar}"/>
442
                    <available file="${ooxml.xmlbeans23.jar}"/>
491
                    <available file="${ooxml.xmlbeans26.jar}"/>
443
                    <available file="${ooxml.xmlbeans26.jar}"/>
444
                    <available file="${ooxml.xsds.jar}"/>
492
                </and>
445
                </and>
493
                <isset property="disconnected"/>
446
                <isset property="disconnected"/>
494
            </or>
447
            </or>
Lines 510-564 under the License. Link Here
510
        <condition property="ooxml-xsds.present">
463
        <condition property="ooxml-xsds.present">
511
            <or>
464
            <or>
512
                <and>
465
                <and>
513
                    <available file="${ooxml.lib}/${ooxml.xsds.izip.1}"/>
466
                    <available file="${ooxml.xsds.izip}"/>
514
                    <available file="${ooxml.lib}/${ooxml.xsds.izip.2}"/>
515
                </and>
467
                </and>
516
                <isset property="disconnected"/>
468
                <isset property="disconnected"/>
517
            </or>
469
            </or>
518
        </condition>
470
        </condition>
519
    </target>
471
    </target>
520
    <target name="fetch-ooxml-xsds" unless="ooxml-xsds.present"
472
    <target name="fetch-ooxml-xsds" unless="ooxml-xsds.present"
521
        depends="check-ooxml-xsds"
473
            depends="check-ooxml-xsds"
522
            description="Fetches needed OOXML xsd files from the Internet">
474
            description="Fetches needed OOXML xsd files from the Internet">
523
        <get dest="${ooxml.lib}" skipexisting="true">
475
        <get src="${ooxml.xsds.url}" dest="${ooxml.xsds.ozip}"/>
524
        	<url url="${ooxml.xsds.url.1}"/>
476
        <unzip src="${ooxml.xsds.ozip}" dest="${ooxml.lib}">
525
        	<url url="${ooxml.xsds.url.2}"/>
526
        	<url url="${ooxml.xsds.dc.1}"/>
527
        	<url url="${ooxml.xsds.dc.2}"/>
528
        	<url url="${ooxml.xsds.dc.3}"/>
529
        	<url url="${ooxml.xsds.dsig.1}"/>
530
        	<url url="${ooxml.xsds.dsig.2}"/>
531
        	<url url="${ooxml.xsds.dsig.3}"/>
532
        	<chainedmapper>
533
        		<flattenmapper/>
534
	        	<firstmatchmapper>
535
	        		<globmapper from="Office%20Open%20XML%201st%20edition%20Part%20*%20(PDF).zip" to="OfficeOpenXML-Part*.zip"/>
536
	        		<identitymapper/>
537
	    		</firstmatchmapper>
538
    		</chainedmapper>
539
    	</get>
540
        <unzip src="${ooxml.lib}/${ooxml.xsds.ozip.1}" dest="${ooxml.lib}">
541
        	<fileset dir="${ooxml.lib}" includes="OfficeOpenXML-Part*.zip"/>
542
            <patternset>
477
            <patternset>
543
                <include name="${ooxml.xsds.izip.1}"/>
478
                <include name="OfficeOpenXML-XMLSchema.zip"/>
544
            	<include name="${ooxml.xsds.izip.2}"/>
545
            </patternset>
479
            </patternset>
546
        </unzip>
480
        </unzip>
547
    </target>
481
    </target>
548
    <target name="check-compiled-ooxml-xsds" depends="fetch-ooxml-xsds">
482
    <target name="check-compiled-ooxml-xsds" depends="fetch-ooxml-xsds">
549
        <condition property="ooxml-compiled-xsds.present">
483
        <condition property="ooxml-compiled-xsds.present">
550
            <or>
484
            <or>
551
            	<and>
485
                <available file="${ooxml.xsds.jar}"/>
552
                    <available file="${ooxml.xsds.jar}"/>
486
                <isset property="disconnected"/>
553
                    <available file="${ooxml.security.jar}"/>
487
            </or>
554
            	</and>
488
        </condition>
489
        <condition property="ooxml-compiled-encryption-xsds.present">
490
            <or>
491
                <available file="${ooxml.encryption.jar}"/>
555
                <isset property="disconnected"/>
492
                <isset property="disconnected"/>
556
            </or>
493
            </or>
557
        </condition>
494
        </condition>
558
    </target>
495
    </target>
559
    <target name="compile-ooxml-xsds" unless="ooxml-compiled-xsds.present"
496
    <target name="compile-ooxml-xsds" unless="ooxml-compiled-xsds.present"
560
        depends="check-jars,fetch-jars,check-compiled-ooxml-xsds"
497
            depends="check-jars,fetch-jars,check-compiled-ooxml-xsds"
561
        description="Unpacks the OOXML xsd files, and compiles them into XmlBeans">
498
            description="Unpacks the OOXML xsd files, and compiles them into XmlBeans">
499
        <property name="ooxml.xsds.tmp.dir" location="build/ooxml-xsds"/>
500
        <mkdir dir="${ooxml.xsds.tmp.dir}"/>
501
562
        <taskdef name="xmlbean"
502
        <taskdef name="xmlbean"
563
                 classname="org.apache.xmlbeans.impl.tool.XMLBean"
503
                 classname="org.apache.xmlbeans.impl.tool.XMLBean"
564
                 classpath="${ooxml.xmlbeans23.jar}"/>
504
                 classpath="${ooxml.xmlbeans23.jar}"/>
Lines 570-578 under the License. Link Here
570
           <equals arg1="${sun.arch.data.model}" arg2="64" />
510
           <equals arg1="${sun.arch.data.model}" arg2="64" />
571
        </condition>
511
        </condition>
572
512
573
    	<property name="ooxml.xsds.tmp.dir" location="build/ooxml-xsds"/>
513
        <unzip src="${ooxml.xsds.izip}" dest="${ooxml.xsds.tmp.dir}"/>
574
        <mkdir dir="${ooxml.xsds.tmp.dir}"/>
514
        <!--
575
        <unzip src="${ooxml.lib}/${ooxml.xsds.izip.1}" dest="${ooxml.xsds.tmp.dir}"/>
515
              schema="build/ooxml-xsds/"
516
              schema="build/ooxml-xsds/sml-workbook.xsd"
517
          -->
576
        <xmlbean
518
        <xmlbean
577
                schema="${ooxml.xsds.tmp.dir}"
519
                schema="${ooxml.xsds.tmp.dir}"
578
                srcgendir="${ooxml.xsds.src.dir}"
520
                srcgendir="${ooxml.xsds.src.dir}"
Lines 586-628 under the License. Link Here
586
            <classpath refid="ooxml.classpath"/>
528
            <classpath refid="ooxml.classpath"/>
587
        </xmlbean>
529
        </xmlbean>
588
530
589
    	<!-- Now make a jar of the schema sources -->
531
        <!-- Now make a jar of the schema sources -->
590
    	<jar
532
        <jar
591
                basedir="${ooxml.xsds.src.dir}"
533
                basedir="${ooxml.xsds.src.dir}"
592
                destfile="${ooxml.xsds.src.jar}"
534
                destfile="${ooxml.xsds.src.jar}"
593
                />
535
                />
536
    </target>
537
538
    <target name="compile-ooxml-encryption-xsds" unless="ooxml-compiled-encryption-xsds.present"
539
            depends="check-jars,fetch-jars,check-compiled-ooxml-xsds"
540
            description="Compiles the OOXML encryption xsd files into XmlBeans">
541
        <taskdef name="xmlbean"
542
                 classname="org.apache.xmlbeans.impl.tool.XMLBean"
543
                 classpath="${ooxml.xmlbeans23.jar}"/>
544
545
        <!-- We need a fair amount of memory to compile the xml schema, -->
546
        <!--  but limit it in case it goes wrong! -->
547
        <!-- Pick the right amount based on 32 vs 64 bit jvm -->
548
        <condition property="ooxml.memory" value="768m" else="512m">
549
           <equals arg1="${sun.arch.data.model}" arg2="64" />
550
        </condition>
594
551
595
		<!-- Now do the same for the security schemas -->
596
    	<property name="ooxml.enc.xsds.tmp.dir" location="build/ooxml-security-xsds"/>
597
        <mkdir dir="${ooxml.enc.xsds.tmp.dir}"/>
598
        <unzip src="${ooxml.lib}/${ooxml.xsds.izip.2}" dest="${ooxml.enc.xsds.tmp.dir}"/>
599
    	
600
    	<copy todir="${ooxml.enc.xsds.tmp.dir}">
601
    		<fileset dir="${ooxml.lib}" includes="dc*.xsd,xmldsig*.xsd,XAdES*.xsd"/>
602
    		<fileset dir="${ooxml.security.xsd.dir}"/>
603
    	</copy>
604
605
    	<!-- noupa/nopvr is set because of the dublincore schemas -->
606
    	<!-- https://issues.apache.org/jira/browse/XMLBEANS-340 -->
607
    	<!-- javasource > 1.5 will not generate all array accessor -->
608
        <xmlbean
552
        <xmlbean
609
                schema="${ooxml.enc.xsds.tmp.dir}"
553
                schema="${ooxml.encryption.xsd.dir}"
610
                srcgendir="${ooxml.security.src.dir}"
554
                srcgendir="${ooxml.encryption.src.dir}"
611
                optimize="yes"
555
                optimize="yes"
612
                destfile="${ooxml.security.jar}"
556
                destfile="${ooxml.encryption.jar}"
613
                javasource="1.5" 
557
                javasource="1.5"
614
                failonerror="true"
558
                failonerror="true"
615
                fork="true"
559
                fork="true"
616
                memoryMaximumSize="${ooxml.memory}"
560
                memoryMaximumSize="${ooxml.memory}"
617
	    		noupa="true"
618
	    		nopvr="true"
619
                >
561
                >
620
            <classpath refid="ooxml.classpath"/>
562
            <classpath refid="ooxml.classpath"/>
621
        </xmlbean>
563
        </xmlbean>
622
564
565
        <!-- Now make a jar of the schema sources -->
623
        <jar
566
        <jar
624
                basedir="${ooxml.security.src.dir}"
567
                basedir="${ooxml.encryption.src.dir}"
625
                destfile="${ooxml.security.src.jar}"
568
                destfile="${ooxml.encryption.src.jar}"
626
                />
569
                />
627
    </target>
570
    </target>
628
571
Lines 712-718 under the License. Link Here
712
        </copy>
655
        </copy>
713
    </target>
656
    </target>
714
657
715
    <target name="compile-ooxml" depends="compile-main,compile-scratchpad,compile-ooxml-xsds">
658
    <target name="compile-ooxml" depends="compile-main,compile-scratchpad,compile-ooxml-xsds,compile-ooxml-encryption-xsds">
716
        <javac target="${jdk.version.class}"
659
        <javac target="${jdk.version.class}"
717
               source="${jdk.version.source}"
660
               source="${jdk.version.source}"
718
               destdir="${ooxml.output.dir}"
661
               destdir="${ooxml.output.dir}"
Lines 721-730 under the License. Link Here
721
               encoding="${java.source.encoding}"
664
               encoding="${java.source.encoding}"
722
               fork="yes"
665
               fork="yes"
723
               includeantruntime="false">
666
               includeantruntime="false">
724
            <classpath>
667
            <classpath refid="ooxml.classpath"/>
725
            	<path refid="ooxml.classpath"/>
726
            	<path refid="ooxml.xmlsec.classpath"/>
727
        	</classpath>
728
        </javac>
668
        </javac>
729
        <javac target="${jdk.version.class}"
669
        <javac target="${jdk.version.class}"
730
               source="${jdk.version.source}"
670
               source="${jdk.version.source}"
Lines 736-743 under the License. Link Here
736
               includeantruntime="false">
676
               includeantruntime="false">
737
            <classpath>
677
            <classpath>
738
                <path refid="ooxml.classpath"/>
678
                <path refid="ooxml.classpath"/>
739
            	<path refid="ooxml.xmlsec.classpath"/>
740
            	<path refid="test.ooxml.classpath"/>
741
                <pathelement path="${ooxml.output.dir}"/>
679
                <pathelement path="${ooxml.output.dir}"/>
742
                <pathelement path="${main.output.test.dir}"/>
680
                <pathelement path="${main.output.test.dir}"/>
743
            </classpath>
681
            </classpath>
Lines 894-900 under the License. Link Here
894
                <jvmarg value="${poi.test.locale}"/>
832
                <jvmarg value="${poi.test.locale}"/>
895
                <jvmarg value="-ea"/>
833
                <jvmarg value="-ea"/>
896
                <jvmarg value="-Xmx256m"/>
834
                <jvmarg value="-Xmx256m"/>
897
            	<jvmarg value="-Dadditionaljar=${additionaljar}"/>
898
                <formatter type="plain"/>
835
                <formatter type="plain"/>
899
                <formatter type="xml"/>
836
                <formatter type="xml"/>
900
                <batchtest todir="${main.reports.test}">
837
                <batchtest todir="${main.reports.test}">
Lines 936-942 under the License. Link Here
936
                <syspropertyset refid="junit.properties"/>
873
                <syspropertyset refid="junit.properties"/>
937
                <jvmarg value="${poi.test.locale}"/>
874
                <jvmarg value="${poi.test.locale}"/>
938
                <jvmarg value="-ea"/>
875
                <jvmarg value="-ea"/>
939
            	<jvmarg value="-Dadditionaljar=${additionaljar}"/>
940
                <!-- 
876
                <!-- 
941
                  YK: ensure that JUnit has enough memory to run tests. 
877
                  YK: ensure that JUnit has enough memory to run tests. 
942
                  Without the line below tests fail on Mac OS X with jdk-1.6.26 
878
                  Without the line below tests fail on Mac OS X with jdk-1.6.26 
Lines 979-985 under the License. Link Here
979
                  <syspropertyset refid="junit.properties"/>
915
                  <syspropertyset refid="junit.properties"/>
980
                  <jvmarg value="${poi.test.locale}"/>
916
                  <jvmarg value="${poi.test.locale}"/>
981
                  <jvmarg value="-ea"/>
917
                  <jvmarg value="-ea"/>
982
                  <jvmarg value="-Dadditionaljar=${additionaljar}"/>
983
                  <formatter type="plain"/>
918
                  <formatter type="plain"/>
984
                  <formatter type="xml"/>
919
                  <formatter type="xml"/>
985
                  <batchtest todir="${ooxml.reports.test}">
920
                  <batchtest todir="${ooxml.reports.test}">
Lines 987-1013 under the License. Link Here
987
                          <include name="**/${testpattern}.java"/>
922
                          <include name="**/${testpattern}.java"/>
988
                          <exclude name="**/TestUnfixedBugs.java"/>
923
                          <exclude name="**/TestUnfixedBugs.java"/>
989
                          <exclude name="**/All*Tests.java"/>
924
                          <exclude name="**/All*Tests.java"/>
990
                      	  <exclude name="**/TestSignatureInfo.java"/>
991
                      </fileset>
992
                  </batchtest>
993
              </junit>
994
            </jacoco:coverage>
995
            <jacoco:coverage enabled="${coverage.enabled}" excludes="${coverage.excludes}" destfile="build/jacoco-@{type}-xmlsec.exec">
996
              <junit printsummary="yes" fork="yes" forkmode="once" haltonfailure="${halt.on.test.failure}"
997
                     failureproperty="ooxml.xmlsec.test.failed">
998
                  <classpath>
999
                  	<path refid="@{classpath}"/>
1000
                  	<path refid="ooxml.xmlsec.classpath"/>
1001
                  </classpath>
1002
                  <syspropertyset refid="junit.properties"/>
1003
                  <jvmarg value="${poi.test.locale}"/>
1004
                  <jvmarg value="-ea"/>
1005
                  <jvmarg value="-Dadditionaljar=${additionaljar}"/>
1006
                  <formatter type="plain"/>
1007
                  <formatter type="xml"/>
1008
                  <batchtest todir="${ooxml.reports.test}">
1009
                      <fileset dir="${ooxml.src.test}">
1010
                      	  <include name="**/TestSignatureInfo.java"/>
1011
                      </fileset>
925
                      </fileset>
1012
                  </batchtest>
926
                  </batchtest>
1013
              </junit>
927
              </junit>
Lines 1031-1037 under the License. Link Here
1031
945
1032
    	<jar destfile="${ooxml.lite-merged.dir}/ooxml-lite-merged.jar">
946
    	<jar destfile="${ooxml.lite-merged.dir}/ooxml-lite-merged.jar">
1033
    		<zipfileset includes="**/*" src="${ooxml.xsds.jar}"/>
947
    		<zipfileset includes="**/*" src="${ooxml.xsds.jar}"/>
1034
        	<zipfileset includes="**/*" src="${ooxml.security.jar}"/>
948
        	<zipfileset includes="**/*" src="${ooxml.encryption.jar}"/>
1035
        </jar>
949
        </jar>
1036
    	
950
    	
1037
        <java classname="org.apache.poi.util.OOXMLLite" fork="yes">
951
        <java classname="org.apache.poi.util.OOXMLLite" fork="yes">
Lines 1039-1048 under the License. Link Here
1039
        		<pathelement path="${ooxml.lite-merged.dir}/ooxml-lite-merged.jar"/>
953
        		<pathelement path="${ooxml.lite-merged.dir}/ooxml-lite-merged.jar"/>
1040
    		</classpath>
954
    		</classpath>
1041
            <classpath refid="test.ooxml.classpath"/>
955
            <classpath refid="test.ooxml.classpath"/>
1042
        	<classpath refid="ooxml.xmlsec.classpath"/>
1043
            <syspropertyset refid="junit.properties"/>
956
            <syspropertyset refid="junit.properties"/>
1044
            <jvmarg value="${poi.test.locale}"/>
957
            <jvmarg value="${poi.test.locale}"/>
1045
            <jvmarg value="-Dadditionaljar=${additionaljar}"/>
1046
            <arg value="-ooxml"/>
958
            <arg value="-ooxml"/>
1047
            <arg value="${ooxml.lite-merged.dir}/ooxml-lite-merged.jar"/>
959
            <arg value="${ooxml.lite-merged.dir}/ooxml-lite-merged.jar"/>
1048
            <arg value="-test"/>
960
            <arg value="-test"/>
Lines 1078-1084 under the License. Link Here
1078
                <syspropertyset refid="junit.properties"/>
990
                <syspropertyset refid="junit.properties"/>
1079
                <jvmarg value="${poi.test.locale}"/>
991
                <jvmarg value="${poi.test.locale}"/>
1080
                <jvmarg value="-ea"/>
992
                <jvmarg value="-ea"/>
1081
                <jvmarg value="-Dadditionaljar=${additionaljar}"/>
1082
                <formatter type="plain"/>
993
                <formatter type="plain"/>
1083
                <formatter type="xml"/>
994
                <formatter type="xml"/>
1084
                <batchtest todir="${excelant.reports.test}">
995
                <batchtest todir="${excelant.reports.test}">
Lines 1155-1161 under the License. Link Here
1155
                <path refid="main.classpath"/>
1066
                <path refid="main.classpath"/>
1156
                <path refid="scratchpad.classpath"/>
1067
                <path refid="scratchpad.classpath"/>
1157
                <path refid="ooxml.classpath"/>
1068
                <path refid="ooxml.classpath"/>
1158
            	<path refid="ooxml.xmlsec.classpath"/>
1159
                <path path="${env.CLASSPATH}"/>
1069
                <path path="${env.CLASSPATH}"/>
1160
            </classpath>
1070
            </classpath>
1161
1071
Lines 1444-1450 under the License. Link Here
1444
1354
1445
    <target name="gump" depends="compile-all, test-all, jar"/>
1355
    <target name="gump" depends="compile-all, test-all, jar"/>
1446
    <target name="jenkins" depends="compile-all, test-all, jar, javadocs, assemble, findbugs, release-notes, rat-check"/>
1356
    <target name="jenkins" depends="compile-all, test-all, jar, javadocs, assemble, findbugs, release-notes, rat-check"/>
1447
1357
	
1448
    <available property="maven.ant.tasks.present" classname="org.apache.maven.artifact.ant.Pom"/>
1358
    <available property="maven.ant.tasks.present" classname="org.apache.maven.artifact.ant.Pom"/>
1449
    <target name="maven.ant.tasks-check">
1359
    <target name="maven.ant.tasks-check">
1450
      <fail unless="maven.ant.tasks.present">
1360
      <fail unless="maven.ant.tasks.present">
Lines 1488-1494 under the License. Link Here
1488
1398
1489
       <typedef resource="org/apache/rat/anttasks/antlib.xml"
1399
       <typedef resource="org/apache/rat/anttasks/antlib.xml"
1490
             uri="antlib:org.apache.rat.anttasks"
1400
             uri="antlib:org.apache.rat.anttasks"
1491
             classpath="${rat.jar}" />
1401
             classpath="${main.lib}/apache-rat-0.10.jar" />
1492
       <rat:report xmlns:rat="antlib:org.apache.rat.anttasks" reportFile="${rat.report}">
1402
       <rat:report xmlns:rat="antlib:org.apache.rat.anttasks" reportFile="${rat.report}">
1493
           <fileset dir="src/">
1403
           <fileset dir="src/">
1494
              <exclude name="documentation/*.txt" />
1404
              <exclude name="documentation/*.txt" />
Lines 1497-1503 under the License. Link Here
1497
              <exclude name="scratchpad/testcases/dummy.txt" />
1407
              <exclude name="scratchpad/testcases/dummy.txt" />
1498
              <exclude name="contrib/testcases/dummy.txt" />
1408
              <exclude name="contrib/testcases/dummy.txt" />
1499
              <exclude name="examples/lib/dummy.txt" />
1409
              <exclude name="examples/lib/dummy.txt" />
1500
              <exclude name="resources/ooxml/org/apache/poi/xslf/usermodel/notesMaster.xml" />
1501
              <exclude name="resources/ooxml/org/apache/poi/xslf/usermodel/presetShapeDefinitions.xml" />
1410
              <exclude name="resources/ooxml/org/apache/poi/xslf/usermodel/presetShapeDefinitions.xml" />
1502
              <exclude name="examples/src/org/apache/poi/xslf/usermodel/pie-chart-data.txt" />
1411
              <exclude name="examples/src/org/apache/poi/xslf/usermodel/pie-chart-data.txt" />
1503
           </fileset>
1412
           </fileset>
Lines 1541-1547 under the License. Link Here
1541
				<exclude name="poi-*${version.id}-sources-*.jar"/>
1450
				<exclude name="poi-*${version.id}-sources-*.jar"/>
1542
			</fileset>
1451
			</fileset>
1543
			<auxClasspath path="ooxml-lib/ooxml-schemas-1.1.jar" />
1452
			<auxClasspath path="ooxml-lib/ooxml-schemas-1.1.jar" />
1544
			<auxClasspath path="ooxml-lib/ooxml-security-1.0.jar" />
1453
			<auxClasspath path="ooxml-lib/ooxml-encryption-1.1.jar" />
1545
			<auxClasspath path="ooxml-lib/xmlbeans-2.6.0.jar" />
1454
			<auxClasspath path="ooxml-lib/xmlbeans-2.6.0.jar" />
1546
			<auxClasspath path="lib/commons-codec-1.9.jar" />
1455
			<auxClasspath path="lib/commons-codec-1.9.jar" />
1547
			<auxClasspath path="lib/commons-logging-1.1.3.jar" />
1456
			<auxClasspath path="lib/commons-logging-1.1.3.jar" />
(-)a/maven/ooxml-security.pom (-79 lines)
Lines 1-79 Link Here
1
<?xml version="1.0"?>
2
<!--
3
4
   Licensed to the Apache Software Foundation (ASF) under one or more
5
   contributor license agreements.  See the NOTICE file distributed with
6
   this work for additional information regarding copyright ownership.
7
   The ASF licenses this file to You under the Apache License, Version 2.0
8
   (the "License"); you may not use this file except in compliance with
9
   the License.  You may obtain a copy of the License at
10
11
       http://www.apache.org/licenses/LICENSE-2.0
12
13
   Unless required by applicable law or agreed to in writing, software
14
   distributed under the License is distributed on an "AS IS" BASIS,
15
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
   See the License for the specific language governing permissions and
17
   limitations under the License.
18
19
-->
20
21
<project xmlns="http://maven.apache.org/POM/4.0.0"
22
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
23
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
24
25
  <modelVersion>4.0.0</modelVersion>
26
  <groupId>org.apache.poi</groupId>
27
  <artifactId>ooxml-security</artifactId>
28
  <version>@VERSION@</version>
29
  <packaging>jar</packaging>
30
  <name>OOXML security</name>
31
  <description>
32
    XmlBeans generated from various supplied xsds for encryption and signing:
33
    http://msdn.microsoft.com/en-us/library/dd925810(v=office.12).aspx
34
    http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%202%20(PDF).zip 
35
    http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd
36
    http://uri.etsi.org/01903/v1.3.2/XAdES.xsd
37
    http://uri.etsi.org/01903/v1.4.1/XAdESv141.xsd
38
    http://dublincore.org/schemas/xmls/qdc/2003/04/02/dc.xsd
39
    http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcterms.xsd
40
    http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcmitype.xsd
41
  </description>
42
  <url>http://poi.apache.org/</url>
43
44
  <mailingLists>
45
    <mailingList>
46
      <name>POI Users List</name>
47
      <subscribe>user-subscribe@poi.apache.org</subscribe>
48
      <unsubscribe>user-unsubscribe@poi.apache.org</unsubscribe>
49
      <archive>http://mail-archives.apache.org/mod_mbox/poi-user/</archive>
50
    </mailingList>
51
    <mailingList>
52
      <name>POI Developer List</name>
53
      <subscribe>dev-subscribe@poi.apache.org</subscribe>
54
      <unsubscribe>dev-unsubscribe@poi.apache.org</unsubscribe>
55
      <archive>http://mail-archives.apache.org/mod_mbox/poi-dev/</archive>
56
    </mailingList>
57
  </mailingLists>
58
59
  <licenses>
60
    <license>
61
      <name>The Apache Software License, Version 2.0</name>
62
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
63
      <distribution>repo</distribution>
64
    </license>
65
  </licenses>
66
67
  <organization>
68
    <name>Apache Software Foundation</name>
69
    <url>http://www.apache.org/</url>
70
  </organization>
71
72
  <dependencies>
73
    <dependency>
74
      <groupId>org.apache.xmlbeans</groupId>
75
      <artifactId>xmlbeans</artifactId>
76
      <version>2.3.0</version>
77
    </dependency>
78
  </dependencies>
79
</project>
(-)a/patch.xml (-75 / +75 lines)
Lines 1-75 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
2
<!--
3
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   Licensed to the Apache Software Foundation (ASF) under one or more
4
   contributor license agreements.  See the NOTICE file distributed with
4
   contributor license agreements.  See the NOTICE file distributed with
5
   this work for additional information regarding copyright ownership.
5
   this work for additional information regarding copyright ownership.
6
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   The ASF licenses this file to You under the Apache License, Version 2.0
7
   (the "License"); you may not use this file except in compliance with
7
   (the "License"); you may not use this file except in compliance with
8
   the License.  You may obtain a copy of the License at
8
   the License.  You may obtain a copy of the License at
9
9
10
       http://www.apache.org/licenses/LICENSE-2.0
10
       http://www.apache.org/licenses/LICENSE-2.0
11
11
12
   Unless required by applicable law or agreed to in writing, software
12
   Unless required by applicable law or agreed to in writing, software
13
   distributed under the License is distributed on an "AS IS" BASIS,
13
   distributed under the License is distributed on an "AS IS" BASIS,
14
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
   See the License for the specific language governing permissions and
15
   See the License for the specific language governing permissions and
16
   limitations under the License.
16
   limitations under the License.
17
-->
17
-->
18
<!--
18
<!--
19
  =======================================================================
19
  =======================================================================
20
   Use Apache Ant to generate a patch file.
20
   Use Apache Ant to generate a patch file.
21
  =======================================================================
21
  =======================================================================
22
-->
22
-->
23
<project name="create-patch" default="patchpackage" basedir=".">
23
<project name="create-patch" default="patchpackage" basedir=".">
24
    <property environment="env"/>
24
    <property environment="env"/>
25
    <property name="patch.package" value="patch.tar.gz"/>
25
    <property name="patch.package" value="patch.tar.gz"/>
26
    <property name="patch.file" value="patch.txt"/>
26
    <property name="patch.file" value="patch.txt"/>
27
27
28
    <condition property="svn.found">
28
    <condition property="svn.found">
29
        <or>
29
        <or>
30
            <available file="svn" filepath="${env.PATH}"/>
30
            <available file="svn" filepath="${env.PATH}"/>
31
            <available file="svn.exe" filepath="${env.PATH}"/>
31
            <available file="svn.exe" filepath="${env.PATH}"/>
32
            <available file="svn.exe" filepath="${env.Path}"/>
32
            <available file="svn.exe" filepath="${env.Path}"/>
33
        </or>
33
        </or>
34
    </condition>
34
    </condition>
35
35
36
    <target name="createpatch">
36
    <target name="createpatch">
37
        <fail unless="svn.found" message="You need a version of svn to create the patch"/>
37
        <fail unless="svn.found" message="You need a version of svn to create the patch"/>
38
        <exec executable="svn" output="${patch.file}">
38
        <exec executable="svn" output="${patch.file}">
39
            <arg value="diff"/>
39
            <arg value="diff"/>
40
        </exec>
40
        </exec>
41
    </target>
41
    </target>
42
42
43
    <target name="newfiles">
43
    <target name="newfiles">
44
        <exec executable="svn" output="${patch.file}.tmp">
44
        <exec executable="svn" output="${patch.file}.tmp">
45
            <arg value="status"/>
45
            <arg value="status"/>
46
        </exec>
46
        </exec>
47
47
48
       <!-- prepare the list of files to include in patch.tar.gz --> 
48
       <!-- prepare the list of files to include in patch.tar.gz --> 
49
       <loadfile srcfile="${patch.file}.tmp" property="tar.file.list">  
49
       <loadfile srcfile="${patch.file}.tmp" property="tar.file.list">  
50
         <filterchain>  
50
         <filterchain>  
51
            <!-- capture any new files -->
51
            <!-- capture any new files -->
52
            <linecontainsregexp>
52
            <linecontainsregexp>
53
                <regexp pattern="^(\?|A)......"/>
53
                <regexp pattern="^(\?|A)......"/>
54
            </linecontainsregexp>
54
            </linecontainsregexp>
55
            <!-- filter out the first six characters -->
55
            <!-- filter out the first six characters -->
56
            <tokenfilter>
56
            <tokenfilter>
57
              <replaceregex pattern="^(.......)" replace=""/>
57
              <replaceregex pattern="^(.......)" replace=""/>
58
            </tokenfilter>
58
            </tokenfilter>
59
            <!--remove line breaks -->
59
            <!--remove line breaks -->
60
            <striplinebreaks/>
60
            <striplinebreaks/>
61
          </filterchain> 
61
          </filterchain> 
62
       </loadfile>  
62
       </loadfile>  
63
    </target>
63
    </target>
64
64
65
    <target name="patchpackage" depends="createpatch,newfiles">
65
    <target name="patchpackage" depends="createpatch,newfiles">
66
       <delete file="${patch.package}"/> 
66
       <delete file="${patch.package}"/> 
67
       <tar includes="${tar.file.list}"
67
       <tar includes="${tar.file.list}"
68
            destfile="${patch.package}"   
68
            destfile="${patch.package}"   
69
            basedir="." 
69
            basedir="." 
70
            compression="gzip" >          
70
            compression="gzip" >          
71
       </tar>  
71
       </tar>  
72
       <delete file="${patch.file}.tmp"/>
72
       <delete file="${patch.file}.tmp"/>
73
    </target>
73
    </target>
74
74
75
</project>
75
</project>
(-)a/sonar/ooxml-schema-encryption/pom.xml (-1 / +1 lines)
Lines 101-107 Link Here
101
		<dependency>
101
		<dependency>
102
		  <groupId>org.apache.xmlbeans</groupId>
102
		  <groupId>org.apache.xmlbeans</groupId>
103
		  <artifactId>xmlbeans</artifactId>
103
		  <artifactId>xmlbeans</artifactId>
104
		  <version>2.6.0</version>
104
		  <version>2.3.0</version>
105
		</dependency>
105
		</dependency>
106
    </dependencies>
106
    </dependencies>
107
</project>
107
</project>
(-)a/sonar/ooxml-schema/pom.xml (-1 / +1 lines)
Lines 98-104 Link Here
98
		<dependency>
98
		<dependency>
99
		  <groupId>org.apache.xmlbeans</groupId>
99
		  <groupId>org.apache.xmlbeans</groupId>
100
		  <artifactId>xmlbeans</artifactId>
100
		  <artifactId>xmlbeans</artifactId>
101
		  <version>2.6.0</version>
101
		  <version>2.3.0</version>
102
		</dependency>
102
		</dependency>
103
    </dependencies>
103
    </dependencies>
104
</project>
104
</project>
(-)a/sonar/ooxml/pom.xml (-2 / +2 lines)
Lines 113-120 Link Here
113
		<dependency>
113
		<dependency>
114
		  <groupId>org.apache.xmlbeans</groupId>
114
		  <groupId>org.apache.xmlbeans</groupId>
115
		  <artifactId>xmlbeans</artifactId>
115
		  <artifactId>xmlbeans</artifactId>
116
		  <version>2.6.0</version>
116
		  <version>2.3.0</version>
117
		</dependency>
117
		</dependency>        
118
		
118
		
119
		<!-- non-test dependency for OOXMLLite -->
119
		<!-- non-test dependency for OOXMLLite -->
120
        <dependency>
120
        <dependency>
(-)a/src/examples/src/org/apache/poi/hwpf/Word2Forrest.java (-15 / +6 lines)
Lines 17-42 Link Here
17
17
18
package org.apache.poi.hwpf;
18
package org.apache.poi.hwpf;
19
19
20
import java.io.FileInputStream;
20
import org.apache.poi.hwpf.HWPFDocument;
21
import java.io.FileOutputStream;
21
import org.apache.poi.hwpf.usermodel.*;
22
import java.io.IOException;
22
import org.apache.poi.hwpf.model.*;
23
import java.io.OutputStream;
23
24
import java.io.OutputStreamWriter;
24
import java.io.*;
25
import java.io.UnsupportedEncodingException;
26
import java.io.Writer;
27
28
import org.apache.poi.hwpf.model.StyleDescription;
29
import org.apache.poi.hwpf.model.StyleSheet;
30
import org.apache.poi.hwpf.usermodel.CharacterRun;
31
import org.apache.poi.hwpf.usermodel.Paragraph;
32
import org.apache.poi.hwpf.usermodel.Range;
33
25
34
public final class Word2Forrest
26
public final class Word2Forrest
35
{
27
{
36
  Writer _out;
28
  Writer _out;
37
  HWPFDocument _doc;
29
  HWPFDocument _doc;
38
30
39
  @SuppressWarnings("unused")
40
  public Word2Forrest(HWPFDocument doc, OutputStream stream)
31
  public Word2Forrest(HWPFDocument doc, OutputStream stream)
41
    throws IOException, UnsupportedEncodingException
32
    throws IOException, UnsupportedEncodingException
42
  {
33
  {
Lines 225-231 public final class Word2Forrest Link Here
225
      new Word2Forrest(new HWPFDocument(new FileInputStream(args[0])), out);
216
      new Word2Forrest(new HWPFDocument(new FileInputStream(args[0])), out);
226
      out.close();
217
      out.close();
227
    }
218
    }
228
    catch (Exception t)
219
    catch (Throwable t)
229
    {
220
    {
230
      t.printStackTrace();
221
      t.printStackTrace();
231
    }
222
    }
(-)a/src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java (-2 / +1 lines)
Lines 41-47 import org.apache.poi.poifs.eventfilesystem.POIFSReader; Link Here
41
 * @author Rainer Klute <a
41
 * @author Rainer Klute <a
42
 * href="mailto:klute@rainer-klute.de">&lt;klute@rainer-klute.de&gt;</a>
42
 * href="mailto:klute@rainer-klute.de">&lt;klute@rainer-klute.de&gt;</a>
43
 */
43
 */
44
@SuppressWarnings("serial")
45
public class POIBrowser extends JFrame
44
public class POIBrowser extends JFrame
46
{
45
{
47
46
Lines 100-106 public class POIBrowser extends JFrame Link Here
100
            {
99
            {
101
                System.err.println(filename + ": " + ex);
100
                System.err.println(filename + ": " + ex);
102
            }
101
            }
103
            catch (Exception t)
102
            catch (Throwable t)
104
            {
103
            {
105
                System.err.println("Unexpected exception while reading \"" +
104
                System.err.println("Unexpected exception while reading \"" +
106
                                   filename + "\":");
105
                                   filename + "\":");
(-)a/src/examples/src/org/apache/poi/poifs/poibrowser/TreeReaderListener.java (-3 / +3 lines)
Lines 70-76 public class TreeReaderListener implements POIFSReaderListener Link Here
70
     * <p>Maps filenames and POI document paths to their associated
70
     * <p>Maps filenames and POI document paths to their associated
71
     * tree nodes.</p>
71
     * tree nodes.</p>
72
     */
72
     */
73
    protected Map<Object,MutableTreeNode> pathToNode;
73
    protected Map pathToNode;
74
74
75
    /**
75
    /**
76
     * <p>The name of the file this {@link TreeReaderListener}
76
     * <p>The name of the file this {@link TreeReaderListener}
Lines 99-105 public class TreeReaderListener implements POIFSReaderListener Link Here
99
    {
99
    {
100
        this.filename = filename;
100
        this.filename = filename;
101
        this.rootNode = rootNode;
101
        this.rootNode = rootNode;
102
        pathToNode = new HashMap<Object,MutableTreeNode>(15); // Should be a reasonable guess.
102
        pathToNode = new HashMap(15); // Should be a reasonable guess.
103
    }
103
    }
104
104
105
105
Lines 146-152 public class TreeReaderListener implements POIFSReaderListener Link Here
146
            d = new DocumentDescriptor(event.getName(), event.getPath(),
146
            d = new DocumentDescriptor(event.getName(), event.getPath(),
147
                                       is, nrOfBytes);
147
                                       is, nrOfBytes);
148
        }
148
        }
149
        catch (Exception t)
149
        catch (Throwable t)
150
        {
150
        {
151
            System.err.println
151
            System.err.println
152
                ("Unexpected exception while processing " +
152
                ("Unexpected exception while processing " +
(-)a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntTask.java (-1 / +1 lines)
Lines 175-181 public class ExcelAntTask extends Task { Link Here
175
        try {
175
        try {
176
            Class.forName("org.apache.poi.hssf.usermodel.HSSFWorkbook");
176
            Class.forName("org.apache.poi.hssf.usermodel.HSSFWorkbook");
177
            Class.forName("org.apache.poi.ss.usermodel.WorkbookFactory");
177
            Class.forName("org.apache.poi.ss.usermodel.WorkbookFactory");
178
        } catch (Exception e) {
178
        } catch (Throwable e) {
179
            throw new BuildException(
179
            throw new BuildException(
180
                    "The <classpath> for <excelant> must include poi.jar and poi-ooxml.jar " +
180
                    "The <classpath> for <excelant> must include poi.jar and poi-ooxml.jar " +
181
                    "if not in Ant's own classpath. Processing .xlsx spreadsheets requires " +
181
                    "if not in Ant's own classpath. Processing .xlsx spreadsheets requires " +
(-)a/src/java/org/apache/poi/hpsf/CustomProperty.java (-4 lines)
Lines 120-127 public class CustomProperty extends MutableProperty Link Here
120
        return (int) this.getID();
120
        return (int) this.getID();
121
    }
121
    }
122
122
123
    @Override
124
    public boolean equals(Object o) {
125
        return (o instanceof CustomProperty) ? equalsContents(o) : false;
126
    }
127
}
123
}
(-)a/src/java/org/apache/poi/hssf/model/WorkbookRecordList.java (-14 / +2 lines)
Lines 72-92 public final class WorkbookRecordList implements Iterable<Record> { Link Here
72
		return records.iterator();
72
		return records.iterator();
73
	}
73
	}
74
74
75
	/**
76
	 * Find the given record in the record list by identity and removes it
77
	 *
78
	 * @param record the identical record to be searched for
79
	 */
80
	public void remove( Object record ) {
75
	public void remove( Object record ) {
81
	   // can't use List.indexOf here because it checks the records for equality and not identity
76
	   int i = records.indexOf(record);
82
	   int i = 0;
77
	   this.remove(i);
83
	   for (Record r : records) {
84
	       if (r == record) {
85
	           remove(i);
86
	           break;
87
	       }
88
	       i++;
89
	   }
90
	}
78
	}
91
79
92
	public void remove( int pos )
80
	public void remove( int pos )
(-)a/src/java/org/apache/poi/hssf/record/FontRecord.java (-9 / +1 lines)
Lines 475-489 public final class FontRecord extends StandardRecord { Link Here
475
		field_7_family              == other.field_7_family &&
475
		field_7_family              == other.field_7_family &&
476
		field_8_charset             == other.field_8_charset &&
476
		field_8_charset             == other.field_8_charset &&
477
		field_9_zero                == other.field_9_zero &&
477
		field_9_zero                == other.field_9_zero &&
478
        stringEquals(this.field_11_font_name, other.field_11_font_name)
478
		field_11_font_name.equals(other.field_11_font_name)
479
		;
479
		;
480
	}
480
	}
481
482
    public boolean equals(Object o) {
483
        return (o instanceof FontRecord) ? sameProperties((FontRecord)o) : false;
484
    }
485
    
486
    private static boolean stringEquals(String s1, String s2) {
487
        return (s1 == s2 || (s1 != null && s1.equals(s2)));
488
    }
489
}
481
}
(-)a/src/java/org/apache/poi/hssf/record/FormulaRecord.java (-8 / +5 lines)
Lines 17-26 Link Here
17
17
18
package org.apache.poi.hssf.record;
18
package org.apache.poi.hssf.record;
19
19
20
import org.apache.poi.ss.formula.ptg.Ptg;
21
import org.apache.poi.ss.formula.eval.ErrorEval;
20
import org.apache.poi.hssf.usermodel.HSSFCell;
22
import org.apache.poi.hssf.usermodel.HSSFCell;
21
import org.apache.poi.ss.formula.Formula;
23
import org.apache.poi.ss.formula.Formula;
22
import org.apache.poi.ss.formula.eval.ErrorEval;
23
import org.apache.poi.ss.formula.ptg.Ptg;
24
import org.apache.poi.util.BitField;
24
import org.apache.poi.util.BitField;
25
import org.apache.poi.util.BitFieldFactory;
25
import org.apache.poi.util.BitFieldFactory;
26
import org.apache.poi.util.HexDump;
26
import org.apache.poi.util.HexDump;
Lines 136-143 public final class FormulaRecord extends CellRecord { Link Here
136
			};
136
			};
137
			return new SpecialCachedValue(vd);
137
			return new SpecialCachedValue(vd);
138
		}
138
		}
139
		@Override
139
		public String toString() {
140
        public String toString() {
141
			StringBuffer sb = new StringBuffer(64);
140
			StringBuffer sb = new StringBuffer(64);
142
			sb.append(getClass().getName());
141
			sb.append(getClass().getName());
143
			sb.append('[').append(formatValue()).append(']');
142
			sb.append('[').append(formatValue()).append(']');
Lines 320-327 public final class FormulaRecord extends CellRecord { Link Here
320
		field_8_parsed_expr = Formula.create(ptgs);
319
		field_8_parsed_expr = Formula.create(ptgs);
321
	}
320
	}
322
321
323
	@Override
322
	public short getSid() {
324
    public short getSid() {
325
		return sid;
323
		return sid;
326
	}
324
	}
327
325
Lines 374-381 public final class FormulaRecord extends CellRecord { Link Here
374
		}
372
		}
375
	}
373
	}
376
374
377
	@Override
375
	public Object clone() {
378
    public Object clone() {
379
		FormulaRecord rec = new FormulaRecord();
376
		FormulaRecord rec = new FormulaRecord();
380
		copyBaseFields(rec);
377
		copyBaseFields(rec);
381
		rec.field_4_value = field_4_value;
378
		rec.field_4_value = field_4_value;
(-)a/src/java/org/apache/poi/hssf/record/RKRecord.java (-2 lines)
Lines 94-105 public final class RKRecord extends CellRecord { Link Here
94
    	return 4;
94
    	return 4;
95
    }
95
    }
96
96
97
    @Override
98
    public short getSid() {
97
    public short getSid() {
99
        return sid;
98
        return sid;
100
    }
99
    }
101
100
102
    @Override
103
    public Object clone() {
101
    public Object clone() {
104
      RKRecord rec = new RKRecord();
102
      RKRecord rec = new RKRecord();
105
      copyBaseFields(rec);
103
      copyBaseFields(rec);
(-)a/src/java/org/apache/poi/hssf/usermodel/DummyGraphics2d.java (-794 / +794 lines)
Lines 1-794 Link Here
1
/* ====================================================================
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
7
   the License.  You may obtain a copy of the License at
8
8
9
       http://www.apache.org/licenses/LICENSE-2.0
9
       http://www.apache.org/licenses/LICENSE-2.0
10
10
11
   Unless required by applicable law or agreed to in writing, software
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
15
   limitations under the License.
16
==================================================================== */
16
==================================================================== */
17
17
18
18
19
package org.apache.poi.hssf.usermodel;
19
package org.apache.poi.hssf.usermodel;
20
20
21
import java.awt.*;
21
import java.awt.*;
22
import java.awt.font.FontRenderContext;
22
import java.awt.font.FontRenderContext;
23
import java.awt.font.GlyphVector;
23
import java.awt.font.GlyphVector;
24
import java.awt.geom.AffineTransform;
24
import java.awt.geom.AffineTransform;
25
import java.awt.image.BufferedImage;
25
import java.awt.image.BufferedImage;
26
import java.awt.image.BufferedImageOp;
26
import java.awt.image.BufferedImageOp;
27
import java.awt.image.ImageObserver;
27
import java.awt.image.ImageObserver;
28
import java.awt.image.RenderedImage;
28
import java.awt.image.RenderedImage;
29
import java.awt.image.renderable.RenderableImage;
29
import java.awt.image.renderable.RenderableImage;
30
import java.text.AttributedCharacterIterator;
30
import java.text.AttributedCharacterIterator;
31
import java.util.Map;
31
import java.util.Map;
32
32
33
public class DummyGraphics2d
33
public class DummyGraphics2d
34
        extends Graphics2D
34
        extends Graphics2D
35
{
35
{
36
    BufferedImage img;
36
    BufferedImage img;
37
    private Graphics2D g2D;
37
    private Graphics2D g2D;
38
38
39
    public DummyGraphics2d()
39
    public DummyGraphics2d()
40
    {
40
    {
41
        img = new BufferedImage(1000, 1000, 2);
41
        img = new BufferedImage(1000, 1000, 2);
42
        g2D = (Graphics2D)img.getGraphics();
42
        g2D = (Graphics2D)img.getGraphics();
43
    }
43
    }
44
44
45
    public void addRenderingHints(Map hints)
45
    public void addRenderingHints(Map hints)
46
    {
46
    {
47
        System.out.println( "addRenderingHinds(Map):" );
47
        System.out.println( "addRenderingHinds(Map):" );
48
        System.out.println( "  hints = " + hints );
48
        System.out.println( "  hints = " + hints );
49
        g2D.addRenderingHints( hints );
49
        g2D.addRenderingHints( hints );
50
    }
50
    }
51
51
52
    public void clip(Shape s)
52
    public void clip(Shape s)
53
    {
53
    {
54
        System.out.println( "clip(Shape):" );
54
        System.out.println( "clip(Shape):" );
55
        System.out.println( "  s = " + s );
55
        System.out.println( "  s = " + s );
56
        g2D.clip( s );
56
        g2D.clip( s );
57
    }
57
    }
58
58
59
    public void draw(Shape s)
59
    public void draw(Shape s)
60
    {
60
    {
61
        System.out.println( "draw(Shape):" );
61
        System.out.println( "draw(Shape):" );
62
        System.out.println( "s = " + s );
62
        System.out.println( "s = " + s );
63
        g2D.draw( s );
63
        g2D.draw( s );
64
    }
64
    }
65
65
66
    public void drawGlyphVector(GlyphVector g, float x, float y)
66
    public void drawGlyphVector(GlyphVector g, float x, float y)
67
    {
67
    {
68
        System.out.println( "drawGlyphVector(GlyphVector, float, float):" );
68
        System.out.println( "drawGlyphVector(GlyphVector, float, float):" );
69
        System.out.println( "g = " + g );
69
        System.out.println( "g = " + g );
70
        System.out.println( "x = " + x );
70
        System.out.println( "x = " + x );
71
        System.out.println( "y = " + y );
71
        System.out.println( "y = " + y );
72
        g2D.drawGlyphVector( g, x, y );
72
        g2D.drawGlyphVector( g, x, y );
73
    }
73
    }
74
74
75
    public void drawImage(BufferedImage img,
75
    public void drawImage(BufferedImage img,
76
				   BufferedImageOp op,
76
				   BufferedImageOp op,
77
				   int x,
77
				   int x,
78
				   int y)
78
				   int y)
79
    {
79
    {
80
        System.out.println( "drawImage(BufferedImage, BufferedImageOp, x, y):" );
80
        System.out.println( "drawImage(BufferedImage, BufferedImageOp, x, y):" );
81
        System.out.println( "img = " + img );
81
        System.out.println( "img = " + img );
82
        System.out.println( "op = " + op );
82
        System.out.println( "op = " + op );
83
        System.out.println( "x = " + x );
83
        System.out.println( "x = " + x );
84
        System.out.println( "y = " + y );
84
        System.out.println( "y = " + y );
85
        g2D.drawImage( img, op, x, y );
85
        g2D.drawImage( img, op, x, y );
86
    }
86
    }
87
87
88
    public boolean drawImage(Image img,
88
    public boolean drawImage(Image img,
89
                                      AffineTransform xform,
89
                                      AffineTransform xform,
90
                                      ImageObserver obs)
90
                                      ImageObserver obs)
91
    {
91
    {
92
        System.out.println( "drawImage(Image,AfflineTransform,ImageObserver):" );
92
        System.out.println( "drawImage(Image,AfflineTransform,ImageObserver):" );
93
        System.out.println( "img = " + img );
93
        System.out.println( "img = " + img );
94
        System.out.println( "xform = " + xform );
94
        System.out.println( "xform = " + xform );
95
        System.out.println( "obs = " + obs );
95
        System.out.println( "obs = " + obs );
96
        return g2D.drawImage( img, xform, obs );
96
        return g2D.drawImage( img, xform, obs );
97
    }
97
    }
98
98
99
    public void drawRenderableImage(RenderableImage img,
99
    public void drawRenderableImage(RenderableImage img,
100
                                             AffineTransform xform)
100
                                             AffineTransform xform)
101
    {
101
    {
102
        System.out.println( "drawRenderableImage(RenderableImage, AfflineTransform):" );
102
        System.out.println( "drawRenderableImage(RenderableImage, AfflineTransform):" );
103
        System.out.println( "img = " + img );
103
        System.out.println( "img = " + img );
104
        System.out.println( "xform = " + xform );
104
        System.out.println( "xform = " + xform );
105
        g2D.drawRenderableImage( img, xform );
105
        g2D.drawRenderableImage( img, xform );
106
    }
106
    }
107
107
108
    public void drawRenderedImage(RenderedImage img,
108
    public void drawRenderedImage(RenderedImage img,
109
                                           AffineTransform xform)
109
                                           AffineTransform xform)
110
    {
110
    {
111
        System.out.println( "drawRenderedImage(RenderedImage, AffineTransform):" );
111
        System.out.println( "drawRenderedImage(RenderedImage, AffineTransform):" );
112
        System.out.println( "img = " + img );
112
        System.out.println( "img = " + img );
113
        System.out.println( "xform = " + xform );
113
        System.out.println( "xform = " + xform );
114
        g2D.drawRenderedImage( img, xform );
114
        g2D.drawRenderedImage( img, xform );
115
    }
115
    }
116
116
117
    public void drawString(AttributedCharacterIterator iterator,
117
    public void drawString(AttributedCharacterIterator iterator,
118
                                    float x, float y)
118
                                    float x, float y)
119
    {
119
    {
120
        System.out.println( "drawString(AttributedCharacterIterator):" );
120
        System.out.println( "drawString(AttributedCharacterIterator):" );
121
        System.out.println( "iterator = " + iterator );
121
        System.out.println( "iterator = " + iterator );
122
        System.out.println( "x = " + x );
122
        System.out.println( "x = " + x );
123
        System.out.println( "y = " + y );
123
        System.out.println( "y = " + y );
124
        g2D.drawString( iterator, x, y );
124
        g2D.drawString( iterator, x, y );
125
    }
125
    }
126
126
127
//    public void drawString(AttributedCharacterIterator iterator,
127
//    public void drawString(AttributedCharacterIterator iterator,
128
//                                    int x, int y)
128
//                                    int x, int y)
129
//    {
129
//    {
130
//        g2D.drawString( iterator, x, y );
130
//        g2D.drawString( iterator, x, y );
131
//    }
131
//    }
132
132
133
    public void drawString(String s, float x, float y)
133
    public void drawString(String s, float x, float y)
134
    {
134
    {
135
        System.out.println( "drawString(s,x,y):" );
135
        System.out.println( "drawString(s,x,y):" );
136
        System.out.println( "s = " + s );
136
        System.out.println( "s = " + s );
137
        System.out.println( "x = " + x );
137
        System.out.println( "x = " + x );
138
        System.out.println( "y = " + y );
138
        System.out.println( "y = " + y );
139
        g2D.drawString( s, x, y );
139
        g2D.drawString( s, x, y );
140
    }
140
    }
141
141
142
//    public void drawString(String str, int x, int y)
142
//    public void drawString(String str, int x, int y)
143
//    {
143
//    {
144
//        g2D.drawString( str, x, y );
144
//        g2D.drawString( str, x, y );
145
//    }
145
//    }
146
146
147
    public void fill(Shape s)
147
    public void fill(Shape s)
148
    {
148
    {
149
        System.out.println( "fill(Shape):" );
149
        System.out.println( "fill(Shape):" );
150
        System.out.println( "s = " + s );
150
        System.out.println( "s = " + s );
151
        g2D.fill( s );
151
        g2D.fill( s );
152
    }
152
    }
153
153
154
//    public void fill3DRect(int x, int y, int width, int height,
154
//    public void fill3DRect(int x, int y, int width, int height,
155
//			   boolean raised) {
155
//			   boolean raised) {
156
//        g2D.fill3DRect( x, y, width, height, raised );
156
//        g2D.fill3DRect( x, y, width, height, raised );
157
//    }
157
//    }
158
158
159
    public Color getBackground()
159
    public Color getBackground()
160
    {
160
    {
161
        System.out.println( "getBackground():" );
161
        System.out.println( "getBackground():" );
162
        return g2D.getBackground();
162
        return g2D.getBackground();
163
    }
163
    }
164
164
165
    public Composite getComposite()
165
    public Composite getComposite()
166
    {
166
    {
167
        System.out.println( "getComposite():" );
167
        System.out.println( "getComposite():" );
168
        return g2D.getComposite();
168
        return g2D.getComposite();
169
    }
169
    }
170
170
171
    public GraphicsConfiguration getDeviceConfiguration()
171
    public GraphicsConfiguration getDeviceConfiguration()
172
    {
172
    {
173
        System.out.println( "getDeviceConfiguration():" );
173
        System.out.println( "getDeviceConfiguration():" );
174
        return g2D.getDeviceConfiguration();
174
        return g2D.getDeviceConfiguration();
175
    }
175
    }
176
176
177
    public FontRenderContext getFontRenderContext()
177
    public FontRenderContext getFontRenderContext()
178
    {
178
    {
179
        System.out.println( "getFontRenderContext():" );
179
        System.out.println( "getFontRenderContext():" );
180
        return g2D.getFontRenderContext();
180
        return g2D.getFontRenderContext();
181
    }
181
    }
182
182
183
    public Paint getPaint()
183
    public Paint getPaint()
184
    {
184
    {
185
        System.out.println( "getPaint():" );
185
        System.out.println( "getPaint():" );
186
        return g2D.getPaint();
186
        return g2D.getPaint();
187
    }
187
    }
188
188
189
    public Object getRenderingHint(RenderingHints.Key hintKey)
189
    public Object getRenderingHint(RenderingHints.Key hintKey)
190
    {
190
    {
191
        System.out.println( "getRenderingHint(RenderingHints.Key):" );
191
        System.out.println( "getRenderingHint(RenderingHints.Key):" );
192
        System.out.println( "hintKey = " + hintKey );
192
        System.out.println( "hintKey = " + hintKey );
193
        return g2D.getRenderingHint( hintKey );
193
        return g2D.getRenderingHint( hintKey );
194
    }
194
    }
195
195
196
    public RenderingHints getRenderingHints()
196
    public RenderingHints getRenderingHints()
197
    {
197
    {
198
        System.out.println( "getRenderingHints():" );
198
        System.out.println( "getRenderingHints():" );
199
        return g2D.getRenderingHints();
199
        return g2D.getRenderingHints();
200
    }
200
    }
201
201
202
    public Stroke getStroke()
202
    public Stroke getStroke()
203
    {
203
    {
204
        System.out.println( "getStroke():" );
204
        System.out.println( "getStroke():" );
205
        return g2D.getStroke();
205
        return g2D.getStroke();
206
    }
206
    }
207
207
208
    public AffineTransform getTransform()
208
    public AffineTransform getTransform()
209
    {
209
    {
210
        System.out.println( "getTransform():" );
210
        System.out.println( "getTransform():" );
211
        return g2D.getTransform();
211
        return g2D.getTransform();
212
    }
212
    }
213
213
214
    public boolean hit(Rectangle rect,
214
    public boolean hit(Rectangle rect,
215
				Shape s,
215
				Shape s,
216
				boolean onStroke)
216
				boolean onStroke)
217
    {
217
    {
218
        System.out.println( "hit(Rectangle, Shape, onStroke):" );
218
        System.out.println( "hit(Rectangle, Shape, onStroke):" );
219
        System.out.println( "rect = " + rect );
219
        System.out.println( "rect = " + rect );
220
        System.out.println( "s = " + s );
220
        System.out.println( "s = " + s );
221
        System.out.println( "onStroke = " + onStroke );
221
        System.out.println( "onStroke = " + onStroke );
222
        return g2D.hit( rect, s, onStroke );
222
        return g2D.hit( rect, s, onStroke );
223
    }
223
    }
224
224
225
    public void rotate(double theta)
225
    public void rotate(double theta)
226
    {
226
    {
227
        System.out.println( "rotate(theta):" );
227
        System.out.println( "rotate(theta):" );
228
        System.out.println( "theta = " + theta );
228
        System.out.println( "theta = " + theta );
229
        g2D.rotate( theta );
229
        g2D.rotate( theta );
230
    }
230
    }
231
231
232
    public void rotate(double theta, double x, double y)
232
    public void rotate(double theta, double x, double y)
233
    {
233
    {
234
        System.out.println( "rotate(double,double,double):" );
234
        System.out.println( "rotate(double,double,double):" );
235
        System.out.println( "theta = " + theta );
235
        System.out.println( "theta = " + theta );
236
        System.out.println( "x = " + x );
236
        System.out.println( "x = " + x );
237
        System.out.println( "y = " + y );
237
        System.out.println( "y = " + y );
238
        g2D.rotate( theta, x, y );
238
        g2D.rotate( theta, x, y );
239
    }
239
    }
240
240
241
    public void scale(double sx, double sy)
241
    public void scale(double sx, double sy)
242
    {
242
    {
243
        System.out.println( "scale(double,double):" );
243
        System.out.println( "scale(double,double):" );
244
        System.out.println( "sx = " + sx );
244
        System.out.println( "sx = " + sx );
245
        System.out.println( "sy" );
245
        System.out.println( "sy" );
246
        g2D.scale( sx, sy );
246
        g2D.scale( sx, sy );
247
    }
247
    }
248
248
249
    public void setBackground(Color color)
249
    public void setBackground(Color color)
250
    {
250
    {
251
        System.out.println( "setBackground(Color):" );
251
        System.out.println( "setBackground(Color):" );
252
        System.out.println( "color = " + color );
252
        System.out.println( "color = " + color );
253
        g2D.setBackground( color );
253
        g2D.setBackground( color );
254
    }
254
    }
255
255
256
    public void setComposite(Composite comp)
256
    public void setComposite(Composite comp)
257
    {
257
    {
258
        System.out.println( "setComposite(Composite):" );
258
        System.out.println( "setComposite(Composite):" );
259
        System.out.println( "comp = " + comp );
259
        System.out.println( "comp = " + comp );
260
        g2D.setComposite( comp );
260
        g2D.setComposite( comp );
261
    }
261
    }
262
262
263
    public void setPaint( Paint paint )
263
    public void setPaint( Paint paint )
264
    {
264
    {
265
        System.out.println( "setPain(Paint):" );
265
        System.out.println( "setPain(Paint):" );
266
        System.out.println( "paint = " + paint );
266
        System.out.println( "paint = " + paint );
267
        g2D.setPaint( paint );
267
        g2D.setPaint( paint );
268
    }
268
    }
269
269
270
    public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue)
270
    public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue)
271
    {
271
    {
272
        System.out.println( "setRenderingHint(RenderingHints.Key, Object):" );
272
        System.out.println( "setRenderingHint(RenderingHints.Key, Object):" );
273
        System.out.println( "hintKey = " + hintKey );
273
        System.out.println( "hintKey = " + hintKey );
274
        System.out.println( "hintValue = " + hintValue );
274
        System.out.println( "hintValue = " + hintValue );
275
        g2D.setRenderingHint( hintKey, hintValue );
275
        g2D.setRenderingHint( hintKey, hintValue );
276
    }
276
    }
277
277
278
    public void setRenderingHints(Map hints)
278
    public void setRenderingHints(Map hints)
279
    {
279
    {
280
        System.out.println( "setRenderingHints(Map):" );
280
        System.out.println( "setRenderingHints(Map):" );
281
        System.out.println( "hints = " + hints );
281
        System.out.println( "hints = " + hints );
282
        g2D.setRenderingHints( hints );
282
        g2D.setRenderingHints( hints );
283
    }
283
    }
284
284
285
    public void setStroke(Stroke s)
285
    public void setStroke(Stroke s)
286
    {
286
    {
287
        System.out.println( "setStroke(Stoke):" );
287
        System.out.println( "setStroke(Stoke):" );
288
        System.out.println( "s = " + s );
288
        System.out.println( "s = " + s );
289
        g2D.setStroke( s );
289
        g2D.setStroke( s );
290
    }
290
    }
291
291
292
    public void setTransform(AffineTransform Tx)
292
    public void setTransform(AffineTransform Tx)
293
    {
293
    {
294
        System.out.println( "setTransform():" );
294
        System.out.println( "setTransform():" );
295
        System.out.println( "Tx = " + Tx );
295
        System.out.println( "Tx = " + Tx );
296
        g2D.setTransform( Tx );
296
        g2D.setTransform( Tx );
297
    }
297
    }
298
298
299
    public void shear(double shx, double shy)
299
    public void shear(double shx, double shy)
300
    {
300
    {
301
        System.out.println( "shear(shx, dhy):" );
301
        System.out.println( "shear(shx, dhy):" );
302
        System.out.println( "shx = " + shx );
302
        System.out.println( "shx = " + shx );
303
        System.out.println( "shy = " + shy );
303
        System.out.println( "shy = " + shy );
304
        g2D.shear( shx, shy );
304
        g2D.shear( shx, shy );
305
    }
305
    }
306
306
307
    public void transform(AffineTransform Tx)
307
    public void transform(AffineTransform Tx)
308
    {
308
    {
309
        System.out.println( "transform(AffineTransform):" );
309
        System.out.println( "transform(AffineTransform):" );
310
        System.out.println( "Tx = " + Tx );
310
        System.out.println( "Tx = " + Tx );
311
        g2D.transform( Tx );
311
        g2D.transform( Tx );
312
    }
312
    }
313
313
314
    public void translate(double tx, double ty)
314
    public void translate(double tx, double ty)
315
    {
315
    {
316
        System.out.println( "translate(double, double):" );
316
        System.out.println( "translate(double, double):" );
317
        System.out.println( "tx = " + tx );
317
        System.out.println( "tx = " + tx );
318
        System.out.println( "ty = " + ty );
318
        System.out.println( "ty = " + ty );
319
        g2D.translate( tx, ty );
319
        g2D.translate( tx, ty );
320
    }
320
    }
321
321
322
//    public void translate(int x, int y)
322
//    public void translate(int x, int y)
323
//    {
323
//    {
324
//        g2D.translate( x, y );
324
//        g2D.translate( x, y );
325
//    }
325
//    }
326
326
327
    public void clearRect(int x, int y, int width, int height)
327
    public void clearRect(int x, int y, int width, int height)
328
    {
328
    {
329
        System.out.println( "clearRect(int,int,int,int):" );
329
        System.out.println( "clearRect(int,int,int,int):" );
330
        System.out.println( "x = " + x );
330
        System.out.println( "x = " + x );
331
        System.out.println( "y = " + y );
331
        System.out.println( "y = " + y );
332
        System.out.println( "width = " + width );
332
        System.out.println( "width = " + width );
333
        System.out.println( "height = " + height );
333
        System.out.println( "height = " + height );
334
        g2D.clearRect( x, y, width, height );
334
        g2D.clearRect( x, y, width, height );
335
    }
335
    }
336
336
337
    public void clipRect(int x, int y, int width, int height)
337
    public void clipRect(int x, int y, int width, int height)
338
    {
338
    {
339
        System.out.println( "clipRect(int, int, int, int):" );
339
        System.out.println( "clipRect(int, int, int, int):" );
340
        System.out.println( "x = " + x );
340
        System.out.println( "x = " + x );
341
        System.out.println( "y = " + y );
341
        System.out.println( "y = " + y );
342
        System.out.println( "width = " + width );
342
        System.out.println( "width = " + width );
343
        System.out.println( "height = " + height );
343
        System.out.println( "height = " + height );
344
        g2D.clipRect( x, y, width, height );
344
        g2D.clipRect( x, y, width, height );
345
    }
345
    }
346
346
347
    public void copyArea(int x, int y, int width, int height,
347
    public void copyArea(int x, int y, int width, int height,
348
				  int dx, int dy)
348
				  int dx, int dy)
349
    {
349
    {
350
        System.out.println( "copyArea(int,int,int,int):" );
350
        System.out.println( "copyArea(int,int,int,int):" );
351
        System.out.println( "x = " + x );
351
        System.out.println( "x = " + x );
352
        System.out.println( "y = " + y );
352
        System.out.println( "y = " + y );
353
        System.out.println( "width = " + width );
353
        System.out.println( "width = " + width );
354
        System.out.println( "height = " + height );
354
        System.out.println( "height = " + height );
355
        g2D.copyArea( x, y, width, height, dx, dy );
355
        g2D.copyArea( x, y, width, height, dx, dy );
356
    }
356
    }
357
357
358
    public Graphics create()
358
    public Graphics create()
359
    {
359
    {
360
        System.out.println( "create():" );
360
        System.out.println( "create():" );
361
        return g2D.create();
361
        return g2D.create();
362
    }
362
    }
363
363
364
    public Graphics create(int x, int y, int width, int height) {
364
    public Graphics create(int x, int y, int width, int height) {
365
        System.out.println( "create(int,int,int,int):" );
365
        System.out.println( "create(int,int,int,int):" );
366
        System.out.println( "x = " + x );
366
        System.out.println( "x = " + x );
367
        System.out.println( "y = " + y );
367
        System.out.println( "y = " + y );
368
        System.out.println( "width = " + width );
368
        System.out.println( "width = " + width );
369
        System.out.println( "height = " + height );
369
        System.out.println( "height = " + height );
370
        return g2D.create( x, y, width, height );
370
        return g2D.create( x, y, width, height );
371
    }
371
    }
372
372
373
    public void dispose()
373
    public void dispose()
374
    {
374
    {
375
        System.out.println( "dispose():" );
375
        System.out.println( "dispose():" );
376
        g2D.dispose();
376
        g2D.dispose();
377
    }
377
    }
378
378
379
    public void draw3DRect(int x, int y, int width, int height,
379
    public void draw3DRect(int x, int y, int width, int height,
380
			   boolean raised) {
380
			   boolean raised) {
381
        System.out.println( "draw3DRect(int,int,int,int,boolean):" );
381
        System.out.println( "draw3DRect(int,int,int,int,boolean):" );
382
        System.out.println( "x = " + x );
382
        System.out.println( "x = " + x );
383
        System.out.println( "y = " + y );
383
        System.out.println( "y = " + y );
384
        System.out.println( "width = " + width );
384
        System.out.println( "width = " + width );
385
        System.out.println( "height = " + height );
385
        System.out.println( "height = " + height );
386
        System.out.println( "raised = " + raised );
386
        System.out.println( "raised = " + raised );
387
        g2D.draw3DRect( x, y, width, height, raised );
387
        g2D.draw3DRect( x, y, width, height, raised );
388
    }
388
    }
389
389
390
    public void drawArc(int x, int y, int width, int height,
390
    public void drawArc(int x, int y, int width, int height,
391
				 int startAngle, int arcAngle)
391
				 int startAngle, int arcAngle)
392
    {
392
    {
393
        System.out.println( "drawArc(int,int,int,int,int,int):" );
393
        System.out.println( "drawArc(int,int,int,int,int,int):" );
394
        System.out.println( "x = " + x );
394
        System.out.println( "x = " + x );
395
        System.out.println( "y = " + y );
395
        System.out.println( "y = " + y );
396
        System.out.println( "width = " + width );
396
        System.out.println( "width = " + width );
397
        System.out.println( "height = " + height );
397
        System.out.println( "height = " + height );
398
        System.out.println( "startAngle = " + startAngle );
398
        System.out.println( "startAngle = " + startAngle );
399
        System.out.println( "arcAngle = " + arcAngle );
399
        System.out.println( "arcAngle = " + arcAngle );
400
        g2D.drawArc( x, y, width, height, startAngle, arcAngle );
400
        g2D.drawArc( x, y, width, height, startAngle, arcAngle );
401
    }
401
    }
402
402
403
    public void drawBytes(byte data[], int offset, int length, int x, int y) {
403
    public void drawBytes(byte data[], int offset, int length, int x, int y) {
404
        System.out.println( "drawBytes(byte[],int,int,int,int):" );
404
        System.out.println( "drawBytes(byte[],int,int,int,int):" );
405
        System.out.println( "data = " + data );
405
        System.out.println( "data = " + data );
406
        System.out.println( "offset = " + offset );
406
        System.out.println( "offset = " + offset );
407
        System.out.println( "length = " + length );
407
        System.out.println( "length = " + length );
408
        System.out.println( "x = " + x );
408
        System.out.println( "x = " + x );
409
        System.out.println( "y = " + y );
409
        System.out.println( "y = " + y );
410
        g2D.drawBytes( data, offset, length, x, y );
410
        g2D.drawBytes( data, offset, length, x, y );
411
    }
411
    }
412
412
413
    public void drawChars(char data[], int offset, int length, int x, int y) {
413
    public void drawChars(char data[], int offset, int length, int x, int y) {
414
        System.out.println( "drawChars(data,int,int,int,int):" );
414
        System.out.println( "drawChars(data,int,int,int,int):" );
415
        System.out.println( "data = " + data.toString() );
415
        System.out.println( "data = " + data.toString() );
416
        System.out.println( "offset = " + offset );
416
        System.out.println( "offset = " + offset );
417
        System.out.println( "length = " + length );
417
        System.out.println( "length = " + length );
418
        System.out.println( "x = " + x );
418
        System.out.println( "x = " + x );
419
        System.out.println( "y = " + y );
419
        System.out.println( "y = " + y );
420
        g2D.drawChars( data, offset, length, x, y );
420
        g2D.drawChars( data, offset, length, x, y );
421
    }
421
    }
422
422
423
    public boolean drawImage(Image img,
423
    public boolean drawImage(Image img,
424
				      int dx1, int dy1, int dx2, int dy2,
424
				      int dx1, int dy1, int dx2, int dy2,
425
				      int sx1, int sy1, int sx2, int sy2,
425
				      int sx1, int sy1, int sx2, int sy2,
426
				      ImageObserver observer)
426
				      ImageObserver observer)
427
    {
427
    {
428
        System.out.println( "drawImage(Image,int,int,int,int,int,int,int,int,ImageObserver):" );
428
        System.out.println( "drawImage(Image,int,int,int,int,int,int,int,int,ImageObserver):" );
429
        System.out.println( "img = " + img );
429
        System.out.println( "img = " + img );
430
        System.out.println( "dx1 = " + dx1 );
430
        System.out.println( "dx1 = " + dx1 );
431
        System.out.println( "dy1 = " + dy1 );
431
        System.out.println( "dy1 = " + dy1 );
432
        System.out.println( "dx2 = " + dx2 );
432
        System.out.println( "dx2 = " + dx2 );
433
        System.out.println( "dy2 = " + dy2 );
433
        System.out.println( "dy2 = " + dy2 );
434
        System.out.println( "sx1 = " + sx1 );
434
        System.out.println( "sx1 = " + sx1 );
435
        System.out.println( "sy1 = " + sy1 );
435
        System.out.println( "sy1 = " + sy1 );
436
        System.out.println( "sx2 = " + sx2 );
436
        System.out.println( "sx2 = " + sx2 );
437
        System.out.println( "sy2 = " + sy2 );
437
        System.out.println( "sy2 = " + sy2 );
438
        System.out.println( "observer = " + observer );
438
        System.out.println( "observer = " + observer );
439
        return g2D.drawImage( img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, observer );
439
        return g2D.drawImage( img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, observer );
440
    }
440
    }
441
441
442
    public boolean drawImage(Image img,
442
    public boolean drawImage(Image img,
443
				      int dx1, int dy1, int dx2, int dy2,
443
				      int dx1, int dy1, int dx2, int dy2,
444
				      int sx1, int sy1, int sx2, int sy2,
444
				      int sx1, int sy1, int sx2, int sy2,
445
				      Color bgcolor,
445
				      Color bgcolor,
446
				      ImageObserver observer)
446
				      ImageObserver observer)
447
    {
447
    {
448
        System.out.println( "drawImage(Image,int,int,int,int,int,int,int,int,Color,ImageObserver):" );
448
        System.out.println( "drawImage(Image,int,int,int,int,int,int,int,int,Color,ImageObserver):" );
449
        System.out.println( "img = " + img );
449
        System.out.println( "img = " + img );
450
        System.out.println( "dx1 = " + dx1 );
450
        System.out.println( "dx1 = " + dx1 );
451
        System.out.println( "dy1 = " + dy1 );
451
        System.out.println( "dy1 = " + dy1 );
452
        System.out.println( "dx2 = " + dx2 );
452
        System.out.println( "dx2 = " + dx2 );
453
        System.out.println( "dy2 = " + dy2 );
453
        System.out.println( "dy2 = " + dy2 );
454
        System.out.println( "sx1 = " + sx1 );
454
        System.out.println( "sx1 = " + sx1 );
455
        System.out.println( "sy1 = " + sy1 );
455
        System.out.println( "sy1 = " + sy1 );
456
        System.out.println( "sx2 = " + sx2 );
456
        System.out.println( "sx2 = " + sx2 );
457
        System.out.println( "sy2 = " + sy2 );
457
        System.out.println( "sy2 = " + sy2 );
458
        System.out.println( "bgcolor = " + bgcolor );
458
        System.out.println( "bgcolor = " + bgcolor );
459
        System.out.println( "observer = " + observer );
459
        System.out.println( "observer = " + observer );
460
        return g2D.drawImage( img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgcolor, observer );
460
        return g2D.drawImage( img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgcolor, observer );
461
    }
461
    }
462
462
463
    public boolean drawImage(Image img, int x, int y,
463
    public boolean drawImage(Image img, int x, int y,
464
				      Color bgcolor,
464
				      Color bgcolor,
465
				      ImageObserver observer)
465
				      ImageObserver observer)
466
    {
466
    {
467
        System.out.println( "drawImage(Image,int,int,Color,ImageObserver):" );
467
        System.out.println( "drawImage(Image,int,int,Color,ImageObserver):" );
468
        System.out.println( "img = " + img );
468
        System.out.println( "img = " + img );
469
        System.out.println( "x = " + x );
469
        System.out.println( "x = " + x );
470
        System.out.println( "y = " + y );
470
        System.out.println( "y = " + y );
471
        System.out.println( "bgcolor = " + bgcolor );
471
        System.out.println( "bgcolor = " + bgcolor );
472
        System.out.println( "observer = " + observer );
472
        System.out.println( "observer = " + observer );
473
        return g2D.drawImage( img, x, y, bgcolor, observer );
473
        return g2D.drawImage( img, x, y, bgcolor, observer );
474
    }
474
    }
475
475
476
    public boolean drawImage(Image img, int x, int y,
476
    public boolean drawImage(Image img, int x, int y,
477
				      ImageObserver observer)
477
				      ImageObserver observer)
478
    {
478
    {
479
        System.out.println( "drawImage(Image,int,int,observer):" );
479
        System.out.println( "drawImage(Image,int,int,observer):" );
480
        System.out.println( "img = " + img );
480
        System.out.println( "img = " + img );
481
        System.out.println( "x = " + x );
481
        System.out.println( "x = " + x );
482
        System.out.println( "y = " + y );
482
        System.out.println( "y = " + y );
483
        System.out.println( "observer = " + observer );
483
        System.out.println( "observer = " + observer );
484
        return g2D.drawImage( img, x, y, observer );
484
        return g2D.drawImage( img, x, y, observer );
485
    }
485
    }
486
486
487
    public boolean drawImage(Image img, int x, int y,
487
    public boolean drawImage(Image img, int x, int y,
488
				      int width, int height,
488
				      int width, int height,
489
				      Color bgcolor,
489
				      Color bgcolor,
490
				      ImageObserver observer)
490
				      ImageObserver observer)
491
    {
491
    {
492
        System.out.println( "drawImage(Image,int,int,int,int,Color,ImageObserver):" );
492
        System.out.println( "drawImage(Image,int,int,int,int,Color,ImageObserver):" );
493
        System.out.println( "img = " + img );
493
        System.out.println( "img = " + img );
494
        System.out.println( "x = " + x );
494
        System.out.println( "x = " + x );
495
        System.out.println( "y = " + y );
495
        System.out.println( "y = " + y );
496
        System.out.println( "width = " + width );
496
        System.out.println( "width = " + width );
497
        System.out.println( "height = " + height );
497
        System.out.println( "height = " + height );
498
        System.out.println( "bgcolor = " + bgcolor );
498
        System.out.println( "bgcolor = " + bgcolor );
499
        System.out.println( "observer = " + observer );
499
        System.out.println( "observer = " + observer );
500
        return g2D.drawImage( img, x, y, width, height, bgcolor, observer );
500
        return g2D.drawImage( img, x, y, width, height, bgcolor, observer );
501
    }
501
    }
502
502
503
    public boolean drawImage(Image img, int x, int y,
503
    public boolean drawImage(Image img, int x, int y,
504
				      int width, int height,
504
				      int width, int height,
505
				      ImageObserver observer)
505
				      ImageObserver observer)
506
    {
506
    {
507
        System.out.println( "drawImage(Image,int,int,width,height,observer):" );
507
        System.out.println( "drawImage(Image,int,int,width,height,observer):" );
508
        System.out.println( "img = " + img );
508
        System.out.println( "img = " + img );
509
        System.out.println( "x = " + x );
509
        System.out.println( "x = " + x );
510
        System.out.println( "y = " + y );
510
        System.out.println( "y = " + y );
511
        System.out.println( "width = " + width );
511
        System.out.println( "width = " + width );
512
        System.out.println( "height = " + height );
512
        System.out.println( "height = " + height );
513
        System.out.println( "observer = " + observer );
513
        System.out.println( "observer = " + observer );
514
        return g2D.drawImage( img, x, y, width, height, observer );
514
        return g2D.drawImage( img, x, y, width, height, observer );
515
    }
515
    }
516
516
517
    public void drawLine(int x1, int y1, int x2, int y2)
517
    public void drawLine(int x1, int y1, int x2, int y2)
518
    {
518
    {
519
        System.out.println( "drawLine(int,int,int,int):" );
519
        System.out.println( "drawLine(int,int,int,int):" );
520
        System.out.println( "x1 = " + x1 );
520
        System.out.println( "x1 = " + x1 );
521
        System.out.println( "y1 = " + y1 );
521
        System.out.println( "y1 = " + y1 );
522
        System.out.println( "x2 = " + x2 );
522
        System.out.println( "x2 = " + x2 );
523
        System.out.println( "y2 = " + y2 );
523
        System.out.println( "y2 = " + y2 );
524
        g2D.drawLine( x1, y1, x2, y2 );
524
        g2D.drawLine( x1, y1, x2, y2 );
525
    }
525
    }
526
526
527
    public void drawOval(int x, int y, int width, int height)
527
    public void drawOval(int x, int y, int width, int height)
528
    {
528
    {
529
        System.out.println( "drawOval(int,int,int,int):" );
529
        System.out.println( "drawOval(int,int,int,int):" );
530
        System.out.println( "x = " + x );
530
        System.out.println( "x = " + x );
531
        System.out.println( "y = " + y );
531
        System.out.println( "y = " + y );
532
        System.out.println( "width = " + width );
532
        System.out.println( "width = " + width );
533
        System.out.println( "height = " + height );
533
        System.out.println( "height = " + height );
534
        g2D.drawOval( x, y, width, height );
534
        g2D.drawOval( x, y, width, height );
535
    }
535
    }
536
536
537
    public void drawPolygon(Polygon p) {
537
    public void drawPolygon(Polygon p) {
538
        System.out.println( "drawPolygon(Polygon):" );
538
        System.out.println( "drawPolygon(Polygon):" );
539
        System.out.println( "p = " + p );
539
        System.out.println( "p = " + p );
540
        g2D.drawPolygon( p );
540
        g2D.drawPolygon( p );
541
    }
541
    }
542
542
543
    public void drawPolygon(int xPoints[], int yPoints[],
543
    public void drawPolygon(int xPoints[], int yPoints[],
544
				     int nPoints)
544
				     int nPoints)
545
    {
545
    {
546
        System.out.println( "drawPolygon(int[],int[],int):" );
546
        System.out.println( "drawPolygon(int[],int[],int):" );
547
        System.out.println( "xPoints = " + xPoints );
547
        System.out.println( "xPoints = " + xPoints );
548
        System.out.println( "yPoints = " + yPoints );
548
        System.out.println( "yPoints = " + yPoints );
549
        System.out.println( "nPoints = " + nPoints );
549
        System.out.println( "nPoints = " + nPoints );
550
        g2D.drawPolygon( xPoints, yPoints, nPoints );
550
        g2D.drawPolygon( xPoints, yPoints, nPoints );
551
    }
551
    }
552
552
553
    public void drawPolyline(int xPoints[], int yPoints[],
553
    public void drawPolyline(int xPoints[], int yPoints[],
554
				      int nPoints)
554
				      int nPoints)
555
    {
555
    {
556
        System.out.println( "drawPolyline(int[],int[],int):" );
556
        System.out.println( "drawPolyline(int[],int[],int):" );
557
        System.out.println( "xPoints = " + xPoints );
557
        System.out.println( "xPoints = " + xPoints );
558
        System.out.println( "yPoints = " + yPoints );
558
        System.out.println( "yPoints = " + yPoints );
559
        System.out.println( "nPoints = " + nPoints );
559
        System.out.println( "nPoints = " + nPoints );
560
        g2D.drawPolyline( xPoints, yPoints, nPoints );
560
        g2D.drawPolyline( xPoints, yPoints, nPoints );
561
    }
561
    }
562
562
563
    public void drawRect(int x, int y, int width, int height) {
563
    public void drawRect(int x, int y, int width, int height) {
564
        System.out.println( "drawRect(int,int,int,int):" );
564
        System.out.println( "drawRect(int,int,int,int):" );
565
        System.out.println( "x = " + x );
565
        System.out.println( "x = " + x );
566
        System.out.println( "y = " + y );
566
        System.out.println( "y = " + y );
567
        System.out.println( "width = " + width );
567
        System.out.println( "width = " + width );
568
        System.out.println( "height = " + height );
568
        System.out.println( "height = " + height );
569
        g2D.drawRect( x, y, width, height );
569
        g2D.drawRect( x, y, width, height );
570
    }
570
    }
571
571
572
    public void drawRoundRect(int x, int y, int width, int height,
572
    public void drawRoundRect(int x, int y, int width, int height,
573
				       int arcWidth, int arcHeight)
573
				       int arcWidth, int arcHeight)
574
    {
574
    {
575
        System.out.println( "drawRoundRect(int,int,int,int,int,int):" );
575
        System.out.println( "drawRoundRect(int,int,int,int,int,int):" );
576
        System.out.println( "x = " + x );
576
        System.out.println( "x = " + x );
577
        System.out.println( "y = " + y );
577
        System.out.println( "y = " + y );
578
        System.out.println( "width = " + width );
578
        System.out.println( "width = " + width );
579
        System.out.println( "height = " + height );
579
        System.out.println( "height = " + height );
580
        System.out.println( "arcWidth = " + arcWidth );
580
        System.out.println( "arcWidth = " + arcWidth );
581
        System.out.println( "arcHeight = " + arcHeight );
581
        System.out.println( "arcHeight = " + arcHeight );
582
        g2D.drawRoundRect( x, y, width, height, arcWidth, arcHeight );
582
        g2D.drawRoundRect( x, y, width, height, arcWidth, arcHeight );
583
    }
583
    }
584
584
585
    public void drawString(AttributedCharacterIterator iterator,
585
    public void drawString(AttributedCharacterIterator iterator,
586
                                    int x, int y)
586
                                    int x, int y)
587
    {
587
    {
588
        System.out.println( "drawString(AttributedCharacterIterator,int,int):" );
588
        System.out.println( "drawString(AttributedCharacterIterator,int,int):" );
589
        System.out.println( "iterator = " + iterator );
589
        System.out.println( "iterator = " + iterator );
590
        System.out.println( "x = " + x );
590
        System.out.println( "x = " + x );
591
        System.out.println( "y = " + y );
591
        System.out.println( "y = " + y );
592
        g2D.drawString( iterator, x, y );
592
        g2D.drawString( iterator, x, y );
593
    }
593
    }
594
594
595
    public void drawString(String str, int x, int y)
595
    public void drawString(String str, int x, int y)
596
    {
596
    {
597
        System.out.println( "drawString(str,int,int):" );
597
        System.out.println( "drawString(str,int,int):" );
598
        System.out.println( "str = " + str );
598
        System.out.println( "str = " + str );
599
        System.out.println( "x = " + x );
599
        System.out.println( "x = " + x );
600
        System.out.println( "y = " + y );
600
        System.out.println( "y = " + y );
601
        g2D.drawString( str, x, y );
601
        g2D.drawString( str, x, y );
602
    }
602
    }
603
603
604
    public void fill3DRect(int x, int y, int width, int height,
604
    public void fill3DRect(int x, int y, int width, int height,
605
			   boolean raised) {
605
			   boolean raised) {
606
        System.out.println( "fill3DRect(int,int,int,int,boolean):" );
606
        System.out.println( "fill3DRect(int,int,int,int,boolean):" );
607
        System.out.println( "x = " + x );
607
        System.out.println( "x = " + x );
608
        System.out.println( "y = " + y );
608
        System.out.println( "y = " + y );
609
        System.out.println( "width = " + width );
609
        System.out.println( "width = " + width );
610
        System.out.println( "height = " + height );
610
        System.out.println( "height = " + height );
611
        System.out.println( "raised = " + raised );
611
        System.out.println( "raised = " + raised );
612
        g2D.fill3DRect( x, y, width, height, raised );
612
        g2D.fill3DRect( x, y, width, height, raised );
613
    }
613
    }
614
614
615
    public void fillArc(int x, int y, int width, int height,
615
    public void fillArc(int x, int y, int width, int height,
616
				 int startAngle, int arcAngle)
616
				 int startAngle, int arcAngle)
617
    {
617
    {
618
        System.out.println( "fillArc(int,int,int,int,int,int):" );
618
        System.out.println( "fillArc(int,int,int,int,int,int):" );
619
        System.out.println( "x = " + x );
619
        System.out.println( "x = " + x );
620
        System.out.println( "y = " + y );
620
        System.out.println( "y = " + y );
621
        System.out.println( "width = " + width );
621
        System.out.println( "width = " + width );
622
        System.out.println( "height = " + height );
622
        System.out.println( "height = " + height );
623
        System.out.println( "startAngle = " + startAngle );
623
        System.out.println( "startAngle = " + startAngle );
624
        System.out.println( "arcAngle = " + arcAngle );
624
        System.out.println( "arcAngle = " + arcAngle );
625
        g2D.fillArc( x, y, width, height, startAngle, arcAngle );
625
        g2D.fillArc( x, y, width, height, startAngle, arcAngle );
626
    }
626
    }
627
627
628
    public void fillOval(int x, int y, int width, int height)
628
    public void fillOval(int x, int y, int width, int height)
629
    {
629
    {
630
        System.out.println( "fillOval(int,int,int,int):" );
630
        System.out.println( "fillOval(int,int,int,int):" );
631
        System.out.println( "x = " + x );
631
        System.out.println( "x = " + x );
632
        System.out.println( "y = " + y );
632
        System.out.println( "y = " + y );
633
        System.out.println( "width = " + width );
633
        System.out.println( "width = " + width );
634
        System.out.println( "height = " + height );
634
        System.out.println( "height = " + height );
635
        g2D.fillOval( x, y, width, height );
635
        g2D.fillOval( x, y, width, height );
636
    }
636
    }
637
637
638
    public void fillPolygon(Polygon p) {
638
    public void fillPolygon(Polygon p) {
639
        System.out.println( "fillPolygon(Polygon):" );
639
        System.out.println( "fillPolygon(Polygon):" );
640
        System.out.println( "p = " + p );
640
        System.out.println( "p = " + p );
641
        g2D.fillPolygon( p );
641
        g2D.fillPolygon( p );
642
    }
642
    }
643
643
644
    public void fillPolygon(int xPoints[], int yPoints[],
644
    public void fillPolygon(int xPoints[], int yPoints[],
645
				     int nPoints)
645
				     int nPoints)
646
    {
646
    {
647
        System.out.println( "fillPolygon(int[],int[],int):" );
647
        System.out.println( "fillPolygon(int[],int[],int):" );
648
        System.out.println( "xPoints = " + xPoints );
648
        System.out.println( "xPoints = " + xPoints );
649
        System.out.println( "yPoints = " + yPoints );
649
        System.out.println( "yPoints = " + yPoints );
650
        System.out.println( "nPoints = " + nPoints );
650
        System.out.println( "nPoints = " + nPoints );
651
        g2D.fillPolygon( xPoints, yPoints, nPoints );
651
        g2D.fillPolygon( xPoints, yPoints, nPoints );
652
    }
652
    }
653
653
654
    public void fillRect(int x, int y, int width, int height)
654
    public void fillRect(int x, int y, int width, int height)
655
    {
655
    {
656
        System.out.println( "fillRect(int,int,int,int):" );
656
        System.out.println( "fillRect(int,int,int,int):" );
657
        System.out.println( "x = " + x );
657
        System.out.println( "x = " + x );
658
        System.out.println( "y = " + y );
658
        System.out.println( "y = " + y );
659
        System.out.println( "width = " + width );
659
        System.out.println( "width = " + width );
660
        System.out.println( "height = " + height );
660
        System.out.println( "height = " + height );
661
        g2D.fillRect( x, y, width, height );
661
        g2D.fillRect( x, y, width, height );
662
    }
662
    }
663
663
664
    public void fillRoundRect(int x, int y, int width, int height,
664
    public void fillRoundRect(int x, int y, int width, int height,
665
				       int arcWidth, int arcHeight)
665
				       int arcWidth, int arcHeight)
666
    {
666
    {
667
        System.out.println( "fillRoundRect(int,int,int,int,int,int):" );
667
        System.out.println( "fillRoundRect(int,int,int,int,int,int):" );
668
        System.out.println( "x = " + x );
668
        System.out.println( "x = " + x );
669
        System.out.println( "y = " + y );
669
        System.out.println( "y = " + y );
670
        System.out.println( "width = " + width );
670
        System.out.println( "width = " + width );
671
        System.out.println( "height = " + height );
671
        System.out.println( "height = " + height );
672
        g2D.fillRoundRect( x, y, width, height, arcWidth, arcHeight );
672
        g2D.fillRoundRect( x, y, width, height, arcWidth, arcHeight );
673
    }
673
    }
674
674
675
    public void finalize() {
675
    public void finalize() {
676
        System.out.println( "finalize():" );
676
        System.out.println( "finalize():" );
677
        g2D.finalize();
677
        g2D.finalize();
678
678
679
        super.finalize();
679
        super.finalize();
680
    }
680
    }
681
681
682
    public Shape getClip()
682
    public Shape getClip()
683
    {
683
    {
684
        System.out.println( "getClip():" );
684
        System.out.println( "getClip():" );
685
        return g2D.getClip();
685
        return g2D.getClip();
686
    }
686
    }
687
687
688
    public Rectangle getClipBounds()
688
    public Rectangle getClipBounds()
689
    {
689
    {
690
        System.out.println( "getClipBounds():" );
690
        System.out.println( "getClipBounds():" );
691
        return g2D.getClipBounds();
691
        return g2D.getClipBounds();
692
    }
692
    }
693
693
694
    public Rectangle getClipBounds(Rectangle r) {
694
    public Rectangle getClipBounds(Rectangle r) {
695
        System.out.println( "getClipBounds(Rectangle):" );
695
        System.out.println( "getClipBounds(Rectangle):" );
696
        System.out.println( "r = " + r );
696
        System.out.println( "r = " + r );
697
        return g2D.getClipBounds( r );
697
        return g2D.getClipBounds( r );
698
    }
698
    }
699
699
700
    @SuppressWarnings("deprecation")
700
    @SuppressWarnings("deprecation")
701
    public Rectangle getClipRect() {
701
    public Rectangle getClipRect() {
702
        System.out.println( "getClipRect():" );
702
        System.out.println( "getClipRect():" );
703
        return g2D.getClipRect();
703
        return g2D.getClipRect();
704
    }
704
    }
705
705
706
    public Color getColor()
706
    public Color getColor()
707
    {
707
    {
708
        System.out.println( "getColor():" );
708
        System.out.println( "getColor():" );
709
        return g2D.getColor();
709
        return g2D.getColor();
710
    }
710
    }
711
711
712
    public Font getFont()
712
    public Font getFont()
713
    {
713
    {
714
        System.out.println( "getFont():" );
714
        System.out.println( "getFont():" );
715
        return g2D.getFont();
715
        return g2D.getFont();
716
    }
716
    }
717
717
718
    public FontMetrics getFontMetrics() {
718
    public FontMetrics getFontMetrics() {
719
        System.out.println( "getFontMetrics():" );
719
        System.out.println( "getFontMetrics():" );
720
        return g2D.getFontMetrics();
720
        return g2D.getFontMetrics();
721
    }
721
    }
722
722
723
    public FontMetrics getFontMetrics(Font f)
723
    public FontMetrics getFontMetrics(Font f)
724
    {
724
    {
725
        System.out.println( "getFontMetrics():" );
725
        System.out.println( "getFontMetrics():" );
726
        return g2D.getFontMetrics( f );
726
        return g2D.getFontMetrics( f );
727
    }
727
    }
728
728
729
    public boolean hitClip(int x, int y, int width, int height) {
729
    public boolean hitClip(int x, int y, int width, int height) {
730
        System.out.println( "hitClip(int,int,int,int):" );
730
        System.out.println( "hitClip(int,int,int,int):" );
731
        System.out.println( "x = " + x );
731
        System.out.println( "x = " + x );
732
        System.out.println( "y = " + y );
732
        System.out.println( "y = " + y );
733
        System.out.println( "width = " + width );
733
        System.out.println( "width = " + width );
734
        System.out.println( "height = " + height );
734
        System.out.println( "height = " + height );
735
        return g2D.hitClip( x, y, width, height );
735
        return g2D.hitClip( x, y, width, height );
736
    }
736
    }
737
737
738
    public void setClip(Shape clip)
738
    public void setClip(Shape clip)
739
    {
739
    {
740
        System.out.println( "setClip(Shape):" );
740
        System.out.println( "setClip(Shape):" );
741
        System.out.println( "clip = " + clip );
741
        System.out.println( "clip = " + clip );
742
        g2D.setClip( clip );
742
        g2D.setClip( clip );
743
    }
743
    }
744
744
745
    public void setClip(int x, int y, int width, int height)
745
    public void setClip(int x, int y, int width, int height)
746
    {
746
    {
747
        System.out.println( "setClip(int,int,int,int):" );
747
        System.out.println( "setClip(int,int,int,int):" );
748
        System.out.println( "x = " + x );
748
        System.out.println( "x = " + x );
749
        System.out.println( "y = " + y );
749
        System.out.println( "y = " + y );
750
        System.out.println( "width = " + width );
750
        System.out.println( "width = " + width );
751
        System.out.println( "height = " + height );
751
        System.out.println( "height = " + height );
752
        g2D.setClip( x, y, width, height );
752
        g2D.setClip( x, y, width, height );
753
    }
753
    }
754
754
755
    public void setColor(Color c)
755
    public void setColor(Color c)
756
    {
756
    {
757
        System.out.println( "setColor():" );
757
        System.out.println( "setColor():" );
758
        System.out.println( "c = " + c );
758
        System.out.println( "c = " + c );
759
        g2D.setColor( c );
759
        g2D.setColor( c );
760
    }
760
    }
761
761
762
    public void setFont(Font font)
762
    public void setFont(Font font)
763
    {
763
    {
764
        System.out.println( "setFont(Font):" );
764
        System.out.println( "setFont(Font):" );
765
        System.out.println( "font = " + font );
765
        System.out.println( "font = " + font );
766
        g2D.setFont( font );
766
        g2D.setFont( font );
767
    }
767
    }
768
768
769
    public void setPaintMode()
769
    public void setPaintMode()
770
    {
770
    {
771
        System.out.println( "setPaintMode():" );
771
        System.out.println( "setPaintMode():" );
772
        g2D.setPaintMode();
772
        g2D.setPaintMode();
773
    }
773
    }
774
774
775
    public void setXORMode(Color c1)
775
    public void setXORMode(Color c1)
776
    {
776
    {
777
        System.out.println( "setXORMode(Color):" );
777
        System.out.println( "setXORMode(Color):" );
778
        System.out.println( "c1 = " + c1 );
778
        System.out.println( "c1 = " + c1 );
779
        g2D.setXORMode( c1 );
779
        g2D.setXORMode( c1 );
780
    }
780
    }
781
781
782
    public String toString() {
782
    public String toString() {
783
        System.out.println( "toString():" );
783
        System.out.println( "toString():" );
784
        return g2D.toString();
784
        return g2D.toString();
785
    }
785
    }
786
786
787
    public void translate(int x, int y)
787
    public void translate(int x, int y)
788
    {
788
    {
789
        System.out.println( "translate(int,int):" );
789
        System.out.println( "translate(int,int):" );
790
        System.out.println( "x = " + x );
790
        System.out.println( "x = " + x );
791
        System.out.println( "y = " + y );
791
        System.out.println( "y = " + y );
792
        g2D.translate( x, y );
792
        g2D.translate( x, y );
793
    }
793
    }
794
}
794
}
(-)a/src/java/org/apache/poi/hssf/usermodel/HSSFFormulaEvaluator.java (-24 / +10 lines)
Lines 51-58 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
51
	/**
51
	/**
52
	 * @deprecated (Sep 2008) HSSFSheet parameter is ignored
52
	 * @deprecated (Sep 2008) HSSFSheet parameter is ignored
53
	 */
53
	 */
54
	@Deprecated
54
	public HSSFFormulaEvaluator(HSSFSheet sheet, HSSFWorkbook workbook) {
55
    public HSSFFormulaEvaluator(HSSFSheet sheet, HSSFWorkbook workbook) {
56
		this(workbook);
55
		this(workbook);
57
		if (false) {
56
		if (false) {
58
			sheet.toString(); // suppress unused parameter compiler warning
57
			sheet.toString(); // suppress unused parameter compiler warning
Lines 105-116 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
105
		CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals);
104
		CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals);
106
	}
105
	}
107
106
108
	@Override
107
	public void setupReferencedWorkbooks(Map<String, FormulaEvaluator> evaluators) {
109
    public void setupReferencedWorkbooks(Map<String, FormulaEvaluator> evaluators) {
110
        CollaboratingWorkbooksEnvironment.setupFormulaEvaluator(evaluators);
108
        CollaboratingWorkbooksEnvironment.setupFormulaEvaluator(evaluators);
111
    }
109
    }
112
	
110
	
113
    @Override
114
    public WorkbookEvaluator _getWorkbookEvaluator() {
111
    public WorkbookEvaluator _getWorkbookEvaluator() {
115
        return _bookEvaluator;
112
        return _bookEvaluator;
116
    }
113
    }
Lines 119-126 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
119
	 * Does nothing
116
	 * Does nothing
120
	 * @deprecated (Aug 2008) - not needed, since the current row can be derived from the cell
117
	 * @deprecated (Aug 2008) - not needed, since the current row can be derived from the cell
121
	 */
118
	 */
122
	@Deprecated
119
	public void setCurrentRow(HSSFRow row) {
123
    public void setCurrentRow(HSSFRow row) {
124
		// do nothing
120
		// do nothing
125
		if (false) {
121
		if (false) {
126
			row.getClass(); // suppress unused parameter compiler warning
122
			row.getClass(); // suppress unused parameter compiler warning
Lines 135-142 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
135
	 * Failure to call this method after changing cell values will cause incorrect behaviour
131
	 * Failure to call this method after changing cell values will cause incorrect behaviour
136
	 * of the evaluate~ methods of this class
132
	 * of the evaluate~ methods of this class
137
	 */
133
	 */
138
	@Override
134
	public void clearAllCachedResultValues() {
139
    public void clearAllCachedResultValues() {
140
		_bookEvaluator.clearAllCachedResultValues();
135
		_bookEvaluator.clearAllCachedResultValues();
141
	}
136
	}
142
	/**
137
	/**
Lines 148-154 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
148
	public void notifyUpdateCell(HSSFCell cell) {
143
	public void notifyUpdateCell(HSSFCell cell) {
149
		_bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell(cell));
144
		_bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell(cell));
150
	}
145
	}
151
    @Override
152
    public void notifyUpdateCell(Cell cell) {
146
    public void notifyUpdateCell(Cell cell) {
153
        _bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell((HSSFCell)cell));
147
        _bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell((HSSFCell)cell));
154
    }
148
    }
Lines 161-168 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
161
	public void notifyDeleteCell(HSSFCell cell) {
155
	public void notifyDeleteCell(HSSFCell cell) {
162
		_bookEvaluator.notifyDeleteCell(new HSSFEvaluationCell(cell));
156
		_bookEvaluator.notifyDeleteCell(new HSSFEvaluationCell(cell));
163
	}
157
	}
164
	@Override
158
	public void notifyDeleteCell(Cell cell) {
165
    public void notifyDeleteCell(Cell cell) {
166
		_bookEvaluator.notifyDeleteCell(new HSSFEvaluationCell((HSSFCell)cell));
159
		_bookEvaluator.notifyDeleteCell(new HSSFEvaluationCell((HSSFCell)cell));
167
	}
160
	}
168
161
Lines 172-179 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
172
	 * Failure to call this method after changing cell values will cause incorrect behaviour
165
	 * Failure to call this method after changing cell values will cause incorrect behaviour
173
	 * of the evaluate~ methods of this class
166
	 * of the evaluate~ methods of this class
174
	 */
167
	 */
175
	@Override
168
	public void notifySetFormula(Cell cell) {
176
    public void notifySetFormula(Cell cell) {
177
		_bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell((HSSFCell)cell));
169
		_bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell((HSSFCell)cell));
178
	}
170
	}
179
171
Lines 187-194 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
187
	 * @param cell may be <code>null</code> signifying that the cell is not present (or blank)
179
	 * @param cell may be <code>null</code> signifying that the cell is not present (or blank)
188
	 * @return <code>null</code> if the supplied cell is <code>null</code> or blank
180
	 * @return <code>null</code> if the supplied cell is <code>null</code> or blank
189
	 */
181
	 */
190
	@Override
182
	public CellValue evaluate(Cell cell) {
191
    public CellValue evaluate(Cell cell) {
192
		if (cell == null) {
183
		if (cell == null) {
193
			return null;
184
			return null;
194
		}
185
		}
Lines 226-233 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
226
	 * @param cell The cell to evaluate
217
	 * @param cell The cell to evaluate
227
	 * @return -1 for non-formula cells, or the type of the <em>formula result</em>
218
	 * @return -1 for non-formula cells, or the type of the <em>formula result</em>
228
	 */
219
	 */
229
	@Override
220
	public int evaluateFormulaCell(Cell cell) {
230
    public int evaluateFormulaCell(Cell cell) {
231
		if (cell == null || cell.getCellType() != HSSFCell.CELL_TYPE_FORMULA) {
221
		if (cell == null || cell.getCellType() != HSSFCell.CELL_TYPE_FORMULA) {
232
			return -1;
222
			return -1;
233
		}
223
		}
Lines 252-259 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
252
	 *  result of the formula. If you simply want the formula
242
	 *  result of the formula. If you simply want the formula
253
	 *  value computed for you, use {@link #evaluateFormulaCell(Cell)}}
243
	 *  value computed for you, use {@link #evaluateFormulaCell(Cell)}}
254
	 */
244
	 */
255
	@Override
245
	public HSSFCell evaluateInCell(Cell cell) {
256
    public HSSFCell evaluateInCell(Cell cell) {
257
		if (cell == null) {
246
		if (cell == null) {
258
			return null;
247
			return null;
259
		}
248
		}
Lines 361-368 public class HSSFFormulaEvaluator implements FormulaEvaluator, WorkbookEvaluator Link Here
361
    * This is a helpful wrapper around looping over all
350
    * This is a helpful wrapper around looping over all
362
    *  cells, and calling evaluateFormulaCell on each one.
351
    *  cells, and calling evaluateFormulaCell on each one.
363
    */
352
    */
364
   @Override
353
   public void evaluateAll() {
365
public void evaluateAll() {
366
      evaluateAllFormulaCells(_book, this);
354
      evaluateAllFormulaCells(_book, this);
367
   }
355
   }
368
356
Lines 391-403 public void evaluateAll() { Link Here
391
	}
379
	}
392
380
393
    /** {@inheritDoc} */
381
    /** {@inheritDoc} */
394
    @Override
395
    public void setIgnoreMissingWorkbooks(boolean ignore){
382
    public void setIgnoreMissingWorkbooks(boolean ignore){
396
        _bookEvaluator.setIgnoreMissingWorkbooks(ignore);
383
        _bookEvaluator.setIgnoreMissingWorkbooks(ignore);
397
    }
384
    }
398
385
399
    /** {@inheritDoc} */
386
    /** {@inheritDoc} */
400
    @Override
401
    public void setDebugEvaluationOutputForNextEval(boolean value){
387
    public void setDebugEvaluationOutputForNextEval(boolean value){
402
        _bookEvaluator.setDebugEvaluationOutputForNextEval(value);
388
        _bookEvaluator.setDebugEvaluationOutputForNextEval(value);
403
    }
389
    }
(-)a/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java (-35 / +16 lines)
Lines 184-213 public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss Link Here
184
        this(InternalWorkbook.createWorkbook());
184
        this(InternalWorkbook.createWorkbook());
185
    }
185
    }
186
186
187
    private HSSFWorkbook(InternalWorkbook book) {
187
	private HSSFWorkbook(InternalWorkbook book) {
188
        super((DirectoryNode)null);
188
		super((DirectoryNode)null);
189
        workbook = book;
189
		workbook = book;
190
        _sheets = new ArrayList<HSSFSheet>(INITIAL_CAPACITY);
190
		_sheets = new ArrayList<HSSFSheet>(INITIAL_CAPACITY);
191
        names = new ArrayList<HSSFName>(INITIAL_CAPACITY);
191
		names = new ArrayList<HSSFName>(INITIAL_CAPACITY);
192
    }
192
	}
193
193
194
    /**
195
     * Given a POI POIFSFileSystem object, read in its Workbook along
196
     *  with all related nodes, and populate the high and low level models.
197
     * <p>This calls {@link #HSSFWorkbook(POIFSFileSystem, boolean)} with
198
     *  preserve nodes set to true. 
199
     * 
200
     * @see #HSSFWorkbook(POIFSFileSystem, boolean)
201
     * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
202
     * @exception IOException if the stream cannot be read
203
     */
204
    public HSSFWorkbook(POIFSFileSystem fs) throws IOException {
194
    public HSSFWorkbook(POIFSFileSystem fs) throws IOException {
205
        this(fs,true);
195
        this(fs,true);
206
    }
196
    }
207
197
208
    /**
198
    /**
209
     * Given a POI POIFSFileSystem object, read in its Workbook and populate 
199
     * given a POI POIFSFileSystem object, read in its Workbook and populate the high and
210
     * the high and low level models.  If you're reading in a workbook... start here!
200
     * low level models.  If you're reading in a workbook...start here.
211
     *
201
     *
212
     * @param fs the POI filesystem that contains the Workbook stream.
202
     * @param fs the POI filesystem that contains the Workbook stream.
213
     * @param preserveNodes whether to preseve other nodes, such as
203
     * @param preserveNodes whether to preseve other nodes, such as
Lines 218-224 public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss Link Here
218
     * @exception IOException if the stream cannot be read
208
     * @exception IOException if the stream cannot be read
219
     */
209
     */
220
    public HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)
210
    public HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)
221
            throws IOException {
211
            throws IOException
212
    {
222
        this(fs.getRoot(), fs, preserveNodes);
213
        this(fs.getRoot(), fs, preserveNodes);
223
    }
214
    }
224
215
Lines 347-370 public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss Link Here
347
        }
338
        }
348
    }
339
    }
349
340
350
    /**
341
     public HSSFWorkbook(InputStream s) throws IOException {
351
     * Companion to HSSFWorkbook(POIFSFileSystem), this constructs the 
342
         this(s,true);
352
     *  POI filesystem around your inputstream, including all nodes.
343
     }
353
     * <p>This calls {@link #HSSFWorkbook(InputStream, boolean)} with
354
     *  preserve nodes set to true. 
355
     *
356
     * @see #HSSFWorkbook(InputStream, boolean)
357
     * @see #HSSFWorkbook(POIFSFileSystem)
358
     * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
359
     * @exception IOException if the stream cannot be read
360
     */
361
    public HSSFWorkbook(InputStream s) throws IOException {
362
        this(s,true);
363
    }
364
344
365
    /**
345
    /**
366
     * Companion to HSSFWorkbook(POIFSFileSystem), this constructs the 
346
     * Companion to HSSFWorkbook(POIFSFileSystem), this constructs the POI filesystem around your
367
     * POI filesystem around your inputstream.
347
     * inputstream.
368
     *
348
     *
369
     * @param s  the POI filesystem that contains the Workbook stream.
349
     * @param s  the POI filesystem that contains the Workbook stream.
370
     * @param preserveNodes whether to preseve other nodes, such as
350
     * @param preserveNodes whether to preseve other nodes, such as
Lines 374-379 public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss Link Here
374
     * @see #HSSFWorkbook(POIFSFileSystem)
354
     * @see #HSSFWorkbook(POIFSFileSystem)
375
     * @exception IOException if the stream cannot be read
355
     * @exception IOException if the stream cannot be read
376
     */
356
     */
357
377
    public HSSFWorkbook(InputStream s, boolean preserveNodes)
358
    public HSSFWorkbook(InputStream s, boolean preserveNodes)
378
            throws IOException
359
            throws IOException
379
    {
360
    {
(-)a/src/java/org/apache/poi/poifs/crypt/CipherAlgorithm.java (-2 lines)
Lines 34-41 public enum CipherAlgorithm { Link Here
34
    // need bouncycastle provider for this one ...
34
    // need bouncycastle provider for this one ...
35
    // see http://stackoverflow.com/questions/4436397/3des-des-encryption-using-the-jce-generating-an-acceptable-key
35
    // see http://stackoverflow.com/questions/4436397/3des-des-encryption-using-the-jce-generating-an-acceptable-key
36
    des3_112(null, "DESede", -1, 128, new int[]{128}, 8, 32, "3DES_112", true),
36
    des3_112(null, "DESede", -1, 128, new int[]{128}, 8, 32, "3DES_112", true),
37
    // only for digital signatures
38
    rsa(null, "RSA", -1, 1024, new int[]{1024, 2048, 3072, 4096}, -1, -1, "", false);
39
    ;
37
    ;
40
    
38
    
41
    public final CipherProvider provider;
39
    public final CipherProvider provider;
(-)a/src/java/org/apache/poi/poifs/crypt/CryptoFunctions.java (-6 / +3 lines)
Lines 19-25 package org.apache.poi.poifs.crypt; Link Here
19
import java.nio.charset.Charset;
19
import java.nio.charset.Charset;
20
import java.security.DigestException;
20
import java.security.DigestException;
21
import java.security.GeneralSecurityException;
21
import java.security.GeneralSecurityException;
22
import java.security.Key;
23
import java.security.MessageDigest;
22
import java.security.MessageDigest;
24
import java.security.Provider;
23
import java.security.Provider;
25
import java.security.Security;
24
import java.security.Security;
Lines 196-202 public class CryptoFunctions { Link Here
196
     * @throws EncryptedDocumentException if the initialization failed or if an algorithm was specified,
195
     * @throws EncryptedDocumentException if the initialization failed or if an algorithm was specified,
197
     *   which depends on a missing bouncy castle provider 
196
     *   which depends on a missing bouncy castle provider 
198
     */
197
     */
199
    public static Cipher getCipher(Key key, CipherAlgorithm cipherAlgorithm, ChainingMode chain, byte[] vec, int cipherMode, String padding) {
198
    public static Cipher getCipher(SecretKey key, CipherAlgorithm cipherAlgorithm, ChainingMode chain, byte[] vec, int cipherMode, String padding) {
200
        int keySizeInBytes = key.getEncoded().length;
199
        int keySizeInBytes = key.getEncoded().length;
201
        if (padding == null) padding = "NoPadding";
200
        if (padding == null) padding = "NoPadding";
202
        
201
        
Lines 297-308 public class CryptoFunctions { Link Here
297
    }
296
    }
298
297
299
    @SuppressWarnings("unchecked")
298
    @SuppressWarnings("unchecked")
300
    public static void registerBouncyCastle() {
299
    private static void registerBouncyCastle() {
301
        if (Security.getProvider("BC") != null) return;
300
        if (Security.getProvider("BC") != null) return;
302
        try {
301
        try {
303
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
302
            Class<Provider> clazz = (Class<Provider>)Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
304
            String bcProviderName = "org.bouncycastle.jce.provider.BouncyCastleProvider";
305
            Class<Provider> clazz = (Class<Provider>)cl.loadClass(bcProviderName);
306
            Security.addProvider(clazz.newInstance());
303
            Security.addProvider(clazz.newInstance());
307
        } catch (Exception e) {
304
        } catch (Exception e) {
308
            throw new EncryptedDocumentException("Only the BouncyCastle provider supports your encryption settings - please add it to the classpath.");
305
            throw new EncryptedDocumentException("Only the BouncyCastle provider supports your encryption settings - please add it to the classpath.");
(-)a/src/java/org/apache/poi/poifs/crypt/HashAlgorithm.java (-2 lines)
Lines 33-40 public enum HashAlgorithm { Link Here
33
    ripemd128("RipeMD128",     -1, "RIPEMD-128", 16, "HMac-RipeMD128", true),
33
    ripemd128("RipeMD128",     -1, "RIPEMD-128", 16, "HMac-RipeMD128", true),
34
    ripemd160("RipeMD160",     -1, "RIPEMD-160", 20, "HMac-RipeMD160", true),
34
    ripemd160("RipeMD160",     -1, "RIPEMD-160", 20, "HMac-RipeMD160", true),
35
    whirlpool("Whirlpool",     -1,  "WHIRLPOOL", 64, "HMac-Whirlpool", true),
35
    whirlpool("Whirlpool",     -1,  "WHIRLPOOL", 64, "HMac-Whirlpool", true),
36
    // only for xml signing
37
    sha224   (  "SHA-224",     -1,     "SHA224", 28,     "HmacSHA224", true);
38
    ;
36
    ;
39
37
40
    public final String jceId;
38
    public final String jceId;
(-)a/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java (-9 / +1 lines)
Lines 139-153 public class StandardDecryptor extends Decryptor { Link Here
139
139
140
        _length = dis.readLong();
140
        _length = dis.readLong();
141
141
142
        // limit wrong calculated ole entries - (bug #57080)
142
        return new BoundedInputStream(new CipherInputStream(dis, getCipher(getSecretKey())), _length);
143
        // standard encryption always uses aes encoding, so blockSize is always 16 
144
        // http://stackoverflow.com/questions/3283787/size-of-data-after-aes-encryption
145
        int blockSize = info.getHeader().getCipherAlgorithm().blockSize;
146
        long cipherLen = (_length/blockSize + 1) * blockSize;
147
        Cipher cipher = getCipher(getSecretKey());
148
        
149
        InputStream boundedDis = new BoundedInputStream(dis, cipherLen);
150
        return new BoundedInputStream(new CipherInputStream(boundedDis, cipher), _length);
151
    }
143
    }
152
144
153
    public long getLength(){
145
    public long getLength(){
(-)a/src/java/org/apache/poi/poifs/property/DirectoryProperty.java (-7 / +13 lines)
Lines 18-30 Link Here
18
package org.apache.poi.poifs.property;
18
package org.apache.poi.poifs.property;
19
19
20
import java.io.IOException;
20
import java.io.IOException;
21
import java.util.ArrayList;
21
import java.util.*;
22
import java.util.Arrays;
23
import java.util.Comparator;
24
import java.util.HashSet;
25
import java.util.Iterator;
26
import java.util.List;
27
import java.util.Set;
28
22
29
/**
23
/**
30
 * Directory property
24
 * Directory property
Lines 124-129 public class DirectoryProperty extends Property implements Parent { // TODO - fi Link Here
124
    public static class PropertyComparator implements Comparator<Property> {
118
    public static class PropertyComparator implements Comparator<Property> {
125
119
126
        /**
120
        /**
121
         * Object equality, implemented as object identity
122
         *
123
         * @param o Object we're being compared to
124
         *
125
         * @return true if identical, else false
126
         */
127
        public boolean equals(Object o)
128
        {
129
            return this == o;
130
        }
131
132
        /**
127
         * compare method. Assumes both parameters are non-null
133
         * compare method. Assumes both parameters are non-null
128
         * instances of Property. One property is less than another if
134
         * instances of Property. One property is less than another if
129
         * its name is shorter than the other property's name. If the
135
         * its name is shorter than the other property's name. If the
(-)a/src/java/org/apache/poi/ss/formula/WorkbookEvaluator.java (-2 / +2 lines)
Lines 806-813 public final class WorkbookEvaluator { Link Here
806
     * Register a function in runtime.
806
     * Register a function in runtime.
807
     *
807
     *
808
     * @param name  the function name
808
     * @param name  the function name
809
     * @param func  the functoin to register
809
     * @param func  the function to register
810
     * @throws IllegalArgumentException if the function is unknown or already  registered.
810
     * @throws IllegalArgumentException If the function is unknown or already registered.
811
     * @since 3.8 beta6
811
     * @since 3.8 beta6
812
     */
812
     */
813
    public static void registerFunction(String name, Function func){
813
    public static void registerFunction(String name, Function func){
(-)a/src/java/org/apache/poi/ss/formula/atp/AnalysisToolPak.java (-2 / +1 lines)
Lines 28-34 import org.apache.poi.ss.formula.functions.Dec2Bin; Link Here
28
import org.apache.poi.ss.formula.functions.Dec2Hex;
28
import org.apache.poi.ss.formula.functions.Dec2Hex;
29
import org.apache.poi.ss.formula.functions.Delta;
29
import org.apache.poi.ss.formula.functions.Delta;
30
import org.apache.poi.ss.formula.functions.EDate;
30
import org.apache.poi.ss.formula.functions.EDate;
31
import org.apache.poi.ss.formula.functions.EOMonth;
32
import org.apache.poi.ss.formula.functions.FactDouble;
31
import org.apache.poi.ss.formula.functions.FactDouble;
33
import org.apache.poi.ss.formula.functions.FreeRefFunction;
32
import org.apache.poi.ss.formula.functions.FreeRefFunction;
34
import org.apache.poi.ss.formula.functions.Hex2Dec;
33
import org.apache.poi.ss.formula.functions.Hex2Dec;
Lines 118-124 public final class AnalysisToolPak implements UDFFinder { Link Here
118
        r(m, "DURATION", null);
117
        r(m, "DURATION", null);
119
        r(m, "EDATE", EDate.instance);
118
        r(m, "EDATE", EDate.instance);
120
        r(m, "EFFECT", null);
119
        r(m, "EFFECT", null);
121
        r(m, "EOMONTH", EOMonth.instance);
120
        r(m, "EOMONTH", null);
122
        r(m, "ERF", null);
121
        r(m, "ERF", null);
123
        r(m, "ERFC", null);
122
        r(m, "ERFC", null);
124
        r(m, "FACTDOUBLE", FactDouble.instance);
123
        r(m, "FACTDOUBLE", FactDouble.instance);
(-)a/src/java/org/apache/poi/ss/formula/eval/FunctionEval.java (-7 / +3 lines)
Lines 41-46 import org.apache.poi.ss.formula.functions.Days360; Link Here
41
import org.apache.poi.ss.formula.functions.Errortype;
41
import org.apache.poi.ss.formula.functions.Errortype;
42
import org.apache.poi.ss.formula.functions.Even;
42
import org.apache.poi.ss.formula.functions.Even;
43
import org.apache.poi.ss.formula.functions.FinanceFunction;
43
import org.apache.poi.ss.formula.functions.FinanceFunction;
44
import org.apache.poi.ss.formula.functions.Fixed;
44
import org.apache.poi.ss.formula.functions.Function;
45
import org.apache.poi.ss.formula.functions.Function;
45
import org.apache.poi.ss.formula.functions.Hlookup;
46
import org.apache.poi.ss.formula.functions.Hlookup;
46
import org.apache.poi.ss.formula.functions.Hyperlink;
47
import org.apache.poi.ss.formula.functions.Hyperlink;
Lines 133-139 public final class FunctionEval { Link Here
133
        retval[11] = new Npv();
134
        retval[11] = new Npv();
134
        retval[12] = AggregateFunction.STDEV;
135
        retval[12] = AggregateFunction.STDEV;
135
        retval[13] = NumericFunction.DOLLAR;
136
        retval[13] = NumericFunction.DOLLAR;
136
137
        retval[14] = new Fixed();
137
        retval[15] = NumericFunction.SIN;
138
        retval[15] = NumericFunction.SIN;
138
        retval[16] = NumericFunction.COS;
139
        retval[16] = NumericFunction.COS;
139
        retval[17] = NumericFunction.TAN;
140
        retval[17] = NumericFunction.TAN;
Lines 150-156 public final class FunctionEval { Link Here
150
        retval[28] = new Lookup();
151
        retval[28] = new Lookup();
151
        retval[29] = new Index();
152
        retval[29] = new Index();
152
        retval[30] = new Rept();
153
        retval[30] = new Rept();
153
154
        retval[31] = TextFunction.MID;
154
        retval[31] = TextFunction.MID;
155
        retval[32] = TextFunction.LEN;
155
        retval[32] = TextFunction.LEN;
156
        retval[33] = new Value();
156
        retval[33] = new Value();
Lines 168-177 public final class FunctionEval { Link Here
168
        retval[57] = FinanceFunction.FV;
168
        retval[57] = FinanceFunction.FV;
169
        retval[58] = FinanceFunction.NPER;
169
        retval[58] = FinanceFunction.NPER;
170
        retval[59] = FinanceFunction.PMT;
170
        retval[59] = FinanceFunction.PMT;
171
172
        retval[60] = new Rate();
171
        retval[60] = new Rate();
173
        retval[61] = new Mirr();
172
        retval[61] = new Mirr();
174
175
        retval[62] = new Irr();
173
        retval[62] = new Irr();
176
        retval[63] = NumericFunction.RAND;
174
        retval[63] = NumericFunction.RAND;
177
        retval[64] = new Match();
175
        retval[64] = new Match();
Lines 180-186 public final class FunctionEval { Link Here
180
        retval[67] = CalendarFieldFunction.DAY;
178
        retval[67] = CalendarFieldFunction.DAY;
181
        retval[68] = CalendarFieldFunction.MONTH;
179
        retval[68] = CalendarFieldFunction.MONTH;
182
        retval[69] = CalendarFieldFunction.YEAR;
180
        retval[69] = CalendarFieldFunction.YEAR;
183
184
        retval[70] = WeekdayFunc.instance;
181
        retval[70] = WeekdayFunc.instance;
185
        retval[71] = CalendarFieldFunction.HOUR;
182
        retval[71] = CalendarFieldFunction.HOUR;
186
        retval[72] = CalendarFieldFunction.MINUTE;
183
        retval[72] = CalendarFieldFunction.MINUTE;
Lines 207-213 public final class FunctionEval { Link Here
207
        retval[111] = TextFunction.CHAR;
204
        retval[111] = TextFunction.CHAR;
208
        retval[112] = TextFunction.LOWER;
205
        retval[112] = TextFunction.LOWER;
209
        retval[113] = TextFunction.UPPER;
206
        retval[113] = TextFunction.UPPER;
210
        retval[114] = TextFunction.PROPER;
207
211
        retval[115] = TextFunction.LEFT;
208
        retval[115] = TextFunction.LEFT;
212
        retval[116] = TextFunction.RIGHT;
209
        retval[116] = TextFunction.RIGHT;
213
        retval[117] = TextFunction.EXACT;
210
        retval[117] = TextFunction.EXACT;
Lines 293-299 public final class FunctionEval { Link Here
293
290
294
        retval[342] = NumericFunction.RADIANS;
291
        retval[342] = NumericFunction.RADIANS;
295
        retval[343] = NumericFunction.DEGREES;
292
        retval[343] = NumericFunction.DEGREES;
296
297
        retval[344] = new Subtotal();
293
        retval[344] = new Subtotal();
298
        retval[345] = new Sumif();
294
        retval[345] = new Sumif();
299
        retval[346] = new Countif();
295
        retval[346] = new Countif();
(-)a/src/java/org/apache/poi/ss/formula/functions/EOMonth.java (-81 lines)
Lines 1-81 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
package org.apache.poi.ss.formula.functions;
19
20
import java.util.Calendar;
21
import java.util.Date;
22
import java.util.GregorianCalendar;
23
24
import org.apache.poi.ss.formula.OperationEvaluationContext;
25
import org.apache.poi.ss.formula.eval.ErrorEval;
26
import org.apache.poi.ss.formula.eval.EvaluationException;
27
import org.apache.poi.ss.formula.eval.NumberEval;
28
import org.apache.poi.ss.formula.eval.ValueEval;
29
import org.apache.poi.ss.usermodel.DateUtil;
30
31
/**
32
 * Implementation for the Excel EOMONTH() function.<p/>
33
 * <p/>
34
 * EOMONTH() returns the date of the last day of a month..<p/>
35
 * <p/>
36
 * <b>Syntax</b>:<br/>
37
 * <b>EOMONTH</b>(<b>start_date</b>,<b>months</b>)<p/>
38
 * <p/>
39
 * <b>start_date</b> is the starting date of the calculation
40
 * <b>months</b> is the number of months to be added to <b>start_date</b>,
41
 * to give a new date. For this new date, <b>EOMONTH</b> returns the date of
42
 * the last day of the month. <b>months</b> may be positive (in the future),
43
 * zero or negative (in the past).
44
 */
45
public class EOMonth implements FreeRefFunction {
46
47
    public static final FreeRefFunction instance = new EOMonth();
48
49
    @Override
50
    public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {
51
        if (args.length != 2) {
52
            return ErrorEval.VALUE_INVALID;
53
        }
54
55
        try {
56
            double startDateAsNumber = NumericFunction.singleOperandEvaluate(args[0], ec.getRowIndex(), ec.getColumnIndex());
57
            int months = (int) NumericFunction.singleOperandEvaluate(args[1], ec.getRowIndex(), ec.getColumnIndex());
58
59
            // Excel treats date 0 as 1900-01-00; EOMONTH results in 1900-01-31
60
            if (startDateAsNumber >= 0.0 && startDateAsNumber < 1.0) {
61
                startDateAsNumber = 1.0;
62
            }
63
64
            Date startDate = DateUtil.getJavaDate(startDateAsNumber, false);
65
66
            Calendar cal = new GregorianCalendar();
67
            cal.setTime(startDate);
68
            cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
69
            cal.set(Calendar.MILLISECOND, 0);
70
71
            cal.add(Calendar.MONTH, months + 1);
72
            cal.set(Calendar.DAY_OF_MONTH, 1);
73
            cal.add(Calendar.DAY_OF_MONTH, -1);
74
75
            return new NumberEval(DateUtil.getExcelDate(cal.getTime()));
76
        } catch (EvaluationException e) {
77
            return e.getErrorEval();
78
        }
79
    }
80
81
}
(-)a/src/java/org/apache/poi/ss/formula/functions/Fixed.java (+106 lines)
Line 0 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
package org.apache.poi.ss.formula.functions;
19
20
import java.math.BigDecimal;
21
import java.math.RoundingMode;
22
import java.text.DecimalFormat;
23
import java.text.NumberFormat;
24
import java.util.Locale;
25
26
import org.apache.poi.ss.formula.eval.BoolEval;
27
import org.apache.poi.ss.formula.eval.ErrorEval;
28
import org.apache.poi.ss.formula.eval.EvaluationException;
29
import org.apache.poi.ss.formula.eval.NumberEval;
30
import org.apache.poi.ss.formula.eval.OperandResolver;
31
import org.apache.poi.ss.formula.eval.StringEval;
32
import org.apache.poi.ss.formula.eval.ValueEval;
33
34
public final class Fixed implements Function1Arg, Function2Arg, Function3Arg {
35
    @Override
36
    public ValueEval evaluate(
37
    		int srcRowIndex, int srcColumnIndex,
38
    		ValueEval arg0, ValueEval arg1, ValueEval arg2) {
39
        return fixed(arg0, arg1, arg2, srcRowIndex, srcColumnIndex);
40
    }
41
42
    @Override
43
    public ValueEval evaluate(
44
    		int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
45
        return fixed(arg0, arg1, BoolEval.FALSE, srcRowIndex, srcColumnIndex);
46
    }
47
48
    @Override
49
    public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) {
50
        return fixed(arg0, new NumberEval(2), BoolEval.FALSE, srcRowIndex, srcColumnIndex);
51
    }
52
53
    @Override
54
    public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
55
        switch (args.length) {
56
            case 1:
57
                return fixed(args[0], new NumberEval(2), BoolEval.FALSE,
58
                		srcRowIndex, srcColumnIndex);
59
            case 2:
60
                return fixed(args[0], args[1], BoolEval.FALSE,
61
                		srcRowIndex, srcColumnIndex);
62
            case 3:
63
                return fixed(args[0], args[1], args[2], srcRowIndex, srcColumnIndex);
64
        }
65
        return ErrorEval.VALUE_INVALID;
66
    }
67
    
68
    private ValueEval fixed(
69
    		ValueEval numberParam, ValueEval placesParam,
70
    		ValueEval skipThousandsSeparatorParam,
71
    		int srcRowIndex, int srcColumnIndex) {
72
        try {
73
            ValueEval numberValueEval =
74
            		OperandResolver.getSingleValue(
75
            		numberParam, srcRowIndex, srcColumnIndex);
76
            BigDecimal number = 
77
            		new BigDecimal(OperandResolver.coerceValueToDouble(numberValueEval));
78
            ValueEval placesValueEval =
79
            		OperandResolver.getSingleValue(
80
            		placesParam, srcRowIndex, srcColumnIndex);
81
            int places = OperandResolver.coerceValueToInt(placesValueEval);
82
            ValueEval skipThousandsSeparatorValueEval =
83
            		OperandResolver.getSingleValue(
84
            		skipThousandsSeparatorParam, srcRowIndex, srcColumnIndex);
85
            Boolean skipThousandsSeparator =
86
            		OperandResolver.coerceValueToBoolean(
87
            		skipThousandsSeparatorValueEval, false);
88
            
89
            // Round number to respective places.
90
            number = number.setScale(places, RoundingMode.HALF_UP);
91
            
92
            // Format number conditionally using a thousands separator.
93
            NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
94
            DecimalFormat formatter = (DecimalFormat)nf;
95
            formatter.setGroupingUsed(! skipThousandsSeparator);
96
            formatter.setMinimumFractionDigits(places >= 0 ? places : 0);
97
            formatter.setMaximumFractionDigits(places >= 0 ? places : 0);
98
            String numberString = formatter.format(number.doubleValue());
99
100
            // Return the result as a StringEval.
101
            return new StringEval(numberString);
102
        } catch (EvaluationException e) {
103
            return e.getErrorEval();
104
        }
105
    }
106
}
(-)a/src/java/org/apache/poi/ss/formula/functions/TextFunction.java (-28 lines)
Lines 17-24 Link Here
17
17
18
package org.apache.poi.ss.formula.functions;
18
package org.apache.poi.ss.formula.functions;
19
19
20
import java.util.regex.Pattern;
21
22
import org.apache.poi.ss.formula.eval.BoolEval;
20
import org.apache.poi.ss.formula.eval.BoolEval;
23
import org.apache.poi.ss.formula.eval.ErrorEval;
21
import org.apache.poi.ss.formula.eval.ErrorEval;
24
import org.apache.poi.ss.formula.eval.EvaluationException;
22
import org.apache.poi.ss.formula.eval.EvaluationException;
Lines 114-145 public abstract class TextFunction implements Function { Link Here
114
			return new StringEval(arg.toUpperCase());
112
			return new StringEval(arg.toUpperCase());
115
		}
113
		}
116
	};
114
	};
117
118
	/**
119
	 * Implementation of the PROPER function:
120
     * Normalizes all words (separated by non-word characters) by
121
     * making the first letter upper and the rest lower case.
122
	 */
123
	public static final Function PROPER = new SingleArgTextFunc() {
124
	    final Pattern nonAlphabeticPattern = Pattern.compile("\\P{IsL}");
125
		protected ValueEval evaluate(String text) {
126
			StringBuilder sb = new StringBuilder();
127
			boolean shouldMakeUppercase = true;
128
			String lowercaseText = text.toLowerCase();
129
			String uppercaseText = text.toUpperCase();
130
			for(int i = 0; i < text.length(); ++i) {
131
				if (shouldMakeUppercase) {
132
					sb.append(uppercaseText.charAt(i));
133
				}
134
				else {
135
					sb.append(lowercaseText.charAt(i));
136
				}
137
				shouldMakeUppercase = nonAlphabeticPattern.matcher(text.subSequence(i, i + 1)).matches();
138
			}
139
			return new StringEval(sb.toString());
140
		}
141
	};
142
143
	/**
115
	/**
144
	 * An implementation of the TRIM function:
116
	 * An implementation of the TRIM function:
145
	 * Removes leading and trailing spaces from value if evaluated operand
117
	 * Removes leading and trailing spaces from value if evaluated operand
(-)a/src/java/org/apache/poi/ss/formula/ptg/Ref2DPtgBase.java (-15 / +11 lines)
Lines 43-73 abstract class Ref2DPtgBase extends RefPtgBase { Link Here
43
		super(cr);
43
		super(cr);
44
	}
44
	}
45
45
46
	@Override
46
	public void write(LittleEndianOutput out) {
47
    public void write(LittleEndianOutput out) {
48
		out.writeByte(getSid() + getPtgClass());
47
		out.writeByte(getSid() + getPtgClass());
49
		writeCoordinates(out);
48
		writeCoordinates(out);
50
	}
49
	}
51
50
52
	@Override
51
	public final String toFormulaString() {
53
    public final String toFormulaString() {
54
		return formatReferenceAsString();
52
		return formatReferenceAsString();
55
	}
53
	}
56
54
57
	protected abstract byte getSid();
55
	protected abstract byte getSid();
58
56
59
	@Override
57
	public final int getSize() {
60
    public final int getSize() {
61
		return SIZE;
58
		return SIZE;
62
	}
59
	}
63
60
64
    @Override
61
	public final String toString() {
65
    public final String toString() {
62
		StringBuffer sb = new StringBuffer();
66
        StringBuffer sb = new StringBuffer();
63
		sb.append(getClass().getName());
67
        sb.append(getClass().getName());
64
		sb.append(" [");
68
        sb.append(" [");
65
		sb.append(formatReferenceAsString());
69
        sb.append(formatReferenceAsString());
66
		sb.append("]");
70
        sb.append("]");
67
		return sb.toString();
71
        return sb.toString();
68
	}
72
    }
73
}
69
}
(-)a/src/java/org/apache/poi/ss/formula/ptg/RefPtgBase.java (-2 / +1 lines)
Lines 111-118 public abstract class RefPtgBase extends OperandPtg { Link Here
111
		return cr.formatAsString();
111
		return cr.formatAsString();
112
	}
112
	}
113
113
114
	@Override
114
	public final byte getDefaultOperandClass() {
115
    public final byte getDefaultOperandClass() {
116
		return Ptg.CLASS_REF;
115
		return Ptg.CLASS_REF;
117
	}
116
	}
118
}
117
}
(-)a/src/java/org/apache/poi/ss/usermodel/Cell.java (-7 / +2 lines)
Lines 110-122 public interface Cell { Link Here
110
110
111
    /**
111
    /**
112
     * Set the cells type (numeric, formula or string).
112
     * Set the cells type (numeric, formula or string).
113
     * <p>If the cell currently contains a value, the value will
113
     * If the cell currently contains a value, the value will
114
     *  be converted to match the new type, if possible. Formatting
114
     *  be converted to match the new type, if possible.
115
     *  is generally lost in the process however.</p>
116
     * <p>If what you want to do is get a String value for your
117
     *  numeric cell, <i>stop!</i>. This is not the way to do it.
118
     *  Instead, for fetching the string value of a numeric or boolean
119
     *  or date cell, use {@link DataFormatter} instead.</p> 
120
     *
115
     *
121
     * @throws IllegalArgumentException if the specified cell type is invalid
116
     * @throws IllegalArgumentException if the specified cell type is invalid
122
     * @throws IllegalStateException if the current value cannot be converted to the new type
117
     * @throws IllegalStateException if the current value cannot be converted to the new type
(-)a/src/java/org/apache/poi/ss/usermodel/FormulaEvaluator.java (-3 / +1 lines)
Lines 95-103 public interface FormulaEvaluator { Link Here
95
     *  and the result. If you want the cell replaced with
95
     *  and the result. If you want the cell replaced with
96
     *  the result of the formula, use {@link #evaluateInCell(Cell)}
96
     *  the result of the formula, use {@link #evaluateInCell(Cell)}
97
     * @param cell The cell to evaluate
97
     * @param cell The cell to evaluate
98
     * @return The type of the formula result, i.e. -1 if the cell is not a formula, 
98
     * @return The type of the formula result (the cell's type remains as Cell.CELL_TYPE_FORMULA however)
99
     *      or one of Cell.CELL_TYPE_NUMERIC, Cell.CELL_TYPE_STRING, Cell.CELL_TYPE_BOOLEAN, Cell.CELL_TYPE_ERROR
100
     *      Note: the cell's type remains as Cell.CELL_TYPE_FORMULA however.
101
     */
99
     */
102
    int evaluateFormulaCell(Cell cell);
100
    int evaluateFormulaCell(Cell cell);
103
101
(-)a/src/java/org/apache/poi/ss/util/CellRangeAddress.java (-14 / +2 lines)
Lines 17-25 Link Here
17
17
18
package org.apache.poi.ss.util;
18
package org.apache.poi.ss.util;
19
19
20
import org.apache.poi.ss.formula.SheetNameFormatter;
20
import org.apache.poi.hssf.record.RecordInputStream;
21
import org.apache.poi.hssf.record.RecordInputStream;
21
import org.apache.poi.hssf.record.SelectionRecord;
22
import org.apache.poi.hssf.record.SelectionRecord;
22
import org.apache.poi.ss.formula.SheetNameFormatter;
23
import org.apache.poi.util.LittleEndianByteArrayOutputStream;
23
import org.apache.poi.util.LittleEndianByteArrayOutputStream;
24
import org.apache.poi.util.LittleEndianOutput;
24
import org.apache.poi.util.LittleEndianOutput;
25
25
Lines 38-63 public class CellRangeAddress extends CellRangeAddressBase { Link Here
38
	 */
38
	 */
39
	public static final int ENCODED_SIZE = 8;
39
	public static final int ENCODED_SIZE = 8;
40
40
41
	/**
42
	 * Creates new cell range. Indexes are zero-based.
43
	 * 
44
	 * @param firstRow Index of first row
45
	 * @param lastRow Index of last row (inclusive), must be equal to or larger than {@code firstRow}
46
	 * @param firstCol Index of first column
47
	 * @param lastCol Index of last column (inclusive), must be equal to or larger than {@code firstCol}
48
	 */
49
	public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) {
41
	public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) {
50
		super(firstRow, lastRow, firstCol, lastCol);
42
		super(firstRow, lastRow, firstCol, lastCol);
51
		
52
		if (lastRow < firstRow || lastCol < firstCol)
53
		    throw new IllegalArgumentException("lastRow < firstRow || lastCol < firstCol");
54
	}
43
	}
55
44
56
	/**
45
	/**
57
	 * @deprecated use {@link #serialize(LittleEndianOutput)}
46
	 * @deprecated use {@link #serialize(LittleEndianOutput)}
58
	 */
47
	 */
59
	@Deprecated
48
	public int serialize(int offset, byte[] data) {
60
    public int serialize(int offset, byte[] data) {
61
		serialize(new LittleEndianByteArrayOutputStream(data, offset, ENCODED_SIZE));
49
		serialize(new LittleEndianByteArrayOutputStream(data, offset, ENCODED_SIZE));
62
		return ENCODED_SIZE;
50
		return ENCODED_SIZE;
63
	}
51
	}
(-)a/src/java/org/apache/poi/ss/util/SheetUtil.java (-37 lines)
Lines 293-333 public class SheetUtil { Link Here
293
        return false;
293
        return false;
294
    }
294
    }
295
295
296
    /**
297
     * Return the cell, taking account of merged regions. Allows you to find the
298
     *  cell who's contents are shown in a given position in the sheet.
299
     * 
300
     * <p>If the cell at the given co-ordinates is a merged cell, this will
301
     *  return the primary (top-left) most cell of the merged region.
302
     * <p>If the cell at the given co-ordinates is not in a merged region,
303
     *  then will return the cell itself.
304
     * <p>If there is no cell defined at the given co-ordinates, will return
305
     *  null.
306
     */
307
    public static Cell getCellWithMerges(Sheet sheet, int rowIx, int colIx) {
308
        Row r = sheet.getRow(rowIx);
309
        if (r != null) {
310
            Cell c = r.getCell(colIx);
311
            if (c != null) {
312
                // Normal, non-merged cell
313
                return c;
314
            }
315
        }
316
        
317
        for (int mr=0; mr<sheet.getNumMergedRegions(); mr++) {
318
            CellRangeAddress mergedRegion = sheet.getMergedRegion(mr);
319
            if (mergedRegion.isInRange(rowIx, colIx)) {
320
                // The cell wanted is in this merged range
321
                // Return the primary (top-left) cell for the range
322
                r = sheet.getRow(mergedRegion.getFirstRow());
323
                if (r != null) {
324
                    return r.getCell(mergedRegion.getFirstColumn());
325
                }
326
            }
327
        }
328
        
329
        // If we get here, then the cell isn't defined, and doesn't
330
        //  live within any merged regions
331
        return null;
332
    }
333
}
296
}
(-)a/src/java/org/apache/poi/ss/util/WorkbookUtil.java (-10 lines)
Lines 124-130 public class WorkbookUtil { Link Here
124
     * </p>
124
     * </p>
125
     *
125
     *
126
     * @param sheetName the name to validate
126
     * @param sheetName the name to validate
127
     * @throws IllegalArgumentException if validation fails
128
     */
127
     */
129
    public static void validateSheetName(String sheetName) {
128
    public static void validateSheetName(String sheetName) {
130
        if (sheetName == null) {
129
        if (sheetName == null) {
Lines 161-175 public class WorkbookUtil { Link Here
161
    }
160
    }
162
161
163
162
164
    /**
165
     * Validates sheet state
166
     *
167
     * @param state the state to validate
168
     * @throws IllegalArgumentException if state is not one of
169
     *      {@link Workbook#SHEET_STATE_VISIBLE},
170
     *      {@link Workbook#SHEET_STATE_HIDDEN} or
171
     *      {@link Workbook#SHEET_STATE_VERY_HIDDEN}
172
     */
173
    public static void validateSheetState(int state) {
163
    public static void validateSheetState(int state) {
174
        switch(state){
164
        switch(state){
175
            case Workbook.SHEET_STATE_VISIBLE: break;
165
            case Workbook.SHEET_STATE_VISIBLE: break;
(-)a/src/java/org/apache/poi/util/LittleEndianOutputStream.java (-14 / +7 lines)
Lines 30-37 public final class LittleEndianOutputStream extends FilterOutputStream implement Link Here
30
		super(out);
30
		super(out);
31
	}
31
	}
32
32
33
	@Override
33
	public void writeByte(int v) {
34
    public void writeByte(int v) {
35
		try {
34
		try {
36
			out.write(v);
35
			out.write(v);
37
		} catch (IOException e) {
36
		} catch (IOException e) {
Lines 39-51 public final class LittleEndianOutputStream extends FilterOutputStream implement Link Here
39
		}
38
		}
40
	}
39
	}
41
40
42
	@Override
41
	public void writeDouble(double v) {
43
    public void writeDouble(double v) {
44
		writeLong(Double.doubleToLongBits(v));
42
		writeLong(Double.doubleToLongBits(v));
45
	}
43
	}
46
44
47
	@Override
45
	public void writeInt(int v) {
48
    public void writeInt(int v) {
49
		int b3 = (v >>> 24) & 0xFF;
46
		int b3 = (v >>> 24) & 0xFF;
50
		int b2 = (v >>> 16) & 0xFF;
47
		int b2 = (v >>> 16) & 0xFF;
51
		int b1 = (v >>>  8) & 0xFF;
48
		int b1 = (v >>>  8) & 0xFF;
Lines 60-73 public final class LittleEndianOutputStream extends FilterOutputStream implement Link Here
60
		}
57
		}
61
	}
58
	}
62
59
63
	@Override
60
	public void writeLong(long v) {
64
    public void writeLong(long v) {
65
		writeInt((int)(v >>  0));
61
		writeInt((int)(v >>  0));
66
		writeInt((int)(v >> 32));
62
		writeInt((int)(v >> 32));
67
	}
63
	}
68
64
69
	@Override
65
	public void writeShort(int v) {
70
    public void writeShort(int v) {
71
		int b1 = (v >>>  8) & 0xFF;
66
		int b1 = (v >>>  8) & 0xFF;
72
		int b0 = (v >>>  0) & 0xFF;
67
		int b0 = (v >>>  0) & 0xFF;
73
		try {
68
		try {
Lines 77-84 public final class LittleEndianOutputStream extends FilterOutputStream implement Link Here
77
			throw new RuntimeException(e);
72
			throw new RuntimeException(e);
78
		}
73
		}
79
	}
74
	}
80
	@Override
75
	public void write(byte[] b) {
81
    public void write(byte[] b) {
82
		// suppress IOException for interface method
76
		// suppress IOException for interface method
83
		try {
77
		try {
84
			super.write(b);
78
			super.write(b);
Lines 86-93 public final class LittleEndianOutputStream extends FilterOutputStream implement Link Here
86
			throw new RuntimeException(e);
80
			throw new RuntimeException(e);
87
		}
81
		}
88
	}
82
	}
89
	@Override
83
	public void write(byte[] b, int off, int len) {
90
    public void write(byte[] b, int off, int len) {
91
		// suppress IOException for interface method
84
		// suppress IOException for interface method
92
		try {
85
		try {
93
			super.write(b, off, len);
86
			super.write(b, off, len);
(-)a/src/ooxml/java/org/apache/poi/POIXMLRelation.java (-11 / +2 lines)
Lines 110-127 public abstract class POIXMLRelation { Link Here
110
        }
110
        }
111
        return _defaultName.replace("#", Integer.toString(index));
111
        return _defaultName.replace("#", Integer.toString(index));
112
    }
112
    }
113
    
113
114
    /**
115
     * Returns the index of the filename within the package for the given part.
116
     *  e.g. 4 for /xl/comments4.xml
117
     */
118
    public Integer getFileNameIndex(POIXMLDocumentPart part) {
119
        String regex = _defaultName.replace("#", "(\\d+)");
120
        return Integer.parseInt(part.getPackageRelationship().getTargetURI().getPath().replaceAll(regex, "$1"));
121
    }
122
    
123
    /**
114
    /**
124
     * Return type of the object used to construct instances of this relationship
115
     * Return type of the obejct used to construct instances of this relationship
125
     *
116
     *
126
     * @return the class of the object used to construct instances of this relation
117
     * @return the class of the object used to construct instances of this relation
127
     */
118
     */
(-)a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationship.java (+2 lines)
Lines 182-187 public final class PackageRelationship { Link Here
182
	}
182
	}
183
183
184
	/**
184
	/**
185
	 * public URI getSourceUri(){ }
186
	 *
185
	 * @return the targetMode
187
	 * @return the targetMode
186
	 */
188
	 */
187
	public TargetMode getTargetMode() {
189
	public TargetMode getTargetMode() {
(-)a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationshipCollection.java (-1 / +1 lines)
Lines 307-313 public final class PackageRelationshipCollection implements Link Here
307
     * @throws InvalidFormatException
307
     * @throws InvalidFormatException
308
     *             Throws if the relationship part is invalid.
308
     *             Throws if the relationship part is invalid.
309
     */
309
     */
310
    public void parseRelationshipsPart(PackagePart relPart)
310
    private void parseRelationshipsPart(PackagePart relPart)
311
            throws InvalidFormatException {
311
            throws InvalidFormatException {
312
        try {
312
        try {
313
            logger.log(POILogger.DEBUG, "Parsing relationship: " + relPart.getPartName());
313
            logger.log(POILogger.DEBUG, "Parsing relationship: " + relPart.getPartName());
(-)a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentTypeManager.java (-5 / +6 lines)
Lines 145-154 public abstract class ContentTypeManager { Link Here
145
	 * </p>
145
	 * </p>
146
	 */
146
	 */
147
	public void addContentType(PackagePartName partName, String contentType) {
147
	public void addContentType(PackagePartName partName, String contentType) {
148
		boolean defaultCTExists = this.defaultContentType.containsValue(contentType);
148
		boolean defaultCTExists = false;
149
		String extension = partName.getExtension().toLowerCase();
149
		String extension = partName.getExtension().toLowerCase();
150
		if ((extension.length() == 0)
150
		if ((extension.length() == 0)
151
				|| (this.defaultContentType.containsKey(extension) && !defaultCTExists))
151
				|| (this.defaultContentType.containsKey(extension) && !(defaultCTExists = this.defaultContentType
152
						.containsValue(contentType))))
152
			this.addOverrideContentType(partName, contentType);
153
			this.addOverrideContentType(partName, contentType);
153
		else if (!defaultCTExists)
154
		else if (!defaultCTExists)
154
			this.addDefaultContentType(extension, contentType);
155
			this.addDefaultContentType(extension, contentType);
Lines 444-457 public abstract class ContentTypeManager { Link Here
444
	 */
445
	 */
445
	private void appendSpecificTypes(Element root,
446
	private void appendSpecificTypes(Element root,
446
			Entry<PackagePartName, String> entry) {
447
			Entry<PackagePartName, String> entry) {
447
        Element specificType = root.getOwnerDocument().createElementNS(TYPES_NAMESPACE_URI, OVERRIDE_TAG_NAME);
448
        Element specificType = root.getOwnerDocument().createElement(OVERRIDE_TAG_NAME);
448
        specificType.setAttribute(PART_NAME_ATTRIBUTE_NAME, entry.getKey().getName());
449
        specificType.setAttribute(PART_NAME_ATTRIBUTE_NAME, entry.getKey().getName());
449
        specificType.setAttribute(CONTENT_TYPE_ATTRIBUTE_NAME, entry.getValue());
450
        specificType.setAttribute(CONTENT_TYPE_ATTRIBUTE_NAME, entry.getValue());
450
        root.appendChild(specificType);
451
        root.appendChild(specificType);
451
	}
452
	}
452
453
453
	/**
454
	/**
454
	 * Use to append default types XML elements, use by the save() method.
455
	 * Use to append default types XML elements, use by the save() metid.
455
	 *
456
	 *
456
	 * @param root
457
	 * @param root
457
	 *            XML parent element use to append this default type element.
458
	 *            XML parent element use to append this default type element.
Lines 460-466 public abstract class ContentTypeManager { Link Here
460
	 * @see #save(java.io.OutputStream)
461
	 * @see #save(java.io.OutputStream)
461
	 */
462
	 */
462
	private void appendDefaultType(Element root, Entry<String, String> entry) {
463
	private void appendDefaultType(Element root, Entry<String, String> entry) {
463
        Element defaultType = root.getOwnerDocument().createElementNS(TYPES_NAMESPACE_URI, DEFAULT_TAG_NAME);
464
        Element defaultType = root.getOwnerDocument().createElement(DEFAULT_TAG_NAME);
464
        defaultType.setAttribute(EXTENSION_ATTRIBUTE_NAME, entry.getKey());
465
        defaultType.setAttribute(EXTENSION_ATTRIBUTE_NAME, entry.getKey());
465
        defaultType.setAttribute(CONTENT_TYPE_ATTRIBUTE_NAME, entry.getValue());
466
        defaultType.setAttribute(CONTENT_TYPE_ATTRIBUTE_NAME, entry.getValue());
466
        root.appendChild(defaultType);
467
        root.appendChild(defaultType);
(-)a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.java (-2 / +2 lines)
Lines 36-43 import org.apache.poi.openxml4j.opc.TargetMode; Link Here
36
import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
36
import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
37
import org.apache.poi.openxml4j.opc.internal.ZipHelper;
37
import org.apache.poi.openxml4j.opc.internal.ZipHelper;
38
import org.apache.poi.util.DocumentHelper;
38
import org.apache.poi.util.DocumentHelper;
39
import org.apache.poi.util.POILogFactory;
40
import org.apache.poi.util.POILogger;
39
import org.apache.poi.util.POILogger;
40
import org.apache.poi.util.POILogFactory;
41
import org.w3c.dom.Document;
41
import org.w3c.dom.Document;
42
import org.w3c.dom.Element;
42
import org.w3c.dom.Element;
43
43
Lines 134-140 public final class ZipPartMarshaller implements PartMarshaller { Link Here
134
134
135
		for (PackageRelationship rel : rels) {
135
		for (PackageRelationship rel : rels) {
136
			// the relationship element
136
			// the relationship element
137
            Element relElem = xmlOutDoc.createElementNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIP_TAG_NAME);
137
            Element relElem = xmlOutDoc.createElement(PackageRelationship.RELATIONSHIP_TAG_NAME);
138
            root.appendChild(relElem);
138
            root.appendChild(relElem);
139
139
140
			// the relationship ID
140
			// the relationship ID
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/CertificateSecurityException.java (-38 lines)
Lines 1-38 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
/* ====================================================================
19
   This product contains an ASLv2 licensed version of the OOXML signer
20
   package from the eID Applet project
21
   http://code.google.com/p/eid-applet/source/browse/trunk/README.txt  
22
   Copyright (C) 2008-2014 FedICT.
23
   ================================================================= */ 
24
25
package org.apache.poi.poifs.crypt.dsig;
26
27
/**
28
 * Exception thrown in case there is something wrong with the incoming eID
29
 * certificate.
30
 * 
31
 * @author Frank Cornelis
32
 * 
33
 */
34
public class CertificateSecurityException extends SecurityException {
35
36
    private static final long serialVersionUID = 1L;
37
38
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/DigestInfo.java (-56 lines)
Lines 1-56 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
/* ====================================================================
19
   This product contains an ASLv2 licensed version of the OOXML signer
20
   package from the eID Applet project
21
   http://code.google.com/p/eid-applet/source/browse/trunk/README.txt  
22
   Copyright (C) 2008-2014 FedICT.
23
   ================================================================= */ 
24
25
package org.apache.poi.poifs.crypt.dsig;
26
27
import java.io.Serializable;
28
29
import org.apache.poi.poifs.crypt.HashAlgorithm;
30
31
/**
32
 * Digest Information data transfer class.
33
 */
34
public class DigestInfo implements Serializable {
35
36
    private static final long serialVersionUID = 1L;
37
38
    /**
39
     * Main constructor.
40
     * 
41
     * @param digestValue
42
     * @param hashAlgo
43
     * @param description
44
     */
45
    public DigestInfo(byte[] digestValue, HashAlgorithm hashAlgo, String description) {
46
        this.digestValue = digestValue;
47
        this.hashAlgo = hashAlgo;
48
        this.description = description;
49
    }
50
51
    public final byte[] digestValue;
52
53
    public final String description;
54
55
    public final HashAlgorithm hashAlgo;
56
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/ExpiredCertificateSecurityException.java (-38 lines)
Lines 1-38 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
/* ====================================================================
19
   This product contains an ASLv2 licensed version of the OOXML signer
20
   package from the eID Applet project
21
   http://code.google.com/p/eid-applet/source/browse/trunk/README.txt  
22
   Copyright (C) 2008-2014 FedICT.
23
   ================================================================= */ 
24
25
package org.apache.poi.poifs.crypt.dsig;
26
27
/**
28
 * Exception thrown in case the incoming eID certificate is expired.
29
 * 
30
 * @author Frank Cornelis
31
 * 
32
 */
33
public class ExpiredCertificateSecurityException extends
34
        CertificateSecurityException {
35
36
    private static final long serialVersionUID = 1L;
37
38
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/KeyInfoKeySelector.java (-103 lines)
Lines 1-103 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
/* ====================================================================
19
   This product contains an ASLv2 licensed version of the OOXML signer
20
   package from the eID Applet project
21
   http://code.google.com/p/eid-applet/source/browse/trunk/README.txt  
22
   Copyright (C) 2008-2014 FedICT.
23
   ================================================================= */ 
24
25
package org.apache.poi.poifs.crypt.dsig;
26
27
import java.security.Key;
28
import java.security.cert.X509Certificate;
29
import java.util.ArrayList;
30
import java.util.List;
31
32
import javax.xml.crypto.AlgorithmMethod;
33
import javax.xml.crypto.KeySelector;
34
import javax.xml.crypto.KeySelectorException;
35
import javax.xml.crypto.KeySelectorResult;
36
import javax.xml.crypto.XMLCryptoContext;
37
import javax.xml.crypto.XMLStructure;
38
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
39
import javax.xml.crypto.dsig.keyinfo.X509Data;
40
41
import org.apache.poi.util.POILogFactory;
42
import org.apache.poi.util.POILogger;
43
44
/**
45
 * JSR105 key selector implementation using the ds:KeyInfo data of the signature
46
 * itself.
47
 */
48
public class KeyInfoKeySelector extends KeySelector implements KeySelectorResult {
49
50
    private static final POILogger LOG = POILogFactory.getLogger(KeyInfoKeySelector.class);
51
52
    private List<X509Certificate> certChain = new ArrayList<X509Certificate>();
53
54
    @SuppressWarnings("unchecked")
55
    @Override
56
    public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException {
57
        LOG.log(POILogger.DEBUG, "select key");
58
        if (null == keyInfo) {
59
            throw new KeySelectorException("no ds:KeyInfo present");
60
        }
61
        List<XMLStructure> keyInfoContent = keyInfo.getContent();
62
        certChain.clear();
63
        for (XMLStructure keyInfoStructure : keyInfoContent) {
64
            if (!(keyInfoStructure instanceof X509Data)) {
65
                continue;
66
            }
67
            X509Data x509Data = (X509Data) keyInfoStructure;
68
            List<Object> x509DataList = x509Data.getContent();
69
            for (Object x509DataObject : x509DataList) {
70
                if (!(x509DataObject instanceof X509Certificate)) {
71
                    continue;
72
                }
73
                X509Certificate certificate = (X509Certificate) x509DataObject;
74
                LOG.log(POILogger.DEBUG, "certificate", certificate.getSubjectX500Principal());
75
                certChain.add(certificate);
76
            }
77
        }
78
        if (certChain.isEmpty()) {
79
            throw new KeySelectorException("No key found!");
80
        }
81
        return this;
82
    }
83
84
    public Key getKey() {
85
        // The first certificate is presumably the signer.
86
        return certChain.isEmpty() ? null : certChain.get(0).getPublicKey();
87
    }
88
89
    /**
90
     * Gives back the X509 certificate used during the last signature
91
     * verification operation.
92
     * 
93
     * @return the certificate which was used to sign the xml content
94
     */
95
    public X509Certificate getSigner() {
96
        // The first certificate is presumably the signer.
97
        return certChain.isEmpty() ? null : certChain.get(0);
98
    }
99
    
100
    public List<X509Certificate> getCertChain() {
101
        return certChain;
102
    }
103
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java (-111 lines)
Lines 1-111 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
/* ====================================================================
19
   This product contains an ASLv2 licensed version of the OOXML signer
20
   package from the eID Applet project
21
   http://code.google.com/p/eid-applet/source/browse/trunk/README.txt  
22
   Copyright (C) 2008-2014 FedICT.
23
   ================================================================= */ 
24
25
package org.apache.poi.poifs.crypt.dsig;
26
27
import java.io.IOException;
28
import java.net.URI;
29
import java.net.URISyntaxException;
30
31
import javax.xml.crypto.Data;
32
import javax.xml.crypto.OctetStreamData;
33
import javax.xml.crypto.URIDereferencer;
34
import javax.xml.crypto.URIReference;
35
import javax.xml.crypto.URIReferenceException;
36
import javax.xml.crypto.XMLCryptoContext;
37
38
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
39
import org.apache.poi.openxml4j.opc.PackagePart;
40
import org.apache.poi.openxml4j.opc.PackagePartName;
41
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
42
import org.apache.poi.poifs.crypt.dsig.SignatureConfig.SignatureConfigurable;
43
import org.apache.poi.util.POILogFactory;
44
import org.apache.poi.util.POILogger;
45
46
/**
47
 * JSR105 URI dereferencer for Office Open XML documents.
48
 */
49
public class OOXMLURIDereferencer implements URIDereferencer, SignatureConfigurable {
50
51
    private static final POILogger LOG = POILogFactory.getLogger(OOXMLURIDereferencer.class);
52
53
    private SignatureConfig signatureConfig;
54
    private URIDereferencer baseUriDereferencer;
55
56
    public void setSignatureConfig(SignatureConfig signatureConfig) {
57
        this.signatureConfig = signatureConfig;
58
    }
59
60
    public Data dereference(URIReference uriReference, XMLCryptoContext context) throws URIReferenceException {
61
        if (baseUriDereferencer == null) {
62
            baseUriDereferencer = signatureConfig.getSignatureFactory().getURIDereferencer();
63
        }
64
        
65
        if (null == uriReference) {
66
            throw new NullPointerException("URIReference cannot be null");
67
        }
68
        if (null == context) {
69
            throw new NullPointerException("XMLCrytoContext cannot be null");
70
        }
71
72
        URI uri;
73
        try {
74
            uri = new URI(uriReference.getURI());
75
        } catch (URISyntaxException e) {
76
            throw new URIReferenceException("could not URL decode the uri: "+uriReference.getURI(), e);
77
        }
78
79
        PackagePart part = findPart(uri);
80
        if (part == null) {
81
            LOG.log(POILogger.DEBUG, "cannot resolve, delegating to base DOM URI dereferencer", uri);
82
            return this.baseUriDereferencer.dereference(uriReference, context);
83
        }
84
        
85
        try {
86
            return new OctetStreamData(part.getInputStream(), uri.toString(), null);
87
        } catch (IOException e) {
88
            throw new URIReferenceException("I/O error: " + e.getMessage(), e);
89
        }
90
    }
91
92
    private PackagePart findPart(URI uri) {
93
        LOG.log(POILogger.DEBUG, "dereference", uri);
94
95
        String path = uri.getPath();
96
        if (path == null || "".equals(path)) {
97
            LOG.log(POILogger.DEBUG, "illegal part name (expected)", uri);
98
            return null;
99
        }
100
        
101
        PackagePartName ppn;
102
        try {
103
            ppn = PackagingURIHelper.createPartName(path);
104
        } catch (InvalidFormatException e) {
105
            LOG.log(POILogger.WARN, "illegal part name (not expected)", uri);
106
            return null;
107
        }
108
        
109
        return signatureConfig.getOpcPackage().getPart(ppn);
110
    }
111
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/RevokedCertificateSecurityException.java (-38 lines)
Lines 1-38 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
/* ====================================================================
19
   This product contains an ASLv2 licensed version of the OOXML signer
20
   package from the eID Applet project
21
   http://code.google.com/p/eid-applet/source/browse/trunk/README.txt  
22
   Copyright (C) 2008-2014 FedICT.
23
   ================================================================= */ 
24
25
package org.apache.poi.poifs.crypt.dsig;
26
27
/**
28
 * Exception thrown in case the incoming eID certificate has been revoked.
29
 * 
30
 * @author Frank Cornelis
31
 * 
32
 */
33
public class RevokedCertificateSecurityException extends
34
        CertificateSecurityException {
35
36
    private static final long serialVersionUID = 1L;
37
38
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureConfig.java (-897 lines)
Lines 1-897 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
package org.apache.poi.poifs.crypt.dsig;
19
20
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.OO_DIGSIG_NS;
21
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XADES_132_NS;
22
23
import java.security.PrivateKey;
24
import java.security.Provider;
25
import java.security.cert.X509Certificate;
26
import java.util.ArrayList;
27
import java.util.Date;
28
import java.util.HashMap;
29
import java.util.List;
30
import java.util.Map;
31
import java.util.UUID;
32
33
import javax.xml.crypto.URIDereferencer;
34
import javax.xml.crypto.dsig.CanonicalizationMethod;
35
import javax.xml.crypto.dsig.DigestMethod;
36
import javax.xml.crypto.dsig.XMLSignatureFactory;
37
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
38
39
import org.apache.poi.EncryptedDocumentException;
40
import org.apache.poi.openxml4j.opc.OPCPackage;
41
import org.apache.poi.poifs.crypt.HashAlgorithm;
42
import org.apache.poi.poifs.crypt.dsig.facets.KeyInfoSignatureFacet;
43
import org.apache.poi.poifs.crypt.dsig.facets.OOXMLSignatureFacet;
44
import org.apache.poi.poifs.crypt.dsig.facets.Office2010SignatureFacet;
45
import org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet;
46
import org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet;
47
import org.apache.poi.poifs.crypt.dsig.services.RevocationDataService;
48
import org.apache.poi.poifs.crypt.dsig.services.SignaturePolicyService;
49
import org.apache.poi.poifs.crypt.dsig.services.TSPTimeStampService;
50
import org.apache.poi.poifs.crypt.dsig.services.TimeStampService;
51
import org.apache.poi.poifs.crypt.dsig.services.TimeStampServiceValidator;
52
import org.apache.poi.util.POILogFactory;
53
import org.apache.poi.util.POILogger;
54
import org.apache.xml.security.signature.XMLSignature;
55
import org.w3c.dom.events.EventListener;
56
57
/**
58
 * This class bundles the configuration options used for the existing
59
 * signature facets.
60
 * Apart of the thread local members (e.g. opc-package) most values will probably be constant, so
61
 * it might be configured centrally (e.g. by spring) 
62
 */
63
public class SignatureConfig {
64
65
    private static final POILogger LOG = POILogFactory.getLogger(SignatureConfig.class);
66
    
67
    public static interface SignatureConfigurable {
68
        void setSignatureConfig(SignatureConfig signatureConfig);        
69
    }
70
71
    private ThreadLocal<OPCPackage> opcPackage = new ThreadLocal<OPCPackage>();
72
    private ThreadLocal<XMLSignatureFactory> signatureFactory = new ThreadLocal<XMLSignatureFactory>();
73
    private ThreadLocal<KeyInfoFactory> keyInfoFactory = new ThreadLocal<KeyInfoFactory>();
74
    private ThreadLocal<Provider> provider = new ThreadLocal<Provider>();
75
    
76
    private List<SignatureFacet> signatureFacets = new ArrayList<SignatureFacet>();
77
    private HashAlgorithm digestAlgo = HashAlgorithm.sha1;
78
    private Date executionTime = new Date();
79
    private PrivateKey key;
80
    private List<X509Certificate> signingCertificateChain;
81
82
    /**
83
     * the optional signature policy service used for XAdES-EPES.
84
     */
85
    private SignaturePolicyService signaturePolicyService;
86
    private URIDereferencer uriDereferencer = null;
87
    private String canonicalizationMethod = CanonicalizationMethod.INCLUSIVE;
88
    
89
    private boolean includeEntireCertificateChain = true;
90
    private boolean includeIssuerSerial = false;
91
    private boolean includeKeyValue = false;
92
    
93
    /**
94
     * the time-stamp service used for XAdES-T and XAdES-X.
95
     */
96
    private TimeStampService tspService = new TSPTimeStampService();
97
    /**
98
     * timestamp service provider URL
99
     */
100
    private String tspUrl;
101
    private boolean tspOldProtocol = false;
102
    /**
103
     * if not defined, it's the same as the main digest
104
     */
105
    private HashAlgorithm tspDigestAlgo = null;
106
    private String tspUser;
107
    private String tspPass;
108
    private TimeStampServiceValidator tspValidator;
109
    /**
110
     * the optional TSP request policy OID.
111
     */
112
    private String tspRequestPolicy = "1.3.6.1.4.1.13762.3";
113
    private String userAgent = "POI XmlSign Service TSP Client";
114
    private String proxyUrl;
115
    
116
    /**
117
     * the optional revocation data service used for XAdES-C and XAdES-X-L.
118
     * When <code>null</code> the signature will be limited to XAdES-T only.
119
     */
120
    private RevocationDataService revocationDataService;
121
    /**
122
     * if not defined, it's the same as the main digest
123
     */
124
    private HashAlgorithm xadesDigestAlgo = null;
125
    private String xadesRole = null;
126
    private String xadesSignatureId = "idSignedProperties";
127
    private boolean xadesSignaturePolicyImplied = true;
128
    private String xadesCanonicalizationMethod = CanonicalizationMethod.EXCLUSIVE;
129
130
    /**
131
     * Work-around for Office 2010 IssuerName encoding.
132
     */
133
    private boolean xadesIssuerNameNoReverseOrder = true;
134
135
    /**
136
     * The signature Id attribute value used to create the XML signature. A
137
     * <code>null</code> value will trigger an automatically generated signature Id.
138
     */
139
    private String packageSignatureId = "idPackageSignature";
140
    
141
    /**
142
     * Gives back the human-readable description of what the citizen will be
143
     * signing. The default value is "Office OpenXML Document".
144
     */
145
    private String signatureDescription = "Office OpenXML Document";
146
    
147
    /**
148
     * The process of signing includes the marshalling of xml structures.
149
     * This also includes the canonicalization. Currently this leads to problems 
150
     * with certain namespaces, so this EventListener is used to interfere
151
     * with the marshalling process.
152
     */
153
    EventListener signatureMarshalListener = null;
154
155
    /**
156
     * Map of namespace uris to prefix
157
     * If a mapping is specified, the corresponding elements will be prefixed
158
     */
159
    Map<String,String> namespacePrefixes = new HashMap<String,String>();
160
    
161
    /**
162
     * Inits and checks the config object.
163
     * If not set previously, complex configuration properties also get 
164
     * created/initialized via this initialization call.
165
     *
166
     * @param onlyValidation if true, only a subset of the properties
167
     * is initialized, which are necessary for validation. If false,
168
     * also the other properties needed for signing are been taken care of
169
     */
170
    protected void init(boolean onlyValidation) {
171
        if (opcPackage == null) {
172
            throw new EncryptedDocumentException("opcPackage is null");
173
        }
174
        if (uriDereferencer == null) {
175
            uriDereferencer = new OOXMLURIDereferencer();
176
        }
177
        if (uriDereferencer instanceof SignatureConfigurable) {
178
            ((SignatureConfigurable)uriDereferencer).setSignatureConfig(this);
179
        }
180
        if (namespacePrefixes.isEmpty()) {
181
            /*
182
             * OOo doesn't like ds namespaces so per default prefixing is off.
183
             */
184
            // namespacePrefixes.put(XML_DIGSIG_NS, "");
185
            namespacePrefixes.put(OO_DIGSIG_NS, "mdssi");
186
            namespacePrefixes.put(XADES_132_NS, "xd");
187
        }
188
        
189
        if (onlyValidation) return;
190
191
        if (signatureMarshalListener == null) {
192
            signatureMarshalListener = new SignatureMarshalListener();
193
        }
194
        
195
        if (signatureMarshalListener instanceof SignatureConfigurable) {
196
            ((SignatureConfigurable)signatureMarshalListener).setSignatureConfig(this);
197
        }
198
        
199
        if (tspService != null) {
200
            tspService.setSignatureConfig(this);
201
        }
202
        
203
        if (signatureFacets.isEmpty()) {
204
            addSignatureFacet(new OOXMLSignatureFacet());
205
            addSignatureFacet(new KeyInfoSignatureFacet());
206
            addSignatureFacet(new XAdESSignatureFacet());
207
            addSignatureFacet(new Office2010SignatureFacet());
208
        }
209
210
        for (SignatureFacet sf : signatureFacets) {
211
            sf.setSignatureConfig(this);
212
        }
213
    }
214
    
215
    /**
216
     * @param signatureFacet the signature facet is appended to facet list 
217
     */
218
    public void addSignatureFacet(SignatureFacet signatureFacet) {
219
        signatureFacets.add(signatureFacet);
220
    }
221
    
222
    /**
223
     * @return the list of facets, may be empty when the config object is not initialized
224
     */
225
    public List<SignatureFacet> getSignatureFacets() {
226
        return signatureFacets;
227
    }
228
229
    /**
230
     * @param signatureFacets the new list of facets
231
     */
232
    public void setSignatureFacets(List<SignatureFacet> signatureFacets) {
233
        this.signatureFacets = signatureFacets;
234
    }
235
236
    /**
237
     * @return the main digest algorithm, defaults to sha-1
238
     */
239
    public HashAlgorithm getDigestAlgo() {
240
        return digestAlgo;
241
    }
242
243
    /**
244
     * @param digestAlgo the main digest algorithm
245
     */
246
    public void setDigestAlgo(HashAlgorithm digestAlgo) {
247
        this.digestAlgo = digestAlgo;
248
    }
249
    
250
    /**
251
     * @return the opc package to be used by this thread, stored as thread-local
252
     */
253
    public OPCPackage getOpcPackage() {
254
        return opcPackage.get();
255
    }
256
    
257
    /**
258
     * @param opcPackage the opc package to be handled by this thread, stored as thread-local
259
     */
260
    public void setOpcPackage(OPCPackage opcPackage) {
261
        this.opcPackage.set(opcPackage);
262
    }
263
264
    /**
265
     * @return the private key
266
     */
267
    public PrivateKey getKey() {
268
        return key;
269
    }
270
271
    /**
272
     * @param key the private key
273
     */
274
    public void setKey(PrivateKey key) {
275
        this.key = key;
276
    }
277
278
    /**
279
     * @return the certificate chain, index 0 is usually the certificate matching
280
     * the private key
281
     */
282
    public List<X509Certificate> getSigningCertificateChain() {
283
        return signingCertificateChain;
284
    }
285
286
    /**
287
     * @param signingCertificateChain the certificate chain, index 0 should be
288
     * the certificate matching the private key
289
     */
290
    public void setSigningCertificateChain(
291
            List<X509Certificate> signingCertificateChain) {
292
        this.signingCertificateChain = signingCertificateChain;
293
    }
294
295
    /**
296
     * @return the time at which the document is signed, also used for the timestamp service.
297
     * defaults to now
298
     */
299
    public Date getExecutionTime() {
300
        return executionTime;
301
    }
302
303
    /**
304
     * @param executionTime sets the time at which the document ought to be signed
305
     */
306
    public void setExecutionTime(Date executionTime) {
307
        this.executionTime = executionTime;
308
    }
309
    
310
    /**
311
     * @return the service to be used for XAdES-EPES properties. There's no default implementation
312
     */
313
    public SignaturePolicyService getSignaturePolicyService() {
314
        return signaturePolicyService;
315
    }
316
317
    /**
318
     * @param signaturePolicyService the service to be used for XAdES-EPES properties
319
     */
320
    public void setSignaturePolicyService(SignaturePolicyService signaturePolicyService) {
321
        this.signaturePolicyService = signaturePolicyService;
322
    }
323
324
    /**
325
     * @return the dereferencer used for Reference/@URI attributes, defaults to {@link OOXMLURIDereferencer}
326
     */
327
    public URIDereferencer getUriDereferencer() {
328
        return uriDereferencer;
329
    }
330
331
    /**
332
     * @param uriDereferencer the dereferencer used for Reference/@URI attributes
333
     */
334
    public void setUriDereferencer(URIDereferencer uriDereferencer) {
335
        this.uriDereferencer = uriDereferencer;
336
    }
337
338
    /**
339
     * @return Gives back the human-readable description of what the citizen
340
     * will be signing. The default value is "Office OpenXML Document".
341
     */
342
    public String getSignatureDescription() {
343
        return signatureDescription;
344
    }
345
346
    /**
347
     * @param signatureDescription the human-readable description of
348
     * what the citizen will be signing.
349
     */
350
    public void setSignatureDescription(String signatureDescription) {
351
        this.signatureDescription = signatureDescription;
352
    }
353
    
354
    /**
355
     * @return the default canonicalization method, defaults to INCLUSIVE
356
     */
357
    public String getCanonicalizationMethod() {
358
        return canonicalizationMethod;
359
    }
360
    
361
    /**
362
     * @param canonicalizationMethod the default canonicalization method
363
     */
364
    public void setCanonicalizationMethod(String canonicalizationMethod) {
365
        this.canonicalizationMethod = canonicalizationMethod;
366
    }
367
368
    /**
369
     * @return The signature Id attribute value used to create the XML signature.
370
     * Defaults to "idPackageSignature"
371
     */
372
    public String getPackageSignatureId() {
373
        return packageSignatureId;
374
    }
375
376
    /**
377
     * @param packageSignatureId The signature Id attribute value used to create the XML signature.
378
     * A <code>null</code> value will trigger an automatically generated signature Id.
379
     */
380
    public void setPackageSignatureId(String packageSignatureId) {
381
        this.packageSignatureId = nvl(packageSignatureId,"xmldsig-"+UUID.randomUUID());
382
    }
383
384
    /**
385
     * @return the url of the timestamp provider (TSP)
386
     */
387
    public String getTspUrl() {
388
        return tspUrl;
389
    }
390
391
    /**
392
     * @param tspUrl the url of the timestamp provider (TSP)
393
     */
394
    public void setTspUrl(String tspUrl) {
395
        this.tspUrl = tspUrl;
396
    }
397
    
398
    /**
399
     * @return if true, uses timestamp-request/response mimetype,
400
     * if false, timestamp-query/reply mimetype 
401
     */
402
    public boolean isTspOldProtocol() {
403
        return tspOldProtocol;
404
    }
405
    
406
    /**
407
     * @param tspOldProtocol defines the timestamp-protocol mimetype
408
     * @see #isTspOldProtocol
409
     */
410
    public void setTspOldProtocol(boolean tspOldProtocol) {
411
        this.tspOldProtocol = tspOldProtocol;
412
    }
413
    
414
    /**
415
     * @return the hash algorithm to be used for the timestamp entry.
416
     * Defaults to the hash algorithm of the main entry
417
     */
418
    public HashAlgorithm getTspDigestAlgo() {
419
        return nvl(tspDigestAlgo,digestAlgo);
420
    }
421
    
422
    /**
423
     * @param tspDigestAlgo the algorithm to be used for the timestamp entry.
424
     * if <code>null</code>, the hash algorithm of the main entry
425
     */
426
    public void setTspDigestAlgo(HashAlgorithm tspDigestAlgo) {
427
        this.tspDigestAlgo = tspDigestAlgo;
428
    }
429
430
    /**
431
     * @return the proxy url to be used for all communications.
432
     * Currently this affects the timestamp service
433
     */
434
    public String getProxyUrl() {
435
        return proxyUrl;
436
    }
437
    
438
    /**
439
     * @param proxyUrl the proxy url to be used for all communications.
440
     * Currently this affects the timestamp service
441
     */
442
    public void setProxyUrl(String proxyUrl) {
443
        this.proxyUrl = proxyUrl;
444
    }
445
    
446
    /**
447
     * @return the timestamp service. Defaults to {@link TSPTimeStampService}
448
     */
449
    public TimeStampService getTspService() {
450
        return tspService;
451
    }
452
    
453
    /**
454
     * @param tspService the timestamp service
455
     */
456
    public void setTspService(TimeStampService tspService) {
457
        this.tspService = tspService;
458
    }
459
    
460
    /**
461
     * @return the user id for the timestamp service - currently only basic authorization is supported
462
     */
463
    public String getTspUser() {
464
        return tspUser;
465
    }
466
    
467
    /**
468
     * @param tspUser the user id for the timestamp service - currently only basic authorization is supported
469
     */
470
    public void setTspUser(String tspUser) {
471
        this.tspUser = tspUser;
472
    }
473
    
474
    /**
475
     * @return the password for the timestamp service
476
     */
477
    public String getTspPass() {
478
        return tspPass;
479
    }
480
    
481
    /**
482
     * @param tspPass the password for the timestamp service
483
     */
484
    public void setTspPass(String tspPass) {
485
        this.tspPass = tspPass;
486
    }
487
    
488
    /**
489
     * @return the validator for the timestamp service (certificate)
490
     */
491
    public TimeStampServiceValidator getTspValidator() {
492
        return tspValidator;
493
    }
494
    
495
    /**
496
     * @param tspValidator the validator for the timestamp service (certificate)
497
     */
498
    public void setTspValidator(TimeStampServiceValidator tspValidator) {
499
        this.tspValidator = tspValidator;
500
    }
501
502
    /**
503
     * @return the optional revocation data service used for XAdES-C and XAdES-X-L.
504
     * When <code>null</code> the signature will be limited to XAdES-T only.
505
     */
506
    public RevocationDataService getRevocationDataService() {
507
        return revocationDataService;
508
    }
509
510
    /**
511
     * @param revocationDataService the optional revocation data service used for XAdES-C and XAdES-X-L.
512
     * When <code>null</code> the signature will be limited to XAdES-T only.
513
     */
514
    public void setRevocationDataService(RevocationDataService revocationDataService) {
515
        this.revocationDataService = revocationDataService;
516
    }
517
518
    /**
519
     * @return hash algorithm used for XAdES. Defaults to the {@link #getDigestAlgo()}
520
     */
521
    public HashAlgorithm getXadesDigestAlgo() {
522
        return nvl(xadesDigestAlgo,digestAlgo);
523
    }
524
    
525
    /**
526
     * @param xadesDigestAlgo hash algorithm used for XAdES.
527
     * When <code>null</code>, defaults to {@link #getDigestAlgo()}
528
     */
529
    public void setXadesDigestAlgo(HashAlgorithm xadesDigestAlgo) {
530
        this.xadesDigestAlgo = xadesDigestAlgo;
531
    }
532
533
    /**
534
     * @return the user agent used for http communication (e.g. to the TSP)
535
     */
536
    public String getUserAgent() {
537
        return userAgent;
538
    }
539
    
540
    /**
541
     * @param userAgent the user agent used for http communication (e.g. to the TSP)
542
     */
543
    public void setUserAgent(String userAgent) {
544
        this.userAgent = userAgent;
545
    }
546
547
    /**
548
     * @return the asn.1 object id for the tsp request policy.
549
     * Defaults to <code>1.3.6.1.4.1.13762.3</code>
550
     */
551
    public String getTspRequestPolicy() {
552
        return tspRequestPolicy;
553
    }
554
    
555
    /**
556
     * @param tspRequestPolicy the asn.1 object id for the tsp request policy.
557
     */
558
    public void setTspRequestPolicy(String tspRequestPolicy) {
559
        this.tspRequestPolicy = tspRequestPolicy;
560
    }
561
562
    /**
563
     * @return true, if the whole certificate chain is included in the signature.
564
     * When false, only the signer cert will be included 
565
     */
566
    public boolean isIncludeEntireCertificateChain() {
567
        return includeEntireCertificateChain;
568
    }
569
570
    /**
571
     * @param includeEntireCertificateChain if true, include the whole certificate chain.
572
     * If false, only include the signer cert
573
     */
574
    public void setIncludeEntireCertificateChain(boolean includeEntireCertificateChain) {
575
        this.includeEntireCertificateChain = includeEntireCertificateChain;
576
    }
577
578
    /**
579
     * @return if true, issuer serial number is included
580
     */
581
    public boolean isIncludeIssuerSerial() {
582
        return includeIssuerSerial;
583
    }
584
585
    /**
586
     * @param includeIssuerSerial if true, issuer serial number is included
587
     */
588
    public void setIncludeIssuerSerial(boolean includeIssuerSerial) {
589
        this.includeIssuerSerial = includeIssuerSerial;
590
    }
591
592
    /**
593
     * @return if true, the key value of the public key (certificate) is included
594
     */
595
    public boolean isIncludeKeyValue() {
596
        return includeKeyValue;
597
    }
598
599
    /**
600
     * @param includeKeyValue if true, the key value of the public key (certificate) is included
601
     */
602
    public void setIncludeKeyValue(boolean includeKeyValue) {
603
        this.includeKeyValue = includeKeyValue;
604
    }
605
606
    /**
607
     * @return the xades role element. If <code>null</code> the claimed role element is omitted.
608
     * Defaults to <code>null</code>
609
     */
610
    public String getXadesRole() {
611
        return xadesRole;
612
    }
613
614
    /**
615
     * @param xadesRole the xades role element. If <code>null</code> the claimed role element is omitted.
616
     */
617
    public void setXadesRole(String xadesRole) {
618
        this.xadesRole = xadesRole;
619
    }
620
621
    /**
622
     * @return the Id for the XAdES SignedProperties element.
623
     * Defaults to <code>idSignedProperties</code>
624
     */
625
    public String getXadesSignatureId() {
626
        return nvl(xadesSignatureId, "idSignedProperties");
627
    }
628
629
    /**
630
     * @param xadesSignatureId the Id for the XAdES SignedProperties element.
631
     * When <code>null</code> defaults to <code>idSignedProperties</code>
632
     */
633
    public void setXadesSignatureId(String xadesSignatureId) {
634
        this.xadesSignatureId = xadesSignatureId;
635
    }
636
637
    /**
638
     * @return when true, include the policy-implied block.
639
     * Defaults to <code>true</code>
640
     */
641
    public boolean isXadesSignaturePolicyImplied() {
642
        return xadesSignaturePolicyImplied;
643
    }
644
645
    /**
646
     * @param xadesSignaturePolicyImplied when true, include the policy-implied block
647
     */
648
    public void setXadesSignaturePolicyImplied(boolean xadesSignaturePolicyImplied) {
649
        this.xadesSignaturePolicyImplied = xadesSignaturePolicyImplied;
650
    }
651
652
    /**
653
     * Make sure the DN is encoded using the same order as present
654
     * within the certificate. This is an Office2010 work-around.
655
     * Should be reverted back.
656
     * 
657
     * XXX: not correct according to RFC 4514.
658
     *
659
     * @return when true, the issuer DN is used instead of the issuer X500 principal
660
     */
661
    public boolean isXadesIssuerNameNoReverseOrder() {
662
        return xadesIssuerNameNoReverseOrder;
663
    }
664
665
    /**
666
     * @param xadesIssuerNameNoReverseOrder when true, the issuer DN instead of the issuer X500 prinicpal is used
667
     */
668
    public void setXadesIssuerNameNoReverseOrder(boolean xadesIssuerNameNoReverseOrder) {
669
        this.xadesIssuerNameNoReverseOrder = xadesIssuerNameNoReverseOrder;
670
    }
671
672
    
673
    /**
674
     * @return the event listener which is active while xml structure for
675
     * the signature is created.
676
     * Defaults to {@link SignatureMarshalListener}
677
     */
678
    public EventListener getSignatureMarshalListener() {
679
        return signatureMarshalListener;
680
    }
681
682
    /**
683
     * @param signatureMarshalListener the event listener watching the xml structure
684
     * generation for the signature
685
     */
686
    public void setSignatureMarshalListener(EventListener signatureMarshalListener) {
687
        this.signatureMarshalListener = signatureMarshalListener;
688
    }
689
690
    /**
691
     * @return the map of namespace uri (key) to prefix (value)
692
     */
693
    public Map<String, String> getNamespacePrefixes() {
694
        return namespacePrefixes;
695
    }
696
697
    /**
698
     * @param namespacePrefixes the map of namespace uri (key) to prefix (value)
699
     */
700
    public void setNamespacePrefixes(Map<String, String> namespacePrefixes) {
701
        this.namespacePrefixes = namespacePrefixes;
702
    }
703
704
    /**
705
     * helper method for null/default value handling
706
     * @param value
707
     * @param defaultValue
708
     * @return if value is not null, return value otherwise defaultValue
709
     */
710
    protected static <T> T nvl(T value, T defaultValue)  {
711
        return value == null ? defaultValue : value;
712
    }
713
714
    /**
715
     * Each digest method has its own IV (initial vector)
716
     *
717
     * @return the IV depending on the main digest method
718
     */
719
    public byte[] getHashMagic() {
720
        // see https://www.ietf.org/rfc/rfc3110.txt
721
        // RSA/SHA1 SIG Resource Records
722
        byte result[];
723
        switch (getDigestAlgo()) {
724
        case sha1: result = new byte[]
725
            { 0x30, 0x1f, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x0e
726
            , 0x03, 0x02, 0x1a, 0x04, 0x14 };
727
            break;
728
        case sha224: result = new byte[] 
729
            { 0x30, 0x2b, 0x30, 0x0b, 0x06, 0x09, 0x60, (byte) 0x86
730
            , 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x04, 0x1c };
731
            break;
732
        case sha256: result = new byte[]
733
            { 0x30, 0x2f, 0x30, 0x0b, 0x06, 0x09, 0x60, (byte) 0x86
734
            , 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x04, 0x20 };
735
            break;
736
        case sha384: result = new byte[]
737
            { 0x30, 0x3f, 0x30, 0x0b, 0x06, 0x09, 0x60, (byte) 0x86
738
            , 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x04, 0x30 };
739
            break;
740
        case sha512: result  = new byte[]
741
            { 0x30, 0x4f, 0x30, 0x0b, 0x06, 0x09, 0x60, (byte) 0x86
742
            , 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x04, 0x40 };
743
            break;
744
        case ripemd128: result = new byte[]
745
            { 0x30, 0x1b, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x24
746
            , 0x03, 0x02, 0x02, 0x04, 0x10 };
747
            break;
748
        case ripemd160: result = new byte[]
749
            { 0x30, 0x1f, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x24
750
            , 0x03, 0x02, 0x01, 0x04, 0x14 };
751
            break;
752
        // case ripemd256: result = new byte[]
753
        //    { 0x30, 0x2b, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x24
754
        //    , 0x03, 0x02, 0x03, 0x04, 0x20 };
755
        //    break;
756
        default: throw new EncryptedDocumentException("Hash algorithm "
757
            +getDigestAlgo()+" not supported for signing.");
758
        }
759
        
760
        return result;
761
    }
762
763
    /**
764
     * @return the uri for the signature method, i.e. currently only rsa is
765
     * supported, so it's the rsa variant of the main digest
766
     */
767
    public String getSignatureMethodUri() {
768
        switch (getDigestAlgo()) {
769
        case sha1:   return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
770
        case sha224: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224;
771
        case sha256: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256;
772
        case sha384: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384;
773
        case sha512: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512;
774
        case ripemd160: return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160;
775
        default: throw new EncryptedDocumentException("Hash algorithm "
776
            +getDigestAlgo()+" not supported for signing.");
777
        }
778
    }
779
    
780
    /**
781
     * @return the uri for the main digest
782
     */
783
    public String getDigestMethodUri() {
784
        return getDigestMethodUri(getDigestAlgo());
785
    }
786
    
787
    /**
788
     * @param digestAlgo the digest algo, currently only sha* and ripemd160 is supported 
789
     * @return the uri for the given digest
790
     */
791
    public static String getDigestMethodUri(HashAlgorithm digestAlgo) {
792
        switch (digestAlgo) {
793
        case sha1:   return DigestMethod.SHA1;
794
        case sha224: return "http://www.w3.org/2001/04/xmldsig-more#sha224";
795
        case sha256: return DigestMethod.SHA256;
796
        case sha384: return "http://www.w3.org/2001/04/xmldsig-more#sha384";
797
        case sha512: return DigestMethod.SHA512;
798
        case ripemd160: return DigestMethod.RIPEMD160;
799
        default: throw new EncryptedDocumentException("Hash algorithm "
800
            +digestAlgo+" not supported for signing.");
801
        }
802
    }
803
    
804
    /**
805
     * @param signatureFactory the xml signature factory, saved as thread-local
806
     */
807
    public void setSignatureFactory(XMLSignatureFactory signatureFactory) {
808
        this.signatureFactory.set(signatureFactory);
809
    }
810
    
811
    /**
812
     * @return the xml signature factory (thread-local)
813
     */
814
    public XMLSignatureFactory getSignatureFactory() {
815
        XMLSignatureFactory sigFac = signatureFactory.get();
816
        if (sigFac == null) {
817
            sigFac = XMLSignatureFactory.getInstance("DOM", getProvider());
818
            setSignatureFactory(sigFac);
819
        }
820
        return sigFac;
821
    }
822
823
    /**
824
     * @param keyInfoFactory the key factory, saved as thread-local
825
     */
826
    public void setKeyInfoFactory(KeyInfoFactory keyInfoFactory) {
827
        this.keyInfoFactory.set(keyInfoFactory);
828
    }
829
    
830
    /**
831
     * @return the key factory (thread-local)
832
     */
833
    public KeyInfoFactory getKeyInfoFactory() {
834
        KeyInfoFactory keyFac = keyInfoFactory.get();
835
        if (keyFac == null) {
836
            keyFac = KeyInfoFactory.getInstance("DOM", getProvider());
837
            setKeyInfoFactory(keyFac);
838
        }
839
        return keyFac;
840
    }
841
842
    /**
843
     * This method tests the existence of xml signature provider in the following order:
844
     * <ul>
845
     * <li>the class pointed to by the system property "jsr105Provider"</li>
846
     * <li>the Santuario xmlsec provider</li>
847
     * <li>the JDK xmlsec provider</li>
848
     * </ul>
849
     * 
850
     * For signing the classes are linked against the Santuario xmlsec, so this might
851
     * only work for validation (not tested).
852
     *  
853
     * @return the xml dsig provider
854
     */
855
    public Provider getProvider() {
856
        Provider prov = provider.get();
857
        if (prov == null) {
858
            String dsigProviderNames[] = {
859
                System.getProperty("jsr105Provider"),
860
                "org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI", // Santuario xmlsec
861
                "org.jcp.xml.dsig.internal.dom.XMLDSigRI"         // JDK xmlsec
862
            };
863
            for (String pn : dsigProviderNames) {
864
                if (pn == null) continue;
865
                try {
866
                    prov = (Provider)Class.forName(pn).newInstance();
867
                    break;
868
                } catch (Exception e) {
869
                    LOG.log(POILogger.DEBUG, "XMLDsig-Provider '"+pn+"' can't be found - trying next.");
870
                }
871
            }
872
        }
873
874
        if (prov == null) {
875
            throw new RuntimeException("JRE doesn't support default xml signature provider - set jsr105Provider system property!");
876
        }
877
        
878
        return prov;
879
    }
880
881
    /**
882
     * @return the cannonicalization method for XAdES-XL signing.
883
     * Defaults to <code>EXCLUSIVE</code>
884
     * @see <a href="http://docs.oracle.com/javase/7/docs/api/javax/xml/crypto/dsig/CanonicalizationMethod.html">javax.xml.crypto.dsig.CanonicalizationMethod</a>
885
     */
886
    public String getXadesCanonicalizationMethod() {
887
        return xadesCanonicalizationMethod;
888
    }
889
890
    /**
891
     * @param xadesCanonicalizationMethod the cannonicalization method for XAdES-XL signing
892
     * @see <a href="http://docs.oracle.com/javase/7/docs/api/javax/xml/crypto/dsig/CanonicalizationMethod.html">javax.xml.crypto.dsig.CanonicalizationMethod</a>
893
     */
894
    public void setXadesCanonicalizationMethod(String xadesCanonicalizationMethod) {
895
        this.xadesCanonicalizationMethod = xadesCanonicalizationMethod;
896
    }
897
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureInfo.java (-639 lines)
Lines 1-639 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
/* ====================================================================
19
   This product contains an ASLv2 licensed version of the OOXML signer
20
   package from the eID Applet project
21
   http://code.google.com/p/eid-applet/source/browse/trunk/README.txt  
22
   Copyright (C) 2008-2014 FedICT.
23
   ================================================================= */ 
24
25
package org.apache.poi.poifs.crypt.dsig;
26
27
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_DIGSIG_NS;
28
29
import java.io.ByteArrayOutputStream;
30
import java.io.File;
31
import java.io.IOException;
32
import java.io.OutputStream;
33
import java.security.GeneralSecurityException;
34
import java.security.MessageDigest;
35
import java.security.cert.X509Certificate;
36
import java.util.ArrayList;
37
import java.util.Collections;
38
import java.util.HashMap;
39
import java.util.Iterator;
40
import java.util.List;
41
import java.util.Map;
42
import java.util.NoSuchElementException;
43
44
import javax.crypto.Cipher;
45
import javax.xml.crypto.MarshalException;
46
import javax.xml.crypto.URIDereferencer;
47
import javax.xml.crypto.XMLStructure;
48
import javax.xml.crypto.dsig.CanonicalizationMethod;
49
import javax.xml.crypto.dsig.Manifest;
50
import javax.xml.crypto.dsig.Reference;
51
import javax.xml.crypto.dsig.SignatureMethod;
52
import javax.xml.crypto.dsig.SignedInfo;
53
import javax.xml.crypto.dsig.XMLObject;
54
import javax.xml.crypto.dsig.XMLSignContext;
55
import javax.xml.crypto.dsig.XMLSignature;
56
import javax.xml.crypto.dsig.XMLSignatureException;
57
import javax.xml.crypto.dsig.XMLSignatureFactory;
58
import javax.xml.crypto.dsig.dom.DOMSignContext;
59
import javax.xml.crypto.dsig.dom.DOMValidateContext;
60
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
61
import javax.xml.xpath.XPath;
62
import javax.xml.xpath.XPathConstants;
63
import javax.xml.xpath.XPathFactory;
64
65
import org.apache.jcp.xml.dsig.internal.dom.DOMReference;
66
import org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo;
67
import org.apache.poi.EncryptedDocumentException;
68
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
69
import org.apache.poi.openxml4j.opc.ContentTypes;
70
import org.apache.poi.openxml4j.opc.OPCPackage;
71
import org.apache.poi.openxml4j.opc.PackagePart;
72
import org.apache.poi.openxml4j.opc.PackagePartName;
73
import org.apache.poi.openxml4j.opc.PackageRelationship;
74
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
75
import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
76
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
77
import org.apache.poi.openxml4j.opc.TargetMode;
78
import org.apache.poi.poifs.crypt.ChainingMode;
79
import org.apache.poi.poifs.crypt.CipherAlgorithm;
80
import org.apache.poi.poifs.crypt.CryptoFunctions;
81
import org.apache.poi.poifs.crypt.dsig.SignatureConfig.SignatureConfigurable;
82
import org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet;
83
import org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService;
84
import org.apache.poi.util.DocumentHelper;
85
import org.apache.poi.util.POILogFactory;
86
import org.apache.poi.util.POILogger;
87
import org.apache.xml.security.Init;
88
import org.apache.xml.security.utils.Base64;
89
import org.apache.xmlbeans.XmlException;
90
import org.apache.xmlbeans.XmlOptions;
91
import org.w3.x2000.x09.xmldsig.SignatureDocument;
92
import org.w3c.dom.Document;
93
import org.w3c.dom.Element;
94
import org.w3c.dom.NodeList;
95
import org.w3c.dom.events.EventListener;
96
import org.w3c.dom.events.EventTarget;
97
98
99
/**
100
 * <p>This class is the default entry point for XML signatures and can be used for
101
 * validating an existing signed office document and signing a office document.</p>
102
 * 
103
 * <p><b>Validating a signed office document</b></p>
104
 * 
105
 * <pre>
106
 * OPCPackage pkg = OPCPackage.open(..., PackageAccess.READ);
107
 * SignatureConfig sic = new SignatureConfig();
108
 * sic.setOpcPackage(pkg);
109
 * SignatureInfo si = new SignatureInfo();
110
 * si.setSignatureConfig(sic);
111
 * boolean isValid = si.validate();
112
 * ...
113
 * </pre>
114
 * 
115
 * <p><b>Signing an office document</b></p>
116
 * 
117
 * <pre>
118
 * // loading the keystore - pkcs12 is used here, but of course jks &amp; co are also valid
119
 * // the keystore needs to contain a private key and it's certificate having a
120
 * // 'digitalSignature' key usage
121
 * char password[] = "test".toCharArray();
122
 * File file = new File("test.pfx");
123
 * KeyStore keystore = KeyStore.getInstance("PKCS12");
124
 * FileInputStream fis = new FileInputStream(file);
125
 * keystore.load(fis, password);
126
 * fis.close();
127
 * 
128
 * // extracting private key and certificate
129
 * String alias = "xyz"; // alias of the keystore entry
130
 * Key key = keystore.getKey(alias, password);
131
 * X509Certificate x509 = (X509Certificate)keystore.getCertificate(alias);
132
 * 
133
 * // filling the SignatureConfig entries (minimum fields, more options are available ...)
134
 * SignatureConfig signatureConfig = new SignatureConfig();
135
 * signatureConfig.setKey(keyPair.getPrivate());
136
 * signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
137
 * OPCPackage pkg = OPCPackage.open(..., PackageAccess.READ_WRITE);
138
 * signatureConfig.setOpcPackage(pkg);
139
 * 
140
 * // adding the signature document to the package
141
 * SignatureInfo si = new SignatureInfo();
142
 * si.setSignatureConfig(signatureConfig);
143
 * si.confirmSignature();
144
 * // optionally verify the generated signature
145
 * boolean b = si.verifySignature();
146
 * assert (b);
147
 * // write the changes back to disc
148
 * pkg.close();
149
 * </pre>
150
 * 
151
 * <p><b>Implementation notes:</b></p>
152
 * 
153
 * <p>Although there's a XML signature implementation in the Oracle JDKs 6 and higher,
154
 * compatibility with IBM JDKs is also in focus (... but maybe not thoroughly tested ...).
155
 * Therefore we are using the Apache Santuario libs (xmlsec) instead of the built-in classes,
156
 * as the compatibility seems to be provided there.</p>
157
 * 
158
 * <p>To use SignatureInfo and its sibling classes, you'll need to have the following libs
159
 * in the classpath:</p>
160
 * <ul>
161
 * <li>BouncyCastle bcpkix and bcprov (tested against 1.51)</li>
162
 * <li>Apache Santuario "xmlsec" (tested against 2.0.1)</li>
163
 * <li>and slf4j-api (tested against 1.7.7)</li>
164
 * </ul>
165
 */
166
public class SignatureInfo implements SignatureConfigurable {
167
168
    private static final POILogger LOG = POILogFactory.getLogger(SignatureInfo.class);
169
    private static boolean isInitialized = false;
170
    
171
    private SignatureConfig signatureConfig;
172
173
    public class SignaturePart {
174
        private final PackagePart signaturePart;
175
        private X509Certificate signer;
176
        private List<X509Certificate> certChain;
177
        
178
        private SignaturePart(PackagePart signaturePart) {
179
            this.signaturePart = signaturePart;
180
        }
181
        
182
        /**
183
         * @return the package part containing the signature
184
         */
185
        public PackagePart getPackagePart() {
186
            return signaturePart;
187
        }
188
        
189
        /**
190
         * @return the signer certificate
191
         */
192
        public X509Certificate getSigner() {
193
            return signer;
194
        }
195
        
196
        /**
197
         * @return the certificate chain of the signer
198
         */
199
        public List<X509Certificate> getCertChain() {
200
            return certChain;
201
        }
202
        
203
        /**
204
         * Helper method for examining the xml signature
205
         *
206
         * @return the xml signature document
207
         * @throws IOException if the xml signature doesn't exist or can't be read
208
         * @throws XmlException if the xml signature is malformed
209
         */
210
        public SignatureDocument getSignatureDocument() throws IOException, XmlException {
211
            // TODO: check for XXE
212
            return SignatureDocument.Factory.parse(signaturePart.getInputStream());
213
        }
214
        
215
        /**
216
         * @return true, when the xml signature is valid, false otherwise
217
         */
218
        public boolean validate() {
219
            KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
220
            try {
221
                Document doc = DocumentHelper.readDocument(signaturePart.getInputStream());
222
                XPath xpath = XPathFactory.newInstance().newXPath();
223
                NodeList nl = (NodeList)xpath.compile("//*[@Id]").evaluate(doc, XPathConstants.NODESET);
224
                for (int i=0; i<nl.getLength(); i++) {
225
                    ((Element)nl.item(i)).setIdAttribute("Id", true);
226
                }
227
                
228
                DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, doc);
229
                domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
230
                domValidateContext.setURIDereferencer(signatureConfig.getUriDereferencer());
231
    
232
                XMLSignatureFactory xmlSignatureFactory = signatureConfig.getSignatureFactory();
233
                XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
234
                boolean valid = xmlSignature.validate(domValidateContext);
235
236
                if (valid) {
237
                    signer = keySelector.getSigner();
238
                    certChain = keySelector.getCertChain();
239
                }
240
                
241
                return valid;
242
            } catch (Exception e) {
243
                LOG.log(POILogger.ERROR, "error in marshalling and validating the signature", e);
244
                return false;
245
            }
246
        }
247
    }
248
    
249
    /**
250
     * Constructor initializes xml signature environment, if it hasn't been initialized before
251
     */
252
    public SignatureInfo() {
253
        initXmlProvider();        
254
    }
255
    
256
    /**
257
     * @return the signature config
258
     */
259
    public SignatureConfig getSignatureConfig() {
260
        return signatureConfig;
261
    }
262
263
    /**
264
     * @param signatureConfig the signature config, needs to be set before a SignatureInfo object is used
265
     */
266
    public void setSignatureConfig(SignatureConfig signatureConfig) {
267
        this.signatureConfig = signatureConfig;
268
    }
269
270
    /**
271
     * @return true, if first signature part is valid
272
     */
273
    public boolean verifySignature() {
274
        // http://www.oracle.com/technetwork/articles/javase/dig-signature-api-140772.html
275
        for (SignaturePart sp : getSignatureParts()){
276
            // only validate first part
277
            return sp.validate();
278
        }
279
        return false;
280
    }
281
282
    /**
283
     * add the xml signature to the document
284
     *
285
     * @throws XMLSignatureException
286
     * @throws MarshalException
287
     */
288
    public void confirmSignature() throws XMLSignatureException, MarshalException {
289
        Document document = DocumentHelper.createDocument();
290
        
291
        // operate
292
        DigestInfo digestInfo = preSign(document, null);
293
294
        // setup: key material, signature value
295
        byte[] signatureValue = signDigest(digestInfo.digestValue);
296
        
297
        // operate: postSign
298
        postSign(document, signatureValue);
299
    }
300
301
    /**
302
     * Sign (encrypt) the digest with the private key.
303
     * Currently only rsa is supported.
304
     *
305
     * @param digest the hashed input
306
     * @return the encrypted hash
307
     */
308
    public byte[] signDigest(byte digest[]) {
309
        Cipher cipher = CryptoFunctions.getCipher(signatureConfig.getKey(), CipherAlgorithm.rsa
310
            , ChainingMode.ecb, null, Cipher.ENCRYPT_MODE, "PKCS1Padding");
311
            
312
        try {
313
            ByteArrayOutputStream digestInfoValueBuf = new ByteArrayOutputStream();
314
            digestInfoValueBuf.write(signatureConfig.getHashMagic());
315
            digestInfoValueBuf.write(digest);
316
            byte[] digestInfoValue = digestInfoValueBuf.toByteArray();
317
            byte[] signatureValue = cipher.doFinal(digestInfoValue);
318
            return signatureValue;
319
        } catch (Exception e) {
320
            throw new EncryptedDocumentException(e);
321
        }
322
    }
323
    
324
    /**
325
     * @return a signature part for each signature document.
326
     * the parts can be validated independently.
327
     */
328
    public Iterable<SignaturePart> getSignatureParts() {
329
        signatureConfig.init(true);
330
        return new Iterable<SignaturePart>() {
331
            public Iterator<SignaturePart> iterator() {
332
                return new Iterator<SignaturePart>() {
333
                    OPCPackage pkg = signatureConfig.getOpcPackage();
334
                    Iterator<PackageRelationship> sigOrigRels = 
335
                        pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN).iterator();
336
                    Iterator<PackageRelationship> sigRels = null;
337
                    PackagePart sigPart = null;
338
                    
339
                    public boolean hasNext() {
340
                        while (sigRels == null || !sigRels.hasNext()) {
341
                            if (!sigOrigRels.hasNext()) return false;
342
                            sigPart = pkg.getPart(sigOrigRels.next());
343
                            LOG.log(POILogger.DEBUG, "Digital Signature Origin part", sigPart);
344
                            try {
345
                                sigRels = sigPart.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE).iterator();
346
                            } catch (InvalidFormatException e) {
347
                                LOG.log(POILogger.WARN, "Reference to signature is invalid.", e);
348
                            }
349
                        }
350
                        return true;
351
                    }
352
                    
353
                    public SignaturePart next() {
354
                        PackagePart sigRelPart = null;
355
                        do {
356
                            try {
357
                                if (!hasNext()) throw new NoSuchElementException();
358
                                sigRelPart = sigPart.getRelatedPart(sigRels.next()); 
359
                                LOG.log(POILogger.DEBUG, "XML Signature part", sigRelPart);
360
                            } catch (InvalidFormatException e) {
361
                                LOG.log(POILogger.WARN, "Reference to signature is invalid.", e);
362
                            }
363
                        } while (sigPart == null);
364
                        return new SignaturePart(sigRelPart);
365
                    }
366
                    
367
                    public void remove() {
368
                        throw new UnsupportedOperationException();
369
                    }
370
                };
371
            }
372
        };
373
    }
374
    
375
    /**
376
     * Initialize the xml signing environment and the bouncycastle provider 
377
     */
378
    protected static synchronized void initXmlProvider() {
379
        if (isInitialized) return;
380
        isInitialized = true;
381
        
382
        try {
383
            Init.init();
384
            RelationshipTransformService.registerDsigProvider();
385
            CryptoFunctions.registerBouncyCastle();
386
        } catch (Exception e) {
387
            throw new RuntimeException("Xml & BouncyCastle-Provider initialization failed", e);
388
        }
389
    }
390
    
391
    /**
392
     * Helper method for adding informations before the signing.
393
     * Normally {@link #confirmSignature()} is sufficient to be used.
394
     */
395
    @SuppressWarnings("unchecked")
396
    public DigestInfo preSign(Document document, List<DigestInfo> digestInfos)
397
    throws XMLSignatureException, MarshalException {
398
        signatureConfig.init(false);
399
        
400
        // it's necessary to explicitly set the mdssi namespace, but the sign() method has no
401
        // normal way to interfere with, so we need to add the namespace under the hand ...
402
        EventTarget target = (EventTarget)document;
403
        EventListener creationListener = signatureConfig.getSignatureMarshalListener();
404
        if (creationListener != null) {
405
            if (creationListener instanceof SignatureMarshalListener) {
406
                ((SignatureMarshalListener)creationListener).setEventTarget(target);
407
            }
408
            SignatureMarshalListener.setListener(target, creationListener, true);
409
        }
410
        
411
        /*
412
         * Signature context construction.
413
         */
414
        XMLSignContext xmlSignContext = new DOMSignContext(signatureConfig.getKey(), document);
415
        URIDereferencer uriDereferencer = signatureConfig.getUriDereferencer();
416
        if (null != uriDereferencer) {
417
            xmlSignContext.setURIDereferencer(uriDereferencer);
418
        }
419
420
        for (Map.Entry<String,String> me : signatureConfig.getNamespacePrefixes().entrySet()) {
421
            xmlSignContext.putNamespacePrefix(me.getKey(), me.getValue());
422
        }
423
        xmlSignContext.setDefaultNamespacePrefix(""); // signatureConfig.getNamespacePrefixes().get(XML_DIGSIG_NS));
424
        
425
        XMLSignatureFactory signatureFactory = signatureConfig.getSignatureFactory();
426
427
        /*
428
         * Add ds:References that come from signing client local files.
429
         */
430
        List<Reference> references = new ArrayList<Reference>();
431
        for (DigestInfo digestInfo : safe(digestInfos)) {
432
            byte[] documentDigestValue = digestInfo.digestValue;
433
434
            String uri = new File(digestInfo.description).getName();
435
            Reference reference = SignatureFacet.newReference
436
                (uri, null, null, null, documentDigestValue, signatureConfig);
437
            references.add(reference);
438
        }
439
440
        /*
441
         * Invoke the signature facets.
442
         */
443
        List<XMLObject> objects = new ArrayList<XMLObject>();
444
        for (SignatureFacet signatureFacet : signatureConfig.getSignatureFacets()) {
445
            LOG.log(POILogger.DEBUG, "invoking signature facet: " + signatureFacet.getClass().getSimpleName());
446
            signatureFacet.preSign(document, references, objects);
447
        }
448
449
        /*
450
         * ds:SignedInfo
451
         */
452
        SignedInfo signedInfo;
453
        try {
454
            SignatureMethod signatureMethod = signatureFactory.newSignatureMethod
455
                (signatureConfig.getSignatureMethodUri(), null);
456
            CanonicalizationMethod canonicalizationMethod = signatureFactory
457
                .newCanonicalizationMethod(signatureConfig.getCanonicalizationMethod(),
458
                (C14NMethodParameterSpec) null);
459
            signedInfo = signatureFactory.newSignedInfo(
460
                canonicalizationMethod, signatureMethod, references);
461
        } catch (GeneralSecurityException e) {
462
            throw new XMLSignatureException(e);
463
        }
464
465
        /*
466
         * JSR105 ds:Signature creation
467
         */
468
        String signatureValueId = signatureConfig.getPackageSignatureId() + "-signature-value";
469
        javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory
470
            .newXMLSignature(signedInfo, null, objects, signatureConfig.getPackageSignatureId(),
471
            signatureValueId);
472
473
        /*
474
         * ds:Signature Marshalling.
475
         */
476
        xmlSignature.sign(xmlSignContext);
477
478
        /*
479
         * Completion of undigested ds:References in the ds:Manifests.
480
         */
481
        for (XMLObject object : objects) {
482
            LOG.log(POILogger.DEBUG, "object java type: " + object.getClass().getName());
483
            List<XMLStructure> objectContentList = object.getContent();
484
            for (XMLStructure objectContent : objectContentList) {
485
                LOG.log(POILogger.DEBUG, "object content java type: " + objectContent.getClass().getName());
486
                if (!(objectContent instanceof Manifest)) continue;
487
                Manifest manifest = (Manifest) objectContent;
488
                List<Reference> manifestReferences = manifest.getReferences();
489
                for (Reference manifestReference : manifestReferences) {
490
                    if (manifestReference.getDigestValue() != null) continue;
491
492
                    DOMReference manifestDOMReference = (DOMReference)manifestReference;
493
                    manifestDOMReference.digest(xmlSignContext);
494
                }
495
            }
496
        }
497
498
        /*
499
         * Completion of undigested ds:References.
500
         */
501
        List<Reference> signedInfoReferences = signedInfo.getReferences();
502
        for (Reference signedInfoReference : signedInfoReferences) {
503
            DOMReference domReference = (DOMReference)signedInfoReference;
504
505
            // ds:Reference with external digest value
506
            if (domReference.getDigestValue() != null) continue;
507
            
508
            domReference.digest(xmlSignContext);
509
        }
510
511
        /*
512
         * Calculation of XML signature digest value.
513
         */
514
        DOMSignedInfo domSignedInfo = (DOMSignedInfo)signedInfo;
515
        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
516
        domSignedInfo.canonicalize(xmlSignContext, dataStream);
517
        byte[] octets = dataStream.toByteArray();
518
519
        /*
520
         * TODO: we could be using DigestOutputStream here to optimize memory
521
         * usage.
522
         */
523
524
        MessageDigest md = CryptoFunctions.getMessageDigest(signatureConfig.getDigestAlgo());
525
        byte[] digestValue = md.digest(octets);
526
        
527
        
528
        String description = signatureConfig.getSignatureDescription();
529
        return new DigestInfo(digestValue, signatureConfig.getDigestAlgo(), description);
530
    }
531
532
    /**
533
     * Helper method for adding informations after the signing.
534
     * Normally {@link #confirmSignature()} is sufficient to be used.
535
     */
536
    public void postSign(Document document, byte[] signatureValue)
537
    throws MarshalException {
538
        LOG.log(POILogger.DEBUG, "postSign");
539
540
        /*
541
         * Check ds:Signature node.
542
         */
543
        String signatureId = signatureConfig.getPackageSignatureId();
544
        if (!signatureId.equals(document.getDocumentElement().getAttribute("Id"))) {
545
            throw new RuntimeException("ds:Signature not found for @Id: " + signatureId);
546
        }
547
548
        /*
549
         * Insert signature value into the ds:SignatureValue element
550
         */
551
        NodeList sigValNl = document.getElementsByTagNameNS(XML_DIGSIG_NS, "SignatureValue");
552
        if (sigValNl.getLength() != 1) {
553
            throw new RuntimeException("preSign has to be called before postSign");
554
        }
555
        sigValNl.item(0).setTextContent(Base64.encode(signatureValue));
556
557
        /*
558
         * Allow signature facets to inject their own stuff.
559
         */
560
        for (SignatureFacet signatureFacet : signatureConfig.getSignatureFacets()) {
561
            signatureFacet.postSign(document);
562
        }
563
564
        writeDocument(document);
565
    }
566
567
    /**
568
     * Write XML signature into the OPC package
569
     *
570
     * @param document the xml signature document
571
     * @throws MarshalException
572
     */
573
    protected void writeDocument(Document document) throws MarshalException {
574
        XmlOptions xo = new XmlOptions();
575
        Map<String,String> namespaceMap = new HashMap<String,String>();
576
        for(Map.Entry<String,String> entry : signatureConfig.getNamespacePrefixes().entrySet()){
577
            namespaceMap.put(entry.getValue(), entry.getKey());
578
        }        
579
        xo.setSaveSuggestedPrefixes(namespaceMap);
580
        xo.setUseDefaultNamespace();
581
582
        LOG.log(POILogger.DEBUG, "output signed Office OpenXML document");
583
584
        /*
585
         * Copy the original OOXML content to the signed OOXML package. During
586
         * copying some files need to changed.
587
         */
588
        OPCPackage pkg = signatureConfig.getOpcPackage();
589
590
        PackagePartName sigPartName, sigsPartName;
591
        try {
592
            // <Override PartName="/_xmlsignatures/sig1.xml" ContentType="application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"/>
593
            sigPartName = PackagingURIHelper.createPartName("/_xmlsignatures/sig1.xml");
594
            // <Default Extension="sigs" ContentType="application/vnd.openxmlformats-package.digital-signature-origin"/>
595
            sigsPartName = PackagingURIHelper.createPartName("/_xmlsignatures/origin.sigs");
596
        } catch (InvalidFormatException e) {
597
            throw new MarshalException(e);
598
        }
599
        
600
        PackagePart sigPart = pkg.getPart(sigPartName);
601
        if (sigPart == null) {
602
            sigPart = pkg.createPart(sigPartName, ContentTypes.DIGITAL_SIGNATURE_XML_SIGNATURE_PART);
603
        }
604
        
605
        try {
606
            OutputStream os = sigPart.getOutputStream();
607
            SignatureDocument sigDoc = SignatureDocument.Factory.parse(document);
608
            sigDoc.save(os, xo);
609
            os.close();
610
        } catch (Exception e) {
611
            throw new MarshalException("Unable to write signature document", e);
612
        }
613
        
614
        PackagePart sigsPart = pkg.getPart(sigsPartName);
615
        if (sigsPart == null) {
616
            // touch empty marker file
617
            sigsPart = pkg.createPart(sigsPartName, ContentTypes.DIGITAL_SIGNATURE_ORIGIN_PART);
618
        }
619
        
620
        PackageRelationshipCollection relCol = pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN);
621
        for (PackageRelationship pr : relCol) {
622
            pkg.removeRelationship(pr.getId());
623
        }
624
        pkg.addRelationship(sigsPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN);
625
        
626
        sigsPart.addRelationship(sigPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE);
627
    }
628
    
629
    /**
630
     * Helper method for null lists, which are converted to empty lists
631
     *
632
     * @param other the reference to wrap, if null
633
     * @return if other is null, an empty lists is returned, otherwise other is returned
634
     */
635
    @SuppressWarnings("unchecked")
636
    private static <T> List<T> safe(List<T> other) {
637
        return other == null ? Collections.EMPTY_LIST : other;
638
    }
639
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureMarshalListener.java (-92 lines)
Lines 1-92 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
package org.apache.poi.poifs.crypt.dsig;
19
20
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.OO_DIGSIG_NS;
21
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_NS;
22
23
import org.apache.poi.poifs.crypt.dsig.SignatureConfig.SignatureConfigurable;
24
import org.w3c.dom.Element;
25
import org.w3c.dom.Node;
26
import org.w3c.dom.NodeList;
27
import org.w3c.dom.events.Event;
28
import org.w3c.dom.events.EventListener;
29
import org.w3c.dom.events.EventTarget;
30
import org.w3c.dom.events.MutationEvent;
31
32
/**
33
 * This listener class is used, to modify the to be digested xml document,
34
 * e.g. to register id attributes or set prefixes for registered namespaces
35
 */
36
public class SignatureMarshalListener implements EventListener, SignatureConfigurable {
37
    ThreadLocal<EventTarget> target = new ThreadLocal<EventTarget>();
38
    SignatureConfig signatureConfig;
39
    public void setEventTarget(EventTarget target) {
40
        this.target.set(target);
41
    }
42
    
43
    public void handleEvent(Event e) {
44
        if (!(e instanceof MutationEvent)) return;
45
        MutationEvent mutEvt = (MutationEvent)e;
46
        EventTarget et = mutEvt.getTarget();
47
        if (!(et instanceof Element)) return;
48
        handleElement((Element)et);
49
    }
50
51
    public void handleElement(Element el) {
52
        EventTarget target = this.target.get();
53
        String packageId = signatureConfig.getPackageSignatureId();
54
        if (el.hasAttribute("Id")) {
55
            el.setIdAttribute("Id", true);
56
        }
57
58
        setListener(target, this, false);
59
        if (packageId.equals(el.getAttribute("Id"))) {
60
            el.setAttributeNS(XML_NS, "xmlns:mdssi", OO_DIGSIG_NS);
61
        }
62
        setPrefix(el);
63
        setListener(target, this, true);
64
    }
65
66
    // helper method to keep it in one place
67
    public static void setListener(EventTarget target, EventListener listener, boolean enabled) {
68
        String type = "DOMSubtreeModified";
69
        boolean useCapture = false;
70
        if (enabled) {
71
            target.addEventListener(type, listener, useCapture);
72
        } else {
73
            target.removeEventListener(type, listener, useCapture);
74
        }
75
    }
76
    
77
    protected void setPrefix(Node el) {
78
        String prefix = signatureConfig.getNamespacePrefixes().get(el.getNamespaceURI());
79
        if (prefix != null && el.getPrefix() == null) {
80
            el.setPrefix(prefix);
81
        }
82
        
83
        NodeList nl = el.getChildNodes();
84
        for (int i=0; i<nl.getLength(); i++) {
85
            setPrefix(nl.item(i));
86
        }
87
    }
88
    
89
    public void setSignatureConfig(SignatureConfig signatureConfig) {
90
        this.signatureConfig = signatureConfig;
91
    }
92
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/TrustCertificateSecurityException.java (-38 lines)
Lines 1-38 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
/* ====================================================================
19
   This product contains an ASLv2 licensed version of the OOXML signer
20
   package from the eID Applet project
21
   http://code.google.com/p/eid-applet/source/browse/trunk/README.txt  
22
   Copyright (C) 2008-2014 FedICT.
23
   ================================================================= */ 
24
25
package org.apache.poi.poifs.crypt.dsig;
26
27
/**
28
 * Exception thrown in case the incoming eID certificate is not trusted.
29
 * 
30
 * @author Frank Cornelis
31
 * 
32
 */
33
public class TrustCertificateSecurityException extends
34
        CertificateSecurityException {
35
36
    private static final long serialVersionUID = 1L;
37
38
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/EnvelopedSignatureFacet.java (-60 lines)
Lines 1-60 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
/* ====================================================================
19
   This product contains an ASLv2 licensed version of the OOXML signer
20
   package from the eID Applet project
21
   http://code.google.com/p/eid-applet/source/browse/trunk/README.txt  
22
   Copyright (C) 2008-2014 FedICT.
23
   ================================================================= */ 
24
25
package org.apache.poi.poifs.crypt.dsig.facets;
26
27
import java.util.ArrayList;
28
import java.util.List;
29
30
import javax.xml.crypto.dsig.CanonicalizationMethod;
31
import javax.xml.crypto.dsig.Reference;
32
import javax.xml.crypto.dsig.Transform;
33
import javax.xml.crypto.dsig.XMLObject;
34
import javax.xml.crypto.dsig.XMLSignatureException;
35
36
import org.w3c.dom.Document;
37
38
/**
39
 * Signature Facet implementation to create enveloped signatures.
40
 * 
41
 * @author Frank Cornelis
42
 * 
43
 */
44
public class EnvelopedSignatureFacet extends SignatureFacet {
45
46
    @Override
47
    public void preSign(Document document
48
        , List<Reference> references
49
        , List<XMLObject> objects)
50
    throws XMLSignatureException {
51
        List<Transform> transforms = new ArrayList<Transform>();
52
        Transform envelopedTransform = newTransform(CanonicalizationMethod.ENVELOPED);
53
        transforms.add(envelopedTransform);
54
        Transform exclusiveTransform = newTransform(CanonicalizationMethod.EXCLUSIVE);
55
        transforms.add(exclusiveTransform);
56
57
        Reference reference = newReference("", transforms, null, null, null);
58
        references.add(reference);
59
    }
60
}
(-)a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/KeyInfoSignatureFacet.java (-145 lines)
Lines 1-145 Link Here
1
/* ====================================================================
2
   Licensed to the Apache Software Foundation (ASF) under one or more
3
   contributor license agreements.  See the NOTICE file distributed with
4
   this work for additional information regarding copyright ownership.
5
   The ASF licenses this file to You under the Apache License, Version 2.0
6
   (the "License"); you may not use this file except in compliance with
7
   the License.  You may obtain a copy of the License at
8
9
       http://www.apache.org/licenses/LICENSE-2.0
10
11
   Unless required by applicable law or agreed to in writing, software
12
   distributed under the License is distributed on an "AS IS" BASIS,
13
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
   See the License for the specific language governing permissions and
15
   limitations under the License.
16
==================================================================== */
17
18
/* ====================================================================
19
   This product contains an ASLv2 licensed version of the OOXML signer
20
   package from the eID Applet project
21
   http://code.google.com/p/eid-applet/source/browse/trunk/README.txt  
22
   Copyright (C) 2008-2014 FedICT.
23
   ================================================================= */ 
24
25
package org.apache.poi.poifs.crypt.dsig.facets;
26
27
import java.security.Key;
28
import java.security.KeyException;
29
import java.security.cert.X509Certificate;
30
import java.util.ArrayList;
31
import java.util.List;
32
import java.util.Map;
33
34
import javax.xml.crypto.MarshalException;
35
import javax.xml.crypto.dom.DOMStructure;
36
import javax.xml.crypto.dsig.dom.DOMSignContext;
37
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
38
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
39
import javax.xml.crypto.dsig.keyinfo.KeyValue;
40
import javax.xml.crypto.dsig.keyinfo.X509Data;
41
42
import org.apache.jcp.xml.dsig.internal.dom.DOMKeyInfo;
43
import org.apache.poi.util.POILogFactory;
44
import org.apache.poi.util.POILogger;
45
import org.w3c.dom.Document;
46
import org.w3c.dom.Element;
47
import org.w3c.dom.Node;
48
import org.w3c.dom.NodeList;
49
50
/**
51
 * Signature Facet implementation that adds ds:KeyInfo to the XML signature.
52
 * 
53
 * @author Frank Cornelis
54
 * 
55
 */
56
public class KeyInfoSignatureFacet extends SignatureFacet {
57
58
    private static final POILogger LOG = POILogFactory.getLogger(KeyInfoSignatureFacet.class);
59
    
60
    @Override
61
    public void postSign(Document document) 
62
    throws MarshalException {
63
        LOG.log(POILogger.DEBUG, "postSign");
64
65
        NodeList nl = document.getElementsByTagNameNS(XML_DIGSIG_NS, "Object");
66
        
67
        /*
68
         * Make sure we insert right after the ds:SignatureValue element, just
69
         * before the first ds:Object element.
70
         */
71
        Node nextSibling = (nl.getLength() == 0) ? null : nl.item(0);
72
73
        /*
74
         * Construct the ds:KeyInfo element using JSR 105.
75
         */
76
        KeyInfoFactory keyInfoFactory = signatureConfig.getKeyInfoFactory();
77
        List<Object> x509DataObjects = new ArrayList<Object>();
78
        X509Certificate signingCertificate = signatureConfig.getSigningCertificateChain().get(0);
79
80
        List<Object> keyInfoContent = new ArrayList<Object>();
81
82
        if (signatureConfig.isIncludeKeyValue()) {
83
            KeyValue keyValue;
84
            try {
85
                keyValue = keyInfoFactory.newKeyValue(signingCertificate.getPublicKey());
86
            } catch (KeyException e) {
87
                throw new RuntimeException("key exception: " + e.getMessage(), e);
88
            }
89
            keyInfoContent.add(keyValue);
90
        }
91
92
        if (signatureConfig.isIncludeIssuerSerial()) {
93
            x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(
94
                signingCertificate.getIssuerX500Principal().toString(),
95
                signingCertificate.getSerialNumber()));
96
        }
97
98
        if (signatureConfig.isIncludeEntireCertificateChain()) {
99
            x509DataObjects.addAll(signatureConfig.getSigningCertificateChain());
100
        } else {
101
            x509DataObjects.add(signingCertificate);
102
        }
103
104
        if (!x509DataObjects.isEmpty()) {
105
            X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
106
            keyInfoContent.add(x509Data);
107
        }
108
        KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);
109
        DOMKeyInfo domKeyInfo = (DOMKeyInfo)keyInfo; 
110
111
        Key key = new Key() {