1761727 converted unit test programs to JUnit tests and updated the build targets

This commit is contained in:
clay_shooter
2007-07-27 03:28:44 +00:00
parent bfdc36ad30
commit 78c7ddf199
71 changed files with 1459 additions and 1257 deletions

View File

@@ -5,7 +5,7 @@
Created Feb 4, 2005 1:23:05 PM as part of migration from ANT Created Feb 4, 2005 1:23:05 PM as part of migration from ANT
Last Modified March 24, 2007 Last Modified March 24, 2007
Tested on Eclipse 3.2 with the Callisto plugis, Ant 1.6.1 and MS Visual C++ 8 (2005) Tested on Eclipse 3.3 with the Europa C++ plugins, Ant 1.7 and MS Visual C++ 8 (2005)
Eclipse users are pretty lucky because the whole project Eclipse users are pretty lucky because the whole project
can be built inside eclipse due to their built in ANT support. can be built inside eclipse due to their built in ANT support.
@@ -55,6 +55,8 @@
<property name="generated.filename.jar" value="jacob.jar" /> <property name="generated.filename.jar" value="jacob.jar" />
<property name="generated.filename.zip" value="jacob_${version}" /> <property name="generated.filename.zip" value="jacob_${version}" />
<property name="junit.jar" value="${basedir}\lib\junit3.8.1\junit.jar" />
<property name="src.java.jacob" value="${basedir}/src" /> <property name="src.java.jacob" value="${basedir}/src" />
<property name="src.java.samples" value="${basedir}/samples" /> <property name="src.java.samples" value="${basedir}/samples" />
<property name="src.java.unittest" value="${basedir}/unittest" /> <property name="src.java.unittest" value="${basedir}/unittest" />
@@ -206,12 +208,24 @@
<!-- ====================================================================== <!-- ======================================================================
Compile the java files and copy version.properties to be jar'd up Compile the java files and copy version.properties to be jar'd up
Relies on ant recognizing when a file needs to be compiled Relies on ant recognizing when a file needs to be compiled
Unit tests compiled seperately because of junit dependency
================================================================== --> ================================================================== -->
<target name="javaCompile" > <target name="javaCompile" >
<echo>Building Jacob , sample and, test classes in ${release.dir.java}</echo> <echo>Building Jacob classes in ${release.dir.java}</echo>
<javac srcdir="${src.java.jacob}:${src.java.samples}:${src.java.unittest}" <javac srcdir="${src.java.jacob}"
destdir="${release.dir.java}" destdir="${release.dir.java}"
listfiles="true" debug="on" source="1.4" /> listfiles="true" debug="on" source="1.4" />
<echo>Building sample classes in ${release.dir.java}</echo>
<javac srcdir="${src.java.samples}"
destdir="${release.dir.java}"
classpath="${release.dir.java}"
listfiles="true" debug="on" source="1.4" />
<echo>Building Jacob test classes in ${release.dir.java} using junit jar ${junit.jar}</echo>
<javac srcdir="${src.java.unittest}"
destdir="${release.dir.java}"
classpath="${release.dir.java}:${junit.jar}"
listfiles="true" debug="on" source="1.4" />
<copy file="version.properties" todir="${release.dir.java}"/> <copy file="version.properties" todir="${release.dir.java}"/>
</target> </target>
<!-- ====================================================================== <!-- ======================================================================
@@ -228,7 +242,7 @@
<exclude name="**/CVS" /> <exclude name="**/CVS" />
<!-- exclude all unit tests (ending in Test) <!-- exclude all unit tests (ending in Test)
and everything in the samples and test packages --> and everything in the samples and test packages -->
<exclude name="com/**/*Test.class"/> <exclude name="com/**/*Test*.class"/>
<exclude name="com/jacob/samples/**"/> <exclude name="com/jacob/samples/**"/>
<exclude name="com/jacob/test/**"/> <exclude name="com/jacob/test/**"/>
<include name="com/**/*.class" /> <include name="com/**/*.class" />
@@ -436,5 +450,34 @@
<zipfileset dir="${basedir}" prefix="${generated.filename.zip}" includes="LICENSE.* version.properties" /> <zipfileset dir="${basedir}" prefix="${generated.filename.zip}" includes="LICENSE.* version.properties" />
</zip> </zip>
</target> </target>
<!-- ======================================================================
JUnit testing
This should probably be dependent on dll also
This assumes we are always testing on x86
This assumes that ant-junit is available
================================================================== -->
<target name='test' depends='javaCompile' >
<junit printsummary="yes"
haltonfailure="yes"
fork="true"
dir="${release.dir.java}"
>
<sysproperty key="java.library.path" value="${release.dir.x86}" />
<classpath>
<pathelement location="${junit.jar}"/>
<pathelement location="${release.dir.java}"/>
<pathelement path="${src.java.unittest}"/>
</classpath>
<formatter type="brief" usefile="false"/>
<batchtest>
<!-- use the source directory because it tries to run inner classes
if we use the release directory -->
<fileset dir="${src.java.unittest}">
<include name="**/*.java"/>
</fileset>
</batchtest>
</junit>
</target>
</project> </project>

View File

@@ -17,28 +17,47 @@ Unpack the source archive zip file or check the files out of CVS into d:\jacob
or some other familiar place. Source Java and JNI files are located in seperate or some other familiar place. Source Java and JNI files are located in seperate
packages from the unit tests and the samples. packages from the unit tests and the samples.
<p> <p>
The java code is in .\src.<BR> <ul>
The C++ code is in .\jni.<br> <li>docs: documentation
Code is compiled into .\release<br> <li>jni: c++ code
<li>lib: libraries needed to compile unit tests
<li>release: a directory built by the ant script where jacob is constructed
<li>samples: sample programs
<li>src: Jacob Java source files
<li>unittest: JUnit 3.8.1 unit test programs. Run from the test target in build.xml
<li>vstudio: some out of date VC++ project files
<li>bulid.xml: the ant build script. It can be run from inside Eclipse
</ul>
<p> <p>
The Servlet examples that required j2ee libraries to compile have temporarily The Servlet examples that required j2ee libraries to compile have temporarily
been removed. been removed.
<p> <p>
<H1>Development Environment</h1> <H1>Development Environment</h1>
The simplest build environment includes MS Visual C++ 8.0 (Studio 2005), The simplest build environment includes MS Visual C++ 8.0 (Studio 2005),
Eclipse 3.2 with the C/C++ module and JDK 1.4. Eclipse 3.3 with the C/C++ module and JDK 1.4.
In that situation, you would just create the <i>compilation_tools.properties</i> In that situation, you would just create the <i>compilation_tools.properties</i>
using the example build.xml as a template. All of the releases, up through 1.12, using the example build.xml as a template.
were built using Visual C++ 6.0. 64 bit builds are supported starting with release 1.11.
Microsoft Visual C++ 8.0 supports 64 bit builds. so no additional tools are required.
<UL> <UL>
<li> Microsoft Visual C++ 8.0 and it's included library. (to D:\apps in my case) <li> Microsoft Visual C++ 8.0 and it's included library. (to D:\apps in my case)
<li> Eclipse 3.2 or later from www.eclipse.org. I use the C/C++ plugin for <li> Eclipse 3.3 or later from www.eclipse.org as the Java IDE.
eclipse rather than MS Visual Studio <li> Eclipse 3.3 or later with the C/C++ plugin can be used for C coding in place of VC++ IDE.
<li> Java JDK 1.4 (1.12 was built using 1.4.2.13) Compilation using JDK 1.5 has not been tested <li> Java JDK 1.4 (1.12 was built using 1.4.2.13) Compilation using JDK 1.5 has not been tested
</ul> </ul>
<p> <p>
<p>
<table>
<TR><TD>Release</TD><TD>C Version</TD><TD>Java Version</TD><TD>ANT Version</TD><TD>Eclipse Version Used</TD><TD>generated DLLs</TD></TR>
<TR><TD>up to 1.6</TD><TD>VC 98 (6.0)</TD><TD>?</TD><td>Used MAKE</td><TD>?</TD><TD>32 bit</TD></TR>
<TR><TD>1.7</TD><TD>VC 98 (6.0)</TD><TD>1.4</TD><td>1.?</td><TD>?</TD><TD>32 bit</TD></TR>
<TR><TD>1.8</TD><TD>VC 98 (6.0)</TD><TD>1.4</TD><td>1.?</td><TD>?</TD><TD>32 bit</TD></TR>
<TR><TD>1.9</TD><TD>VC 98 (6.0)</TD><TD>1.4</TD><td>1.?</td><TD>?</TD><TD>32 bit</TD></TR>
<TR><TD>1.10</TD><TD>VC 98 (6.0)</TD><TD>1.4</TD><td>1.?</td><TD>3.??</TD><TD>32 bit</TD></TR>
<TR><TD>1.11</TD><TD>VC 98 (6.0) & 2003 64bit libs</TD><TD>1.4.?</TD><td>1.6.?</td><TD>3.2.1</TD><TD>32 and 64 bit</TD></TR>
<TR><TD>1.12</TD><TD>VC 98 (6.0) & 2003 64bit libs</TD><TD>1.4.2</TD><td>1.6.5</td><TD>3.2.2</TD><TD>32 and 64 bit</TD></TR>
<TR><TD>1.13</TD><TD>VC 2005</TD><TD>1.4.2</TD><TD>1.7.0</TD><TD>3.3</TD><TD>32 and 64 bit</TD></TR>
</table>
Microsoft Visual C++ 8.0 supports 64 bit builds. so no additional tools are required.
<p> <p>
<H1>Build Process</H1> <H1>Build Process</H1>
@@ -85,18 +104,20 @@ Open up the project properties and go to the "Java Build Path" properties panel.
<li> Add folders <code>samples</code>, <code>src</code> and <code>unittest</code> <li> Add folders <code>samples</code>, <code>src</code> and <code>unittest</code>
to the build path in the Source tab.</li> to the build path in the Source tab.</li>
<li> Exclude *.txt from each of the newly added folders. </li> <li> Exclude *.txt from each of the newly added folders. </li>
<li> Set the build output directory to <code>jacob-project/release/java</code></li> <li> Set the default build output directory to <code>jacob-project/release/java</code></li>
</ul> </ul>
<h1> Running Samples and Tests </h1> <h1> Running Samples and Tests </h1>
Samples and test programs can be found in the source jar or in CVS. The programs Samples and JUnit test programs can be found in the source jar or in CVS. The programs
can be run from a bat file or from inside the Eclipse IDE. The java library can be run from a bat file or from inside the Eclipse IDE. The java library
path variable must be set to include the directory the jacob.dll is in. The path variable must be set to include the directory the jacob.dll is in. The
simplest way to do that is to add it as a command line option. simplest way to do that is to add it as a command line option.
<p>
JUnit test programs can be individually run from inside eclipse or en-masse
via the <code>ant test</code> target.
Last Modified 7/2007 1.13M3
Last Modified 4/2007
</BODY> </BODY>
</HTML> </HTML>

View File

@@ -8,7 +8,10 @@
Now compiles with with Visual Studio 2005 (M1). Now compiles with with Visual Studio 2005 (M1).
</li> </li>
<li> <li>
Changed milestone release naming convetion from "pre..." to "M..." Changed milestone release naming convention from "pre..." to "M..."
</li>
<li>
unittest directory now a JUnit 3.8.1 test repository
</li> </li>
</ul> </ul>
@@ -45,6 +48,11 @@
<tr> <tr>
<td width="100%" colspan="2"><b>Feature Requests</b></td> <td width="100%" colspan="2"><b>Feature Requests</b></td>
</tr> </tr>
<tr>
<td width="13%" valign="top">1761727</td>
<td width="87%" valign="top">(M3) unittest directory test programs
converted to JUnit 3.8.1. New ANT target created to run all unit tests. </td>
</tr>
<tr> <tr>
<td width="13%" valign="top">&nbsp;</td> <td width="13%" valign="top">&nbsp;</td>
<td width="87%" valign="top">&nbsp;</td> <td width="87%" valign="top">&nbsp;</td>

BIN
lib/junit3.8.1/junit.jar Normal file

Binary file not shown.

View File

@@ -1,4 +1,4 @@
package com.jacob.test.MathProj; package com.jacob.samples.MathProj;
import com.jacob.activeX.ActiveXComponent; import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.*; import com.jacob.com.*;

View File

@@ -1,4 +1,4 @@
package com.jacob.test.atl; package com.jacob.samples.atl;
import com.jacob.com.*; import com.jacob.com.*;
import com.jacob.activeX.*; import com.jacob.activeX.*;

View File

@@ -1,6 +1,7 @@
package com.jacob.com; package com.jacob.com;
import com.jacob.activeX.ActiveXComponent; import com.jacob.activeX.ActiveXComponent;
import com.jacob.test.BaseTestCase;
/** /**
* This exercises the two Dispatch factor methods that let you * This exercises the two Dispatch factor methods that let you
@@ -9,8 +10,9 @@ import com.jacob.activeX.ActiveXComponent;
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options. * Look in the docs area at the Jacob usage document for command line options.
*/ */
public class ActiveXComponentFactoryTest { public class ActiveXComponentFactoryTest extends BaseTestCase {
public static void main(String args[]) throws Exception {
public void testActiveXComponentFactory(){
ComThread.InitSTA(true); ComThread.InitSTA(true);
try { try {
System.out.println("This test only works if MS Word is NOT already running"); System.out.println("This test only works if MS Word is NOT already running");
@@ -31,26 +33,27 @@ public class ActiveXComponentFactoryTest {
} }
ActiveXComponent mTryConnectingThird = ActiveXComponent.connectToActiveInstance(mApplicationId); ActiveXComponent mTryConnectingThird = ActiveXComponent.connectToActiveInstance(mApplicationId);
if (mTryConnectingThird == null ){ if (mTryConnectingThird == null ){
System.out.println("was unable able to connect to MSWord after previous startup"); fail("Was unable able to connect to MSWord after previous startup");
} else { } else {
System.out.println("Correctly could connect to running MSWord"); System.out.println("Stopping MSWord");
// stop it so we can fail trying to connect to a running // stop it so we can fail trying to connect to a running
mTryConnectingThird.invoke("Quit",new Variant[] {}); mTryConnectingThird.invoke("Quit",new Variant[] {});
System.out.println(" Word stopped");
} }
Thread.sleep(2000); Thread.sleep(2000);
ActiveXComponent mTryConnectingFourth = ActiveXComponent.connectToActiveInstance(mApplicationId); ActiveXComponent mTryConnectingFourth = ActiveXComponent.connectToActiveInstance(mApplicationId);
if (mTryConnectingFourth != null ){ if (mTryConnectingFourth != null ){
System.out.println("Was able to connect to MSWord that was stopped");
mTryConnectingFourth.invoke("Quit",new Variant[] {}); mTryConnectingFourth.invoke("Quit",new Variant[] {});
fail("Was able to connect to MSWord that was stopped");
} else { } else {
System.out.println("Correctly could not connect to running MSWord"); System.out.println("Correctly could not connect to running MSWord");
} }
} catch (InterruptedException ie){
} catch (ComException e) { } catch (ComException e) {
e.printStackTrace(); e.printStackTrace();
fail("Caught COM exception");
} finally { } finally {
System.out.println("About to sleep for 2 seconds so we can bask in the glory of this success"); //System.out.println("About to sleep for 2 seconds so we can bask in the glory of this success");
Thread.sleep(2000); //Thread.sleep(2000);
ComThread.Release(); ComThread.Release();
ComThread.quitMainSTA(); ComThread.quitMainSTA();
} }

View File

@@ -4,35 +4,36 @@ import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import com.jacob.com.DateUtilities; import junit.framework.TestCase;
/** /**
* test cases that should exercise the new date conversion code * test cases that should exercise the new date conversion code
* <p> * <p>
* May need to run with some command line options (including from inside Eclipse). * This test does not require any command line options because it is only a utility test
* Look in the docs area at the Jacob usage document for command line options.
*/ */
public class DateUtilitiesTest { public class DateUtilitiesTest extends TestCase {
public static void main(String[] args) public void testDateUtilities(){
{
Date now = new Date(); Date now = new Date();
double comTimeForNow = DateUtilities.convertDateToWindowsTime(now); double comTimeForNow = DateUtilities.convertDateToWindowsTime(now);
Date retrievedNow = DateUtilities.convertWindowsTimeToDate(comTimeForNow); Date retrievedNow = DateUtilities.convertWindowsTimeToDate(comTimeForNow);
if (!now.equals(retrievedNow)){ if (!now.equals(retrievedNow)){
System.out.println("DateUtilities Date Test failed " +now+ " != " +retrievedNow ); fail("DateUtilities Date Test failed " +now+ " != " +retrievedNow );
} else { } else {
System.out.println("DateUtilities Date Test passed"); System.out.println("DateUtilities Date Test passed");
} }
}
public void testBeginningOfWindowsTime(){
// this is a magic time in the windows world // this is a magic time in the windows world
Date beginningOfWindowsTime = Date beginningOfWindowsTime =
new GregorianCalendar(1899, Calendar.DECEMBER, 30).getTime(); new GregorianCalendar(1899, Calendar.DECEMBER, 30).getTime();
double comTimeForBeginningOfWindowsTime = double comTimeForBeginningOfWindowsTime =
DateUtilities.convertDateToWindowsTime(beginningOfWindowsTime); DateUtilities.convertDateToWindowsTime(beginningOfWindowsTime);
if (comTimeForBeginningOfWindowsTime > 0){ if (comTimeForBeginningOfWindowsTime > 0){
System.out.println("Beginning of windows time test failed " fail("Beginning of windows time test failed "
+comTimeForBeginningOfWindowsTime); +comTimeForBeginningOfWindowsTime);
} else { } else {
System.out.println("Beginning of windows time test passed"); System.out.println("Beginning of windows time test passed");

View File

@@ -1,20 +1,22 @@
package com.jacob.com; package com.jacob.com;
import com.jacob.test.BaseTestCase;
/** /**
* This test verifies that the Dispatch object protects itself when * This test verifies that the Dispatch object protects itself when
* the constructor is called with a null program id. * the constructor is called with a null program id.
* Prior to this protection, the VM might crash.m * Prior to this protection, the VM might crash.m
* @author joe * <p>
* * May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options.
*/ */
public class DispatchNullProgramId { public class DispatchNullProgramId extends BaseTestCase {
public static void main(String[] args) { public void testNullProgramId(){
try { try {
String nullParam = null; String nullParam = null;
new Dispatch(nullParam); new Dispatch(nullParam);
System.out.println( fail("the dispatch failed to protect itself from null program ids");
"the dispatch failed to protect itself from null program ids");
} catch (IllegalArgumentException iae){ } catch (IllegalArgumentException iae){
System.out.println( System.out.println(
"the dispatch protected itself from null program ids"); "the dispatch protected itself from null program ids");
@@ -22,8 +24,7 @@ public class DispatchNullProgramId {
try { try {
String nullParam = ""; String nullParam = "";
new Dispatch(nullParam); new Dispatch(nullParam);
System.out.println( fail("the dispatch failed to protect itself from empty string program ids");
"the dispatch failed to protect itself from empty string program ids");
} catch (IllegalArgumentException iae){ } catch (IllegalArgumentException iae){
System.out.println( System.out.println(
"the dispatch protected itself from empty string program ids"); "the dispatch protected itself from empty string program ids");

View File

@@ -2,30 +2,23 @@ package com.jacob.com;
import java.util.Date; import java.util.Date;
import com.jacob.test.BaseTestCase;
/** /**
* Test some of the Dispatch utility methods * Test some of the Dispatch utility methods
* <p>
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside Eclipse).
* If so, then try these * Look in the docs area at the Jacob usage document for command line options.
* <pre>
* -Djava.library.path=d:/jacob/release/x86
* -Dcom.jacob.autogc=false
* -Dcom.jacob.debug=false
* -Xcheck:jni
* </pre>
*/ */
public class DispatchTest { public class DispatchTest extends BaseTestCase {
public static void main(String[] args) public void testDispatch() {
{
Date testDate = new Date(); Date testDate = new Date();
Variant fromDate = Dispatch.obj2variant(testDate); Variant fromDate = Dispatch.obj2variant(testDate);
Date returnedDate = fromDate.getJavaDate(); Date returnedDate = fromDate.getJavaDate();
System.out.println("test date is "+testDate); //System.out.println("test date is "+testDate);
System.out.println("VariantDate is "+fromDate.getJavaDate()); //System.out.println("VariantDate is "+fromDate.getJavaDate());
if (testDate.equals(returnedDate)){ assertTrue("Could not call obj2variant(Date) and get it to work",
testDate.equals(returnedDate));
} else {
System.out.println("Could not call obj2variant(Date) and get it to work");
}
} }
} }

View File

@@ -1,29 +1,28 @@
package com.jacob.com; package com.jacob.com;
import com.jacob.test.BaseTestCase;
/** /**
* Test armoring of dispatch static methods * Test armoring of dispatch static methods
* <p>
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside Eclipse).
* If so, then try these * Look in the docs area at the Jacob usage document for command line options.
* <pre>
* -Djava.library.path=d:/jacob/release/x86
* -Dcom.jacob.autogc=false
* -Dcom.jacob.debug=false
* -Xcheck:jni
* </pre>
*/ */
public class DispatchValidDispatchTest { public class DispatchValidDispatchTest extends BaseTestCase {
public static void main(String[] args) public void testThrowIllegalArgumentException() {
{
try { try {
Dispatch.call(null, 0); Dispatch.call(null, 0);
System.out.println("Failed to throw IllegalArgumentException"); fail("Failed to throw IllegalArgumentException");
} catch (IllegalArgumentException iae){ } catch (IllegalArgumentException iae){
System.out.println("Caught correct IllegalArgumentException: "+iae); System.out.println("Caught correct IllegalArgumentException: "+iae);
} }
}
public void testThrowIllegalStateException() {
try { try {
Dispatch foo = new Dispatch(); Dispatch foo = new Dispatch();
Dispatch.call(foo, 0); Dispatch.call(foo, 0);
fail("Failed to throw IllegalStateException");
} catch (IllegalStateException ise){ } catch (IllegalStateException ise){
System.out.println("Caught correct IllegalStateException "+ise); System.out.println("Caught correct IllegalStateException "+ise);
} }

View File

@@ -1,24 +1,15 @@
package com.jacob.com; package com.jacob.com;
import com.jacob.test.BaseTestCase;
/** /**
* This will eventually be changed to a unit test. * This will eventually be changed to a unit test.
* <p> * <p>
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside Eclipse).
* If so, then try these * Look in the docs area at the Jacob usage document for command line options.
* <pre>
* -Djava.library.path=d:/jacob/release/x86
* -Dcom.jacob.autogc=false
* -Dcom.jacob.debug=false
* -Xcheck:jni
* </pre>
*/ */
public class JacobObjectTest { public class JacobObjectTest extends BaseTestCase {
public static void main(String args[]) throws Exception
{
JacobObjectTest testJig = new JacobObjectTest();
testJig.testBuildVersion();
}
public void testBuildVersion(){ public void testBuildVersion(){
System.out.println("build version is "+JacobObject.getBuildVersion()); System.out.println("build version is "+JacobObject.getBuildVersion());

View File

@@ -1,92 +1,85 @@
package com.jacob.com; package com.jacob.com;
import com.jacob.test.BaseTestCase;
/** /**
* This test class exists to test the WeakRefernce implementation . * This test class exists to test the WeakRefernce implementation .
* *
* It is not useful if there isn't one at this time * It is not useful if there isn't one at this time
* *
* This will eventually be changed to a unit test.
*
* <p> * <p>
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside
* Look in the docs area at the Jacob usage document for command line options. * Eclipse). Look in the docs area at the Jacob usage document for command line
* options.
*/ */
public class ROT2Test public class ROT2Test extends BaseTestCase {
{
public static void main(String args[]) throws Exception public void testDoesNotBlowUp() {
{
ROT2TestThread threads[] = new ROT2TestThread[4]; ROT2TestThread threads[] = new ROT2TestThread[4];
for (int i = 0; i < threads.length; i++) for (int i = 0; i < threads.length; i++) {
{
threads[i] = new ROT2TestThread("thread-" + i, 3000); threads[i] = new ROT2TestThread("thread-" + i, 3000);
} }
for (int i = 0; i < threads.length; i++) for (int i = 0; i < threads.length; i++) {
{
threads[i].start(); threads[i].start();
} }
} }
}
/** /**
* This wil try and exercise the thread support in the ROT * This will try and exercise the thread support in the ROT
**/ */
class ROT2TestThread extends Thread public class ROT2TestThread extends Thread {
{
private java.util.List ThreadObjects; private java.util.List ThreadObjects;
private int initialRunSize = 0; private int initialRunSize = 0;
/** /**
* @param arg0 * @param arg0
*/ */
public ROT2TestThread(String arg0, int iStartCount) public ROT2TestThread(String arg0, int iStartCount) {
{
super(arg0); super(arg0);
initialRunSize = iStartCount; initialRunSize = iStartCount;
} }
/** /**
* A semi-complexe serie of steps to put the ROT under stress. 1) discard * A semi-complexe serie of steps to put the ROT under stress. 1)
* half the objects we've created 2) if size is greater than 1 but not a * discard half the objects we've created 2) if size is greater than 1
* even number, add 1 new object 3) stop when size is 1. * but not a even number, add 1 new object 3) stop when size is 1.
* *
* @see java.lang.Runnable#run() * @see java.lang.Runnable#run()
*/ */
public void run() public void run() {
{
// something that keeps object references around // something that keeps object references around
// so the gc can't collect them // so the gc can't collect them
// we need to create these in the thread so they end up in the right ROT table // we need to create these in the thread so they end up in the right
// ROT table
ThreadObjects = new java.util.ArrayList(initialRunSize); ThreadObjects = new java.util.ArrayList(initialRunSize);
for (int i = 0; i < initialRunSize; i++) for (int i = 0; i < initialRunSize; i++) {
{
// create the object // create the object
Variant aNewVariant = new Variant(getName() + "_" + i); Variant aNewVariant = new Variant(getName() + "_" + i);
// create a hard reference to it // create a hard reference to it
ThreadObjects.add(aNewVariant); ThreadObjects.add(aNewVariant);
} }
while (ThreadObjects.size() > 1) while (ThreadObjects.size() > 1) {
{
String message = ""; String message = "";
message = getName() + " Workingset=" + ThreadObjects.size() message = getName() + " Workingset=" + ThreadObjects.size()
+ " ROT: "; + " ROT: ";
message += "(before additions and gc "+ROT.getThreadObjects(false).size()+")"; message += "(before additions and gc "
+ ROT.getThreadObjects(false).size() + ")";
// if there is an odd number of objects greater than 2 // if there is an odd number of objects greater than 2
if (ThreadObjects.size() > 2 && ThreadObjects.size() % 2 != 0) if (ThreadObjects.size() > 2 && ThreadObjects.size() % 2 != 0) {
{
// add a new object // add a new object
Variant aNewVariant = new Variant(getName() + "_*" + ThreadObjects.size()); Variant aNewVariant = new Variant(getName() + "_*"
+ ThreadObjects.size());
ThreadObjects.add(aNewVariant); ThreadObjects.add(aNewVariant);
} }
// now iterate across all the objects in our list // now iterate across all the objects in our list
for (int i = ThreadObjects.size(); i > 0; i--) for (int i = ThreadObjects.size(); i > 0; i--) {
{
// removing every other one? // removing every other one?
if (i % 2 == 0) if (i % 2 == 0) {
{
// remove the reference so gc can get it // remove the reference so gc can get it
ThreadObjects.remove(i - 1); ThreadObjects.remove(i - 1);
} }
@@ -95,27 +88,30 @@ class ROT2TestThread extends Thread
try { try {
// simulate the system under load and run the GC // simulate the system under load and run the GC
// should end up with weak references with no objects attached // should end up with weak references with no objects
// attached
Thread.sleep(9); Thread.sleep(9);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// the VM doesn't want us to sleep anymore, // the VM doesn't want us to sleep anymore,
// so get back to work // so get back to work
} }
message += " (before gc, after additions "+ROT.getThreadObjects(false).size()+")"; message += " (before gc, after additions "
+ ROT.getThreadObjects(false).size() + ")";
System.gc(); System.gc();
message += " (after System.gc "+ROT.getThreadObjects(false).size()+")"; message += " (after System.gc "
+ ROT.getThreadObjects(false).size() + ")";
System.out.println(message); System.out.println(message);
} }
} }
/** /**
* Another test would be to overide this to always return the same name. * Another test would be to override this to always return the same name.
* That would really screw the ROT! * That would really screw the ROT!
* *
* @see java.lang.Object#toString() * @see java.lang.Object#toString()
*/ */
public String toString() public String toString() {
{
return super.toString(); return super.toString();
} }
} }
}

View File

@@ -1,109 +1,108 @@
package com.jacob.com; package com.jacob.com;
import com.jacob.test.BaseTestCase;
/** /**
* This trys to exercise ROT's garbage collecion * This tries to exercise ROT's garbage collection This is named this way because
* This is named this way because the build.xml * the build.xml ignores files ending in Test when building the binary zip file
* ignores files ending in Test when building the binary zip file
* *
* This will eventually be changed to a unit test. * This will eventually be changed to a unit test.
* *
* <p> * <p>
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside
* Look in the docs area at the Jacob usage document for command line options. * Eclipse). Look in the docs area at the Jacob usage document for command line
* options.
*/ */
public class ROT3Test public class ROT3Test extends BaseTestCase {
{
public static void main(String args[]) throws Exception public void testROTVersion3() {
{
ROT3TestThread threads[] = new ROT3TestThread[4]; ROT3TestThread threads[] = new ROT3TestThread[4];
for (int i = 0; i < threads.length; i++) for (int i = 0; i < threads.length; i++) {
{
threads[i] = new ROT3TestThread("thread-" + i, 3000 + i * 10); threads[i] = new ROT3TestThread("thread-" + i, 3000 + i * 10);
} }
for (int i = 0; i < threads.length; i++) for (int i = 0; i < threads.length; i++) {
{
threads[i].start(); threads[i].start();
} }
} }
}
/** /**
* This wil try and exercise the thread support in the ROT * This will try and exercise the thread support in the ROT
**/ */
class ROT3TestThread extends Thread public class ROT3TestThread extends Thread {
{
private java.util.List variansCreatedInThisThread; private java.util.List variansCreatedInThisThread;
private int initialRunSize = 0; private int initialRunSize = 0;
/** /**
* @param arg0 * @param arg0
*/ */
public ROT3TestThread(String arg0, int iStartCount) public ROT3TestThread(String arg0, int iStartCount) {
{
super(arg0); super(arg0);
initialRunSize = iStartCount; initialRunSize = iStartCount;
} }
/** /**
* A semi-complexe serie of steps to put the ROT under stress. 1) discard * A semi-complexe serie of steps to put the ROT under stress. 1)
* half the objects we've created 2) if size is greater than 1 but not a * discard half the objects we've created 2) if size is greater than 1
* even number, add 1 new object 3) stop when size is 1. * but not a even number, add 1 new object 3) stop when size is 1.
* *
* @see java.lang.Runnable#run() * @see java.lang.Runnable#run()
*/ */
public void run() public void run() {
{
// something that keeps object references around // something that keeps object references around
// so the gc can't collect them // so the gc can't collect them
// we need to create these in the thread so they end up in the right ROT table // we need to create these in the thread so they end up in the right
// ROT table
variansCreatedInThisThread = new java.util.ArrayList(initialRunSize); variansCreatedInThisThread = new java.util.ArrayList(initialRunSize);
for (int i = 0; i < initialRunSize; i++) for (int i = 0; i < initialRunSize; i++) {
{
// create the object // create the object
Variant aNewVariant = new Variant(getName() + "_" + i); Variant aNewVariant = new Variant(getName() + "_" + i);
// create a hard reference to it // create a hard reference to it
variansCreatedInThisThread.add(aNewVariant); variansCreatedInThisThread.add(aNewVariant);
} }
while (variansCreatedInThisThread.size() > 1) while (variansCreatedInThisThread.size() > 1) {
{
String message = ""; String message = "";
message = getName()+" Workingset=" +variansCreatedInThisThread.size() message = getName() + " Workingset="
+" ROT threadObject hashCode: "+ROT.getThreadObjects(true).hashCode(); + variansCreatedInThisThread.size()
message += " size before mods and gc "+ROT.getThreadObjects(true).size()+")"; + " ROT threadObject hashCode: "
// If there are more than 10 objects in our cache then add 1/4 of that again + ROT.getThreadObjects(true).hashCode();
if (variansCreatedInThisThread.size() > 10) message += " size before mods and gc "
{ + ROT.getThreadObjects(true).size() + ")";
// If there are more than 10 objects in our cache then add 1/4
// of that again
if (variansCreatedInThisThread.size() > 10) {
message += " (adding) "; message += " (adding) ";
// add an additional 1/4 of our current number // add an additional 1/4 of our current number
for (int i = 0; i < variansCreatedInThisThread.size() / 4; i++) { for (int i = 0; i < variansCreatedInThisThread.size() / 4; i++) {
// add a new object // add a new object
Variant aNewVariant = new Variant(getName() + "_*" + variansCreatedInThisThread.size()); Variant aNewVariant = new Variant(getName() + "_*"
+ variansCreatedInThisThread.size());
variansCreatedInThisThread.add(aNewVariant); variansCreatedInThisThread.add(aNewVariant);
} }
} }
// now iterate across 1/2 the objects in our list // now iterate across 1/2 the objects in our list
message += " (removing) "; message += " (removing) ";
for (int i = variansCreatedInThisThread.size(); i > 0; i--) for (int i = variansCreatedInThisThread.size(); i > 0; i--) {
{
// removing every other one? // removing every other one?
if (i % 2 == 0) if (i % 2 == 0) {
{
// remove the reference so gc can get it // remove the reference so gc can get it
if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) { if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) {
// uses deprecated API to set up a special situation // uses deprecated API to set up a special situation
// because this is an ROT test // because this is an ROT test
ROT.removeObject((JacobObject)variansCreatedInThisThread.get(i-1)); ROT
.removeObject((JacobObject) variansCreatedInThisThread
.get(i - 1));
} }
variansCreatedInThisThread.remove(i - 1); variansCreatedInThisThread.remove(i - 1);
} }
} }
message += " (after mods "+ROT.getThreadObjects(true).size()+")"; message += " (after mods " + ROT.getThreadObjects(true).size()
+ ")";
// comm // comm
if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) { if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) {
ROT.clearObjects(); ROT.clearObjects();
@@ -115,7 +114,8 @@ class ROT3TestThread extends Thread
} catch (InterruptedException ie) { } catch (InterruptedException ie) {
} }
message += " (after gc "+ROT.getThreadObjects(true).size()+")"; message += " (after gc " + ROT.getThreadObjects(true).size()
+ ")";
message += " Should see GC if debug turned on..."; message += " Should see GC if debug turned on...";
System.out.println(message); System.out.println(message);
} }
@@ -127,8 +127,8 @@ class ROT3TestThread extends Thread
* *
* @see java.lang.Object#toString() * @see java.lang.Object#toString()
*/ */
public String toString() public String toString() {
{
return super.toString(); return super.toString();
} }
} }
}

View File

@@ -1,27 +1,15 @@
package com.jacob.com; package com.jacob.com;
import com.jacob.com.ROT; import com.jacob.test.BaseTestCase;
/** /**
* This trys to exercise ROT's garbage collecion * This tries to exercise ROT's garbage collection
* *
* This will eventually be changed to a unit test. * This will eventually be changed to a unit test.
* <p> * <p>
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside Eclipse).
* If so, then try these * Look in the docs area at the Jacob usage document for command line options.
* <pre>
* -Djava.library.path=d:/jacob/release/x86
* -Dcom.jacob.autogc=false
* -Dcom.jacob.debug=false
* -Xcheck:jni
* </pre>
*/ */
public class ROTTest { public class ROTTest extends BaseTestCase {
public static void main(String args[]) throws Exception
{
ROTTest testJig = new ROTTest();
testJig.testDontFillROTSystemProperty();
testJig.testGCBehavior();
}
/** /**
* verify the SystemProperty (classname).PutInROT functions as expected. * verify the SystemProperty (classname).PutInROT functions as expected.

View File

@@ -2,7 +2,7 @@ package com.jacob.com;
import java.util.Date; import java.util.Date;
import com.jacob.com.Variant; import com.jacob.test.BaseTestCase;
/** /**
* test cases that should exercise the new date conversion code * test cases that should exercise the new date conversion code
@@ -10,32 +10,37 @@ import com.jacob.com.Variant;
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options. * Look in the docs area at the Jacob usage document for command line options.
*/ */
public class VariantDateTest { public class VariantDateTest extends BaseTestCase {
public static void main(String[] args) public void testVariantDate() {
{
Date now = new Date(); Date now = new Date();
Variant holder = new Variant(); Variant holder = new Variant();
holder.putDate(now); holder.putDate(now);
Date retrievedNow = holder.getJavaDate(); Date retrievedNow = holder.getJavaDate();
if (!now.equals(retrievedNow)){ if (!now.equals(retrievedNow)){
System.out.println("Variant Date Test failed " +now+ " != " +retrievedNow ); fail("Variant Date Test failed " +now+ " != " +retrievedNow );
} else { } else {
//System.out.println("Variant Date Test passed"); System.out.println("Variant Date Test passed");
} }
}
public void testVariantDateToJavaObject(){
Date now = new Date();
Variant holder = new Variant(now);
for ( int i = 0; i < 30000; i++){ for ( int i = 0; i < 30000; i++){
Variant dateVariant = new Variant(now); Variant dateVariant = new Variant(now);
Date retrievedNow = holder.getJavaDate();
retrievedNow = dateVariant.getJavaDate(); retrievedNow = dateVariant.getJavaDate();
if (!now.equals(retrievedNow)){ if (!now.equals(retrievedNow)){
System.out.println("Variant Date Test (1) failed " +now+ " != " +retrievedNow ); fail("Variant Date Test (1) failed " +now+ " != " +retrievedNow );
} else { } else {
//System.out.println("Variant Date Test (1) passed"); //System.out.println("Variant Date Test (1) passed");
} }
// verify auto typecasting works // verify auto typecasting works
retrievedNow = (Date)dateVariant.toJavaObject(); retrievedNow = (Date)dateVariant.toJavaObject();
if (!now.equals(retrievedNow)){ if (!now.equals(retrievedNow)){
System.out.println("Variant Date Test (2) failed " +now+ " != " +retrievedNow ); fail("Variant Date Test (2) failed " +now+ " != " +retrievedNow );
} else { } else {
//System.out.println("Variant Date Test (2) passed "+retrievedNow); //System.out.println("Variant Date Test (2) passed "+retrievedNow);
} }
@@ -47,7 +52,7 @@ public class VariantDateTest {
System.out.println("int variant returned date"); System.out.println("int variant returned date");
} }
} }
System.out.print("Test finished. All tests passed if no errors before this line"); System.out.print("Test finished. All tests passed.");
} }

View File

@@ -1,63 +0,0 @@
package com.jacob.com;
import java.io.*;
/**
* Verifies serialization works for variants.
* Variant serialization is BROKEN and has been since 1.7
* <p>
* May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options.
*/
class VariantSerializationTest {
static Variant vs1 = new Variant("hi");
static Variant vs2 = new Variant(123.456);
public static void main(String[] args) throws Exception {
doJustSerialization();
compareVariantBytes();
}
private static void compareVariantBytes() throws Exception{
System.out.println("compareVariantBytes");
Variant var1 = new Variant("hello");
Variant var2 = new Variant("hello");
byte[] var1Bytes = var1.SerializationWriteToBytes();
byte[] var2Bytes = var2.SerializationWriteToBytes();
for ( int i = 0 ; i < var1Bytes.length; i++){
if (var1Bytes[i]!=var2Bytes[i]){
System.out.println("variant strings differ at position "+i);
return;
}
}
System.out.println("two strings return identical serialization data");
}
private static void doJustSerialization() throws Exception {
System.out.println("doJustSerialization");
// same thing with serialization
FileOutputStream fos;
FileInputStream fis;
fos = new FileOutputStream("foo.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(vs1);
//oos.writeObject(vs2);
oos.close();
fos.close();
fis = new FileInputStream("foo.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Variant vss1 = null;
Variant vss2 = null;
vss1 = (Variant) ois.readObject();
//vss2 = (Variant) ois.readObject();
ois.close();
fis.close();
System.out.println(vss1);
System.out.println(vss2);
}
}

View File

@@ -2,6 +2,8 @@ package com.jacob.com;
import java.util.Date; import java.util.Date;
import com.jacob.test.BaseTestCase;
/** /**
* runs through some of the get and set methods on Variant * runs through some of the get and set methods on Variant
* *
@@ -9,33 +11,7 @@ import java.util.Date;
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options. * Look in the docs area at the Jacob usage document for command line options.
*/ */
class VariantTest { public class VariantTest extends BaseTestCase {
public static void main(String[] args) {
System.out.println("Testing Started");
VariantTest testJig = new VariantTest();
testJig.testUninitializedVariant();
testJig.testToStringDoesNotConvert();
testJig.testPutsAndGets();
testJig.testSafeReleaseBoolean();
testJig.testSafeReleaseConstant();
testJig.testSafeReleaseString();
testJig.testObjectIsAConstant();
testJig.testSomeChangeVT();
testJig.testByRefToJavaObject();
testJig.testDispatchToJavaObject();
System.out.println("Starting last test");
testJig.testManyThreadedInit();
System.out.println("Testing Complete");
}
/**
* dummy constructor
*
*/
public VariantTest(){
}
/** /**
* This verifies that toJavaObject() works for all of the * This verifies that toJavaObject() works for all of the
@@ -45,21 +21,21 @@ class VariantTest {
* toJavaObject() for the regular. * toJavaObject() for the regular.
* *
*/ */
private void testByRefToJavaObject(){ public void testByRefToJavaObject(){
Variant v = null; Variant v = null;
Variant vByRef = null; Variant vByRef = null;
v = new Variant(new Float(53.3),false); v = new Variant(new Float(53.3),false);
vByRef = new Variant(new Float(53.3),true); vByRef = new Variant(new Float(53.3),true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){ if (!v.toJavaObject().equals(vByRef.toJavaObject())){
System.out.println(v.toString() + " could not make type " fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt() + v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same"); +" java objects come out the same");
} }
v = new Variant(new Double(53.3),false); v = new Variant(new Double(53.3),false);
vByRef = new Variant(new Double(53.3),true); vByRef = new Variant(new Double(53.3),true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){ if (!v.toJavaObject().equals(vByRef.toJavaObject())){
System.out.println(v.toString() + " could not make type " fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt() + v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same"); +" java objects come out the same");
} }
@@ -67,7 +43,7 @@ class VariantTest {
v = new Variant(new Boolean(true),false); v = new Variant(new Boolean(true),false);
vByRef = new Variant(new Boolean(true),true); vByRef = new Variant(new Boolean(true),true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){ if (!v.toJavaObject().equals(vByRef.toJavaObject())){
System.out.println(v.toString() + " could not make type " fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt() + v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same"); +" java objects come out the same");
} }
@@ -75,7 +51,7 @@ class VariantTest {
v = new Variant(new Integer(53),false); v = new Variant(new Integer(53),false);
vByRef = new Variant(new Integer(53),true); vByRef = new Variant(new Integer(53),true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){ if (!v.toJavaObject().equals(vByRef.toJavaObject())){
System.out.println(v.toString() + " could not make type " fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt() + v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same"); +" java objects come out the same");
} }
@@ -83,7 +59,7 @@ class VariantTest {
v = new Variant(new Short((short)53),false); v = new Variant(new Short((short)53),false);
vByRef = new Variant(new Short((short)53),true); vByRef = new Variant(new Short((short)53),true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){ if (!v.toJavaObject().equals(vByRef.toJavaObject())){
System.out.println(v.toString() + " could not make type " fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt() + v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same"); +" java objects come out the same");
} }
@@ -91,7 +67,7 @@ class VariantTest {
v = new Variant("53.33",false); v = new Variant("53.33",false);
vByRef = new Variant("53.33",true); vByRef = new Variant("53.33",true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){ if (!v.toJavaObject().equals(vByRef.toJavaObject())){
System.out.println(v.toString() + " could not make type " fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt() + v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same"); +" java objects come out the same");
} }
@@ -100,7 +76,7 @@ class VariantTest {
v = new Variant(now,false); v = new Variant(now,false);
vByRef = new Variant(now,true); vByRef = new Variant(now,true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){ if (!v.toJavaObject().equals(vByRef.toJavaObject())){
System.out.println(v.toString() + " could not make type " fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt() + v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same"); +" java objects come out the same");
} }
@@ -113,7 +89,7 @@ class VariantTest {
* instead of getDispatch so toString() on dispatch blows up. * instead of getDispatch so toString() on dispatch blows up.
* *
*/ */
private void testDispatchToJavaObject(){ public void testDispatchToJavaObject(){
Variant v2 = new Variant(); Variant v2 = new Variant();
v2.putNothing(); v2.putNothing();
// this test fails even though the exact same code below works fine // this test fails even though the exact same code below works fine
@@ -124,7 +100,7 @@ class VariantTest {
* see what happens when we conver to by ref * see what happens when we conver to by ref
* *
*/ */
private void testSomeChangeVT(){ public void testSomeChangeVT(){
Variant v; Variant v;
// the code shows e shouldn't need to use a returned Variant but the test says we do // the code shows e shouldn't need to use a returned Variant but the test says we do
Variant vConverted; Variant vConverted;
@@ -135,7 +111,7 @@ class VariantTest {
modifier = Variant.VariantShort; modifier = Variant.VariantShort;
vConverted = v.changeType(modifier); vConverted = v.changeType(modifier);
if (vConverted.getvt() != modifier){ if (vConverted.getvt() != modifier){
System.out.println("Failed to change Variant "+originalVT fail("Failed to change Variant "+originalVT
+ " using mask "+modifier + " using mask "+modifier
+ " resulted in "+vConverted.getvt() + " resulted in "+vConverted.getvt()
); );
@@ -144,7 +120,7 @@ class VariantTest {
modifier = Variant.VariantString; modifier = Variant.VariantString;
vConverted = v.changeType(modifier); vConverted = v.changeType(modifier);
if (vConverted.getvt() != modifier){ if (vConverted.getvt() != modifier){
System.out.println("Failed to change Variant "+originalVT fail("Failed to change Variant "+originalVT
+ " using mask "+modifier + " using mask "+modifier
+ " resulted in "+vConverted.getvt() + " resulted in "+vConverted.getvt()
); );
@@ -154,7 +130,7 @@ class VariantTest {
modifier = Variant.VariantByref | Variant.VariantShort; modifier = Variant.VariantByref | Variant.VariantShort;
vConverted = v.changeType(modifier); vConverted = v.changeType(modifier);
if (vConverted.getvt() == modifier){ if (vConverted.getvt() == modifier){
System.out.println("Should not have been able to change Variant "+originalVT fail("Should not have been able to change Variant "+originalVT
+ " using mask "+modifier + " using mask "+modifier
+ " resulted in "+vConverted.getvt() + " resulted in "+vConverted.getvt()
); );
@@ -165,7 +141,7 @@ class VariantTest {
* make sure variant with no backing store works. * make sure variant with no backing store works.
* *
*/ */
private void testUninitializedVariant(){ public void testUninitializedVariant(){
Variant v; Variant v;
// Variants created without parameters are auto set to VariantEmpty // Variants created without parameters are auto set to VariantEmpty
v = new Variant(); v = new Variant();
@@ -182,7 +158,7 @@ class VariantTest {
try { try {
v.toString(); v.toString();
} catch (IllegalStateException ise){ } catch (IllegalStateException ise){
System.out.println("toString() should never throw a runtime exception"); fail("toString() should never throw a runtime exception");
throw new RuntimeException("toString() should not blow up even with uninitialized Variant"); throw new RuntimeException("toString() should not blow up even with uninitialized Variant");
} }
@@ -193,31 +169,31 @@ class VariantTest {
* *
* verify the toString() method does not do type conversion * verify the toString() method does not do type conversion
*/ */
private void testToStringDoesNotConvert(){ public void testToStringDoesNotConvert(){
Variant v; Variant v;
v = new Variant(true); v = new Variant(true);
v.toString(); v.toString();
if (v.getvt() != Variant.VariantBoolean){ if (v.getvt() != Variant.VariantBoolean){
throw new RuntimeException("toString() converted boolean to something else"); throw new RuntimeException("toString() converted boolean to something else");
} else { } else {
//System.out.println("toString() correctly does not convert type"); //fail("toString() correctly does not convert type");
} }
if (v.getBoolean() != true){ if (v.getBoolean() != true){
System.out.println("toString() converted boolean true to "+ v.getBoolean()); fail("toString() converted boolean true to "+ v.getBoolean());
} }
v = new Variant(false); v = new Variant(false);
v.toString(); v.toString();
if (v.getvt() != Variant.VariantBoolean){ if (v.getvt() != Variant.VariantBoolean){
throw new RuntimeException("toString() converted boolean to something else"); throw new RuntimeException("toString() converted boolean to something else");
} else { } else {
//System.out.println("toString() correctly does not convert type"); //fail("toString() correctly does not convert type");
} }
if (v.getBoolean() != false){ if (v.getBoolean() != false){
System.out.println("toString() converted boolean false to "+ v.getBoolean()); fail("toString() converted boolean false to "+ v.getBoolean());
} }
} }
private void testSafeReleaseBoolean(){ public void testSafeReleaseBoolean(){
Variant v; Variant v;
v = new Variant(true); v = new Variant(true);
//System.out.println("Newly created Variant ("+ v.getBoolean()+") "+ //System.out.println("Newly created Variant ("+ v.getBoolean()+") "+
@@ -225,7 +201,7 @@ class VariantTest {
v.safeRelease(); v.safeRelease();
try { try {
v.getBoolean(); v.getBoolean();
System.out.println("IllegalStateException should have been thrown when querying safeReleased object"); fail("IllegalStateException should have been thrown when querying safeReleased object");
throw new RuntimeException("test failed"); throw new RuntimeException("test failed");
} catch (IllegalStateException ise){ } catch (IllegalStateException ise){
//System.out.println("IllegalStateException correctly thrown after safeRelease"); //System.out.println("IllegalStateException correctly thrown after safeRelease");
@@ -239,7 +215,7 @@ class VariantTest {
ComThread.Release(); ComThread.Release();
try { try {
v.getBoolean(); v.getBoolean();
System.out.println("IllegalStateException should have been thrown when querying ComThread.Release"); fail("IllegalStateException should have been thrown when querying ComThread.Release");
throw new RuntimeException("test failed"); throw new RuntimeException("test failed");
} catch (IllegalStateException ise){ } catch (IllegalStateException ise){
//System.out.println("IllegalStateException correctly thrown after ComThread.Release"); //System.out.println("IllegalStateException correctly thrown after ComThread.Release");
@@ -250,11 +226,11 @@ class VariantTest {
* verify the constant values aren't released with safeRelease * verify the constant values aren't released with safeRelease
* *
*/ */
private void testSafeReleaseConstant(){ public void testSafeReleaseConstant(){
//System.out.println("Using Static constant Variant - should never throw access violation"); //System.out.println("Using Static constant Variant - should never throw access violation");
Variant.VT_TRUE.safeRelease(); Variant.VT_TRUE.safeRelease();
if (Variant.VT_TRUE.getBoolean() != true){ if (Variant.VT_TRUE.getBoolean() != true){
System.out.println("VT_TRUE has been broken by SafeRelease()"); fail("VT_TRUE has been broken by SafeRelease()");
throw new RuntimeException("test failed"); throw new RuntimeException("test failed");
} else { } else {
//System.out.println("VT_TRUE survived SafeRelease()"); //System.out.println("VT_TRUE survived SafeRelease()");
@@ -268,7 +244,7 @@ class VariantTest {
ComThread.Release(); ComThread.Release();
if (Variant.VT_TRUE.getBoolean() != true){ if (Variant.VT_TRUE.getBoolean() != true){
System.out.println("VT_TRUE has been broken by ComThread.Release()"); fail("VT_TRUE has been broken by ComThread.Release()");
throw new RuntimeException("test failed"); throw new RuntimeException("test failed");
} else { } else {
//System.out.println("VT_TRUE survived ComThread.Release()"); //System.out.println("VT_TRUE survived ComThread.Release()");
@@ -282,7 +258,7 @@ class VariantTest {
* working after a release * working after a release
* *
*/ */
private void testSafeReleaseString(){ public void testSafeReleaseString(){
String mTestString = "Guitar Hero"; String mTestString = "Guitar Hero";
Variant v = new Variant(mTestString); Variant v = new Variant(mTestString);
//System.out.println("Newly created Variant ("+ v.getString()+") "+ //System.out.println("Newly created Variant ("+ v.getString()+") "+
@@ -290,7 +266,7 @@ class VariantTest {
v.safeRelease(); v.safeRelease();
try { try {
v.getString(); v.getString();
System.out.println("IllegalStateException should have been thrown when querying safeReleased object"); fail("IllegalStateException should have been thrown when querying safeReleased object");
throw new RuntimeException("test failed"); throw new RuntimeException("test failed");
} catch (IllegalStateException ise){ } catch (IllegalStateException ise){
//System.out.println("IllegalStateException correctly thrown after safeRelease"); //System.out.println("IllegalStateException correctly thrown after safeRelease");
@@ -304,22 +280,22 @@ class VariantTest {
public void testObjectIsAConstant(){ public void testObjectIsAConstant(){
Variant v = new Variant("d"); Variant v = new Variant("d");
if (!v.objectIsAConstant(Variant.VT_FALSE)){ if (!v.objectIsAConstant(Variant.VT_FALSE)){
System.out.println("did not recognize VT_FALSE"); fail("did not recognize VT_FALSE");
} }
if (!v.objectIsAConstant(Variant.VT_TRUE)){ if (!v.objectIsAConstant(Variant.VT_TRUE)){
System.out.println("did not recognize VT_TRUE"); fail("did not recognize VT_TRUE");
} }
if (!v.objectIsAConstant(Variant.VT_MISSING)){ if (!v.objectIsAConstant(Variant.VT_MISSING)){
System.out.println("did not recognize VT_MISSING"); fail("did not recognize VT_MISSING");
} }
if (!v.objectIsAConstant(Variant.DEFAULT)){ if (!v.objectIsAConstant(Variant.DEFAULT)){
System.out.println("did not recognize DEFAULT"); fail("did not recognize DEFAULT");
} }
if (v.objectIsAConstant(new Variant(true))){ if (v.objectIsAConstant(new Variant(true))){
System.out.println("confused a boolean with VT_TRUE"); fail("confused a boolean with VT_TRUE");
} }
if (v.objectIsAConstant(new Variant(false))){ if (v.objectIsAConstant(new Variant(false))){
System.out.println("confused a boolean with VT_FALSE"); fail("confused a boolean with VT_FALSE");
} }
@@ -329,81 +305,81 @@ class VariantTest {
* tests put and get methods looking for obvious defects * tests put and get methods looking for obvious defects
* *
*/ */
private void testPutsAndGets(){ public void testPutsAndGets(){
Variant v = new Variant(); Variant v = new Variant();
v.putInt(10); v.putInt(10);
if (v.getInt() != 10){ if (v.getInt() != 10){
System.out.println("int test failed"); fail("int test failed");
} }
v.putShort((short)10); v.putShort((short)10);
if (v.getShort() != 10){ if (v.getShort() != 10){
System.out.println("short test failed"); fail("short test failed");
} }
v.putByte((byte)10); v.putByte((byte)10);
if (v.getByte() != 10){ if (v.getByte() != 10){
System.out.println("int test failed"); fail("int test failed");
} }
v.putFloat(10); v.putFloat(10);
if (v.getFloat() != 10.0){ if (v.getFloat() != 10.0){
System.out.println("float test failed"); fail("float test failed");
} }
v.putDouble(10); v.putDouble(10);
if (v.getDouble() != 10.0){ if (v.getDouble() != 10.0){
System.out.println("double test failed"); fail("double test failed");
} }
v.putString("1234.567"); v.putString("1234.567");
if (!"1234.567".equals(v.getString())){ if (!"1234.567".equals(v.getString())){
System.out.println("string test failed"); fail("string test failed");
} }
v.putBoolean(true); v.putBoolean(true);
if (v.getBoolean() != true){ if (v.getBoolean() != true){
System.out.println("failed boolean test(true)"); fail("failed boolean test(true)");
} }
v.putBoolean(false); v.putBoolean(false);
if (v.getBoolean() != false){ if (v.getBoolean() != false){
System.out.println("failed boolean test(false)"); fail("failed boolean test(false)");
} }
v.putCurrency(123456789123456789L); v.putCurrency(123456789123456789L);
if (v.getCurrency()!=123456789123456789L){ if (v.getCurrency()!=123456789123456789L){
System.out.println("failed currency test"); fail("failed currency test");
} }
Date ourDate = new Date(); Date ourDate = new Date();
v.putDate(ourDate); v.putDate(ourDate);
Date retrievedDate = v.getJavaDate(); Date retrievedDate = v.getJavaDate();
if (!retrievedDate.equals(ourDate)){ if (!retrievedDate.equals(ourDate)){
System.out.println("failed java date load and unload"); fail("failed java date load and unload");
} }
v.putNull(); v.putNull();
if (!v.isNull()){ if (!v.isNull()){
System.out.println("failed detecting set null"); fail("failed detecting set null");
} }
v.putString("something other than null"); v.putString("something other than null");
if (v.isNull()){ if (v.isNull()){
System.out.println("failed null replacement with string"); fail("failed null replacement with string");
} }
v.putEmpty(); v.putEmpty();
if (!v.isNull()){ if (!v.isNull()){
System.out.println("failed detecting set empty as null"); fail("failed detecting set empty as null");
} }
v.putString("something other than null"); v.putString("something other than null");
if (v.isNull()){ if (v.isNull()){
System.out.println("failed empty replacement with string as isNull"); fail("failed empty replacement with string as isNull");
} }
Variant v2 = new Variant(); Variant v2 = new Variant();
v2.putNothing(); v2.putNothing();
if (v2.getvt() != Variant.VariantDispatch){ if (v2.getvt() != Variant.VariantDispatch){
System.out.println("putNothing was supposed to set the type to VariantDispatch"); fail("putNothing was supposed to set the type to VariantDispatch");
} }
if (!v2.isNull()){ if (!v2.isNull()){
System.out.println("putNothing is supposed to cause isNull() to return true"); fail("putNothing is supposed to cause isNull() to return true");
} }
// this line blows up in the test above // this line blows up in the test above
if (v2.toJavaObject() == null){ if (v2.toJavaObject() == null){
System.out.println("putNothing() followed by toJavaObject() should return a Dispatch"); fail("putNothing() followed by toJavaObject() should return a Dispatch");
} }
} }

View File

@@ -0,0 +1,159 @@
package com.jacob.test;
import java.net.URL;
import junit.framework.TestCase;
import com.jacob.com.JacobObject;
/**
* May need to run with some command line options (including from inside
* Eclipse). Look in the docs area at the Jacob usage document for command line
* options. Or try these:
*
* <pre>
* -Djava.library.path=d:/jacob/release/x86
* -Dcom.jacob.autogc=false
* -Dcom.jacob.debug=false
* -Xcheck:jni
* </pre>
*/
public class BaseTestCase extends TestCase {
protected void setUp() {
// verify we have run with the dll in the lib path
try {
JacobObject foo = new JacobObject();
if (foo == null) {
fail("Failed basic sanity test: Can't create JacobObject (-D<java.library.path=xxx>)");
}
} catch (UnsatisfiedLinkError ule) {
fail("Did you remember to run with the jacob.dll in the libpath ?");
}
}
/**
* this test exists just to test the setup.
*/
public void testSetup(){
JacobObject foo = new JacobObject();
assertNotNull(foo);
}
/**
*
* @return a simple VB script that generates the result "3"
*/
public String getSampleVPScriptForEval() {
return "1+(2*4)-3";
}
/**
* Converts the class name into a path and appends the resource name.
* Used to derive the path to a resouce in the file system
* where the resource is co-located with the referenced class.
*
* @param resourceName
* @param classInSamePackageAsResource
* @return a class loader compatible fully qualified file system path to a resource
*/
public String getJavaFilePathToPackageResource(String resourceName,
Class classInSamePackageAsResource) {
String classPackageName = classInSamePackageAsResource.getName();
int i = classPackageName.lastIndexOf('.');
if (i == -1) {
classPackageName = "";
} else {
classPackageName = classPackageName.substring(0,i);
}
// change all "." to ^ for later conversion to "/" so we can append resource names with "."
classPackageName = classPackageName.replace('.', '^');
System.out.println("classPackageName:" + classPackageName);
String fullPathToResource = (classPackageName.length() > 0 ? classPackageName
+ "^"
: "")
+ resourceName;
fullPathToResource = fullPathToResource.replace('^', '/');
System.out.println("fullPathToResource:" + fullPathToResource);
URL urlToLibrary =
classInSamePackageAsResource.getClassLoader().getResource(fullPathToResource);
assertNotNull(urlToLibrary);
String fullPathToResourceAsFile = urlToLibrary.getFile();
System.out.println("url to library: "+urlToLibrary);
System.out.println("fullPathToResourceAsFile: "+fullPathToResourceAsFile);
return fullPathToResourceAsFile;
}
/**
* Converts the class name into a path and appends the resource name.
* Used to derive the path to a resouce in the file system
* where the resource is co-located with the referenced class.
*
* @param resourceName
* @param classInSamePackageAsResource
* @return returns the path in the file system of the requested resource in windows c
* compatible format
*/
public String getWindowsFilePathToPackageResource(
String resourceName, Class classInSamePackageAsResource) {
String javaFilePath = getJavaFilePathToPackageResource(
resourceName, classInSamePackageAsResource);
javaFilePath = javaFilePath.replace('/', '\\');
return javaFilePath.substring(1);
}
/**
*
* @param resourceName
* @param classInSamePackageAsResource
* @return a resource located in the same package as the passed in class
*/
public Object getPackageResource(String resourceName,
Class classInSamePackageAsResource) {
String fullPathToResource = getJavaFilePathToPackageResource(resourceName,
classInSamePackageAsResource);
ClassLoader localClassLoader = classInSamePackageAsResource
.getClassLoader();
if (null == localClassLoader) {
return ClassLoader.getSystemResource(fullPathToResource);
} else {
return localClassLoader.getResource(fullPathToResource);
}
}
/**
* load a library from same place in the file system that the class was
* loaded from.
* <p>
* This is an attempt to let unit tests run without having to run
* regsvr32.
*
* @param libraryName
* @param classInSamePackageAsResource
*/
public void loadLibraryFromClassPackage(String libraryName,
Class classInSamePackageAsResource) {
String libraryNameWithSuffix = "";
String fullLibraryNameWithPath = "";
if (libraryName != null && libraryName.endsWith("dll")) {
libraryNameWithSuffix = libraryName;
} else if (libraryName != null) {
libraryNameWithSuffix = libraryName + ".dll";
} else {
fail("can't create full library name " + libraryName);
}
// generate the path the classloader would use to find this on the classpath
fullLibraryNameWithPath = getJavaFilePathToPackageResource(
libraryNameWithSuffix, classInSamePackageAsResource);
System.load(fullLibraryNameWithPath);
// requires that the dll be on the library path
//System.loadLibrary(fullLibraryNameWithPath);
}
}

View File

@@ -6,6 +6,7 @@ import com.jacob.com.Dispatch;
import com.jacob.com.DispatchEvents; import com.jacob.com.DispatchEvents;
import com.jacob.com.InvocationProxy; import com.jacob.com.InvocationProxy;
import com.jacob.com.Variant; import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/** /**
* This test was lifted from a forum posting and shows how you can't listen to * This test was lifted from a forum posting and shows how you can't listen to
@@ -15,13 +16,13 @@ import com.jacob.com.Variant;
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options. * Look in the docs area at the Jacob usage document for command line options.
*/ */
public class ExcelEventTest extends InvocationProxy { public class ExcelEventTest extends BaseTestCase {
/** /**
* load up excel, register for events and make stuff happen * load up excel, register for events and make stuff happen
* @param args * @param args
*/ */
public static void main(String args[]) { public void testExcelWithInvocationProxy() {
String pid = "Excel.Application"; String pid = "Excel.Application";
String typeLibLocation = "C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE"; String typeLibLocation = "C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE";
@@ -31,9 +32,9 @@ public class ExcelEventTest extends InvocationProxy {
// Add a listener (doesn't matter what it is). // Add a listener (doesn't matter what it is).
DispatchEvents de; DispatchEvents de;
if (typeLibLocation == null) { if (typeLibLocation == null) {
de = new DispatchEvents(axc, new ExcelEventTest()); de = new DispatchEvents(axc, new ExcelEvents());
} else { } else {
de = new DispatchEvents(axc, new ExcelEventTest(), pid, de = new DispatchEvents(axc, new ExcelEvents(), pid,
typeLibLocation); typeLibLocation);
} }
if (de == null) { if (de == null) {
@@ -67,16 +68,18 @@ public class ExcelEventTest extends InvocationProxy {
} catch (ComException cfe) { } catch (ComException cfe) {
cfe.printStackTrace(); cfe.printStackTrace();
System.out.println("Failed to attach to " + pid + ": " fail("Failed to attach to " + pid + ": "
+ cfe.getMessage()); + cfe.getMessage());
} }
} }
public class ExcelEvents extends InvocationProxy {
/** /**
* Constructor so we can create an instance that implements invoke() * Constructor so we can create an instance that implements invoke()
*/ */
public ExcelEventTest() { public ExcelEvents() {
} }
/** /**
@@ -89,3 +92,4 @@ public class ExcelEventTest extends InvocationProxy {
} }
} }
}

View File

@@ -1,7 +1,11 @@
package com.jacob.test.events; package com.jacob.test.events;
import com.jacob.com.*; import com.jacob.activeX.ActiveXComponent;
import com.jacob.activeX.*; import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.DispatchEvents;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/** /**
* This test runs fine against jdk 1.4 and 1.5 * This test runs fine against jdk 1.4 and 1.5
* *
@@ -15,10 +19,9 @@ import com.jacob.activeX.*;
* Look in the docs area at the Jacob usage document for command line options. * Look in the docs area at the Jacob usage document for command line options.
*/ */
class IETest public class IETest extends BaseTestCase {
{
public static void main(String[] args) public void testRunIE() {
{
// this line starts the pump but it runs fine without it // this line starts the pump but it runs fine without it
ComThread.startMainSTA(); ComThread.startMainSTA();
// remove this line and it dies // remove this line and it dies
@@ -39,6 +42,10 @@ class IETest
ComThread.quitMainSTA(); ComThread.quitMainSTA();
System.out.println("Main: did quit main sta in thread " System.out.println("Main: did quit main sta in thread "
+Thread.currentThread().getName()); +Thread.currentThread().getName());
if (aThread.threadFailedWithException != null){
fail("caught an unexpected exception "+aThread.threadFailedWithException);
}
} }
} }
@@ -46,6 +53,11 @@ class IETestThread extends Thread
{ {
public static boolean quitHandled = false; public static boolean quitHandled = false;
/**
* holds any caught exception so the main/test case can see them
*/
public Throwable threadFailedWithException = null;
public IETestThread(){ public IETestThread(){
super(); super();
} }
@@ -80,8 +92,10 @@ class IETestThread extends Thread
System.out.println("IETestThread: Did call navigate to yahoo"); System.out.println("IETestThread: Did call navigate to yahoo");
try { Thread.sleep(delay); } catch (Exception e) {} try { Thread.sleep(delay); } catch (Exception e) {}
} catch (Exception e) { } catch (Exception e) {
threadFailedWithException = e;
e.printStackTrace(); e.printStackTrace();
} catch (Throwable re){ } catch (Throwable re){
threadFailedWithException = re;
re.printStackTrace(); re.printStackTrace();
} finally { } finally {
System.out.println("IETestThread: About to send Quit"); System.out.println("IETestThread: About to send Quit");

View File

@@ -5,6 +5,7 @@ import com.jacob.activeX.ActiveXDispatchEvents;
import com.jacob.com.ComThread; import com.jacob.com.ComThread;
import com.jacob.com.Dispatch; import com.jacob.com.Dispatch;
import com.jacob.com.Variant; import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/** /**
* This test runs fine against jdk 1.4 and 1.5 * This test runs fine against jdk 1.4 and 1.5
* *
@@ -18,10 +19,10 @@ import com.jacob.com.Variant;
* Look in the docs area at the Jacob usage document for command line options. * Look in the docs area at the Jacob usage document for command line options.
*/ */
class IETestActiveXProxy public class IETestActiveXProxy extends BaseTestCase {
{
public static void main(String[] args)
{ public void testIEActiveProxyCallback() {
// this line starts the pump but it runs fine without it // this line starts the pump but it runs fine without it
ComThread.startMainSTA(); ComThread.startMainSTA();
// remove this line and it dies // remove this line and it dies
@@ -42,6 +43,9 @@ class IETestActiveXProxy
ComThread.quitMainSTA(); ComThread.quitMainSTA();
System.out.println("Main: did quit main sta in thread " System.out.println("Main: did quit main sta in thread "
+Thread.currentThread().getName()); +Thread.currentThread().getName());
if (aThread.threadFailedWithException != null){
fail("caught an unexpected exception "+aThread.threadFailedWithException);
}
} }
} }
@@ -49,6 +53,11 @@ class IETestActiveProxyThread extends Thread
{ {
public static boolean quitHandled = false; public static boolean quitHandled = false;
/**
* holds any caught exception so the main/test case can see them
*/
public Throwable threadFailedWithException = null;
public IETestActiveProxyThread(){ public IETestActiveProxyThread(){
super(); super();
} }
@@ -83,8 +92,10 @@ class IETestActiveProxyThread extends Thread
System.out.println("IETestActiveProxyThread: Did call navigate to yahoo"); System.out.println("IETestActiveProxyThread: Did call navigate to yahoo");
try { Thread.sleep(delay); } catch (Exception e) {} try { Thread.sleep(delay); } catch (Exception e) {}
} catch (Exception e) { } catch (Exception e) {
threadFailedWithException = e;
e.printStackTrace(); e.printStackTrace();
} catch (Throwable re){ } catch (Throwable re){
threadFailedWithException = re;
re.printStackTrace(); re.printStackTrace();
} finally { } finally {
System.out.println("IETestActiveProxyThread: About to send Quit"); System.out.println("IETestActiveProxyThread: About to send Quit");

View File

@@ -5,6 +5,7 @@ import com.jacob.com.ComException;
import com.jacob.com.DispatchEvents; import com.jacob.com.DispatchEvents;
import com.jacob.com.InvocationProxy; import com.jacob.com.InvocationProxy;
import com.jacob.com.Variant; import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/** /**
* This test was lifted from a forum posting and shows how you can't listen to * This test was lifted from a forum posting and shows how you can't listen to
@@ -17,13 +18,13 @@ import com.jacob.com.Variant;
* May need to run with some command line options (including from inside Eclipse). * May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options. * Look in the docs area at the Jacob usage document for command line options.
*/ */
public class WordEventTest extends InvocationProxy { public class WordEventTest extends BaseTestCase {
/** /**
* load up word, register for events and make stuff happen * load up word, register for events and make stuff happen
* @param args * @param args
*/ */
public static void main(String args[]) { public void testCaptureWordEvents() {
String pid = "Word.Application"; String pid = "Word.Application";
String typeLibLocation = null; String typeLibLocation = null;
@@ -39,8 +40,7 @@ public class WordEventTest extends InvocationProxy {
typeLibLocation); typeLibLocation);
} }
if (de == null) { if (de == null) {
System.out fail("No exception thrown but no dispatch returned for Word events");
.println("No exception thrown but no dispatch returned for Word events");
} else { } else {
// Yea! // Yea!
System.out.println("Successfully attached to " + pid); System.out.println("Successfully attached to " + pid);
@@ -52,14 +52,13 @@ public class WordEventTest extends InvocationProxy {
axc.setProperty("Visible",true); axc.setProperty("Visible",true);
ActiveXComponent documents = axc.getPropertyAsComponent("Documents"); ActiveXComponent documents = axc.getPropertyAsComponent("Documents");
if (documents == null){ if (documents == null){
System.out.println("unable to get documents"); fail("unable to get documents");
} }
axc.invoke("Quit", new Variant[] {}); axc.invoke("Quit", new Variant[] {});
} catch (ComException cfe) { } catch (ComException cfe) {
cfe.printStackTrace(); cfe.printStackTrace();
System.out.println("Failed to attach to " + pid + ": " fail("Failed to attach to " + pid + ": " + cfe.getMessage());
+ cfe.getMessage());
} }
System.out.println( System.out.println(
@@ -68,10 +67,11 @@ public class WordEventTest extends InvocationProxy {
"thinks we tested something"); "thinks we tested something");
} }
public class WordEvents extends InvocationProxy {
/** /**
* Constructor so we can create an instance that implements invoke() * Constructor so we can create an instance that implements invoke()
*/ */
public WordEventTest() { public WordEvents() {
} }
/** /**
@@ -83,3 +83,4 @@ public class WordEventTest extends InvocationProxy {
} }
} }
}

View File

@@ -9,8 +9,10 @@ package com.jacob.test.powerpoint;
* Look in the docs area at the Jacob usage document for command line options. * Look in the docs area at the Jacob usage document for command line options.
*/ */
import com.jacob.activeX.ActiveXComponent; import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.ComThread; import com.jacob.com.ComThread;
import com.jacob.com.Dispatch; import com.jacob.com.Dispatch;
import com.jacob.test.BaseTestCase;
/** /**
* *
@@ -18,67 +20,31 @@ import com.jacob.com.Dispatch;
* The submitter stated they had the problem on windows 2000 with office 2000 * The submitter stated they had the problem on windows 2000 with office 2000
* I have been unable to duplicate on windows XP with office 2003. * I have been unable to duplicate on windows XP with office 2003.
* I am comitting this to the tree just in case we need to come back to it. * I am comitting this to the tree just in case we need to come back to it.
* <P>
* This relies on BaseTestCase to provide the root path to the file under test
* <p>
* May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options.
*/ */
public class PowerpointTest extends Thread { public class PowerpointTest extends BaseTestCase {
private static final int NUM_THREADS = 5; private static final int NUM_THREADS = 5;
protected static final int NUM_ITERATIONS = 50; protected static final int NUM_ITERATIONS = 50;
private static String POWERPOINT_TEST_PATH =
"D:\\jacob\\samples\\com\\jacob\\test\\powerpoint";
//"c:\\PowerpointTest\test";
private int threadID;
private Dispatch comPowerpoint;
public PowerpointTest(int threadID, Dispatch comPowerpoint) {
super("TestThread "+threadID);
this.threadID = threadID;
this.comPowerpoint = comPowerpoint;
}
public void run() {
System.out.println("Thread \""+Thread.currentThread().getName()+"\" started");
System.out.flush();
ComThread.InitMTA();
try {
for (int i=0; i<NUM_ITERATIONS; i++) {
if (i % 10 == 0) {
System.out.println(Thread.currentThread().getName()+": Iteration "+i);
System.out.flush();
}
Dispatch comPresentations = Dispatch.get(comPowerpoint,"Presentations").toDispatch();
Dispatch comPresentation = Dispatch.call(comPresentations,
"Open",
POWERPOINT_TEST_PATH+"\\test"+threadID+".ppt",
new Integer(0),
new Integer(0),
new Integer(0)).toDispatch();
Dispatch.call(comPresentation, "Close");
}
} catch (Exception e) {
System.err.println("Error in Thread \""+Thread.currentThread().getName()+"\":");
e.printStackTrace();
} finally {
ComThread.Release();
System.out.println("Thread \""+Thread.currentThread().getName()+"\" finished");
System.out.flush();
}
}
/** /**
* main program that lets us run this as a test * main program that lets us run this as a test
* @param args * @param args
*/ */
public static void main(String[] args) { public void testPowerpoint() {
ComThread.InitMTA(); ComThread.InitMTA();
ActiveXComponent component = new ActiveXComponent("Powerpoint.Application"); ActiveXComponent component = new ActiveXComponent("Powerpoint.Application");
Dispatch comPowerpoint = component.getObject(); Dispatch comPowerpoint = component.getObject();
try { try {
PowerpointTest[] threads = new PowerpointTest[NUM_THREADS]; PowerpointTestThread[] threads = new PowerpointTestThread[NUM_THREADS];
for (int i=0; i<NUM_THREADS; i++) { for (int i=0; i<NUM_THREADS; i++) {
threads[i] = new PowerpointTest(i+1, comPowerpoint); threads[i] = new PowerpointTestThread(i+1, comPowerpoint);
threads[i].start(); threads[i].start();
} }
@@ -101,8 +67,67 @@ public class PowerpointTest extends Thread {
} }
Dispatch.call(comPowerpoint,"Quit"); Dispatch.call(comPowerpoint,"Quit");
for (int i = 0 ; i < NUM_THREADS; i++){
if (threads[i].threadFailedWithException != null){
fail ("caught unexpected exception in thread "+
threads[i].threadFailedWithException);
}
}
} finally { } finally {
ComThread.Release(); ComThread.Release();
} }
}
public class PowerpointTestThread extends Thread {
/**
* holds any caught exception so the main/test case can see them
*/
public Throwable threadFailedWithException = null;
private int threadID;
private Dispatch comPowerpoint;
public PowerpointTestThread(int threadID, Dispatch comPowerpoint) {
super("TestThread "+threadID);
this.threadID = threadID;
this.comPowerpoint = comPowerpoint;
}
public void run() {
System.out.println("Thread \""+Thread.currentThread().getName()+"\" started");
System.out.flush();
ComThread.InitMTA();
try {
for (int i=0; i<NUM_ITERATIONS; i++) {
if (i % 10 == 0) {
System.out.println(Thread.currentThread().getName()+": Iteration "+i);
System.out.flush();
}
Dispatch comPresentations = Dispatch.get(comPowerpoint,"Presentations").toDispatch();
Dispatch comPresentation = Dispatch.call(comPresentations,
"Open",
getWindowsFilePathToPackageResource("test"+threadID+".ppt",this.getClass()),
new Integer(0),
new Integer(0),
new Integer(0)).toDispatch();
Dispatch.call(comPresentation, "Close");
}
} catch (ComFailException cfe){
threadFailedWithException = cfe;
System.err.println(Thread.currentThread().getName()+"\" while working on: "+
getWindowsFilePathToPackageResource("test"+threadID+".ppt",this.getClass()));
cfe.printStackTrace();
} catch (Exception e) {
threadFailedWithException = e;
System.err.println("Error in Thread \""+Thread.currentThread().getName()+"\":");
e.printStackTrace();
} finally {
ComThread.Release();
System.out.println("Thread \""+Thread.currentThread().getName()+"\" finished");
System.out.flush();
}
}
} }
} }

View File

@@ -1,16 +1,21 @@
package com.jacob.test.safearray; package com.jacob.test.safearray;
import com.jacob.com.*; import com.jacob.com.SafeArray;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/** /**
* SafeArrayTest Program * SafeArrayTest Program
* *
* This is more of an exerciser. It doesn't verify that it gets back * This is more of an exerciser. It doesn't verify that it gets back
* what it expects like a junit test would * what it expects like a junit test would
* <p>
* May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options.
* *
*/ */
class sa_test { public class SafeArrayBasicTest extends BaseTestCase {
public static void main(String[] args) { public void testBasicSafeArray(){
//System.runFinalizersOnExit(true); //System.runFinalizersOnExit(true);
SafeArray sa = new SafeArray(Variant.VariantVariant, 3); SafeArray sa = new SafeArray(Variant.VariantVariant, 3);
@@ -60,11 +65,9 @@ class sa_test {
new Variant(1), new Variant(2.3), new Variant("hi") }); new Variant(1), new Variant(2.3), new Variant("hi") });
System.out.println("sa variant=" + sa); System.out.println("sa variant=" + sa);
sa_ND_test();
} }
public static void sa_ND_test() { public void testSafeArrayNumDimensions() {
int[] lowerBounds = new int[] { 0, 0, 0 }; int[] lowerBounds = new int[] { 0, 0, 0 };
int[] dimensionSizes = new int[] { 3, 3, 3 }; int[] dimensionSizes = new int[] { 3, 3, 3 };

View File

@@ -1,12 +1,21 @@
package com.jacob.test.safearray; package com.jacob.test.safearray;
import com.jacob.com.*; import com.jacob.com.ComFailException;
import com.jacob.com.SafeArray;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
class SafeArrayContents /**
{ * A safe array contents test (old test)
*
* <p>
* May need to run with some command line options (including from inside
* Eclipse). Look in the docs area at the Jacob usage document for command line
* options.
*/
public class SafeArrayContents extends BaseTestCase {
public static void printArray(boolean a[]) public static void printArray(boolean a[]) {
{
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
@@ -14,8 +23,7 @@ class SafeArrayContents
System.out.println("]"); System.out.println("]");
} }
public static void printArray(int a[]) public static void printArray(int a[]) {
{
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
@@ -23,8 +31,7 @@ class SafeArrayContents
System.out.println("]"); System.out.println("]");
} }
public static void printArray(short a[]) public static void printArray(short a[]) {
{
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
@@ -32,8 +39,7 @@ class SafeArrayContents
System.out.println("]"); System.out.println("]");
} }
public static void printArray(byte a[]) public static void printArray(byte a[]) {
{
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
@@ -41,8 +47,7 @@ class SafeArrayContents
System.out.println("]"); System.out.println("]");
} }
public static void printArray(double a[]) public static void printArray(double a[]) {
{
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
@@ -50,8 +55,7 @@ class SafeArrayContents
System.out.println("]"); System.out.println("]");
} }
public static void printArray(float a[]) public static void printArray(float a[]) {
{
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
@@ -59,8 +63,7 @@ class SafeArrayContents
System.out.println("]"); System.out.println("]");
} }
public static void printArray(String a[]) public static void printArray(String a[]) {
{
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
@@ -68,8 +71,7 @@ class SafeArrayContents
System.out.println("]"); System.out.println("]");
} }
public static void printArray(Variant a[]) public static void printArray(Variant a[]) {
{
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
@@ -77,8 +79,7 @@ class SafeArrayContents
System.out.println("]"); System.out.println("]");
} }
public static void printArray(char a[]) public static void printArray(char a[]) {
{
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
@@ -86,8 +87,7 @@ class SafeArrayContents
System.out.println("]"); System.out.println("]");
} }
public static void main(String[] args) public void testSafeArrayContents() {
{
// int // int
System.out.println("Int"); System.out.println("Int");
SafeArray ia = new SafeArray(Variant.VariantInt, 4); SafeArray ia = new SafeArray(Variant.VariantInt, 4);
@@ -130,7 +130,8 @@ class SafeArrayContents
System.out.println("Float"); System.out.println("Float");
SafeArray fa = new SafeArray(Variant.VariantFloat, 4); SafeArray fa = new SafeArray(Variant.VariantFloat, 4);
System.out.println("elem size:" + fa.getElemSize()); System.out.println("elem size:" + fa.getElemSize());
float fack[] = new float[] {123.456F,456.123F,1234567.89F,12.3456789F}; float fack[] = new float[] { 123.456F, 456.123F, 1234567.89F,
12.3456789F };
printArray(fack); printArray(fack);
fa.fromFloatArray(fack); fa.fromFloatArray(fack);
fack = fa.toFloatArray(); fack = fa.toFloatArray();
@@ -225,13 +226,8 @@ class SafeArrayContents
System.out.println("Variant"); System.out.println("Variant");
SafeArray va = new SafeArray(Variant.VariantVariant, 4); SafeArray va = new SafeArray(Variant.VariantVariant, 4);
System.out.println("elem size:" + va.getElemSize()); System.out.println("elem size:" + va.getElemSize());
Variant vack[] = new Variant[] Variant vack[] = new Variant[] { new Variant(1), new Variant(2.3),
{ new Variant(true), new Variant("four"), };
new Variant(1),
new Variant(2.3),
new Variant(true),
new Variant("four"),
};
printArray(vack); printArray(vack);
va.fromVariantArray(vack); va.fromVariantArray(vack);
vack = va.toVariantArray(); vack = va.toVariantArray();
@@ -266,11 +262,12 @@ class SafeArrayContents
printArray(bback); printArray(bback);
try { try {
System.out.println("Should see a com exception right after this line...");
// this should throw ComException // this should throw ComException
bba2.fromCharArray(new char[] { 'a' }); bba2.fromCharArray(new char[] { 'a' });
} catch (Exception e) { fail("Failed to catch expected exception");
e.printStackTrace(); } catch (ComFailException cfe) {
// do nothing
//cfe.printStackTrace();
} }
} }
} }

View File

@@ -0,0 +1,42 @@
package com.jacob.test.safearray;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComException;
import com.jacob.com.Dispatch;
import com.jacob.com.SafeArray;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
public class SafeArrayDispatchTest extends BaseTestCase {
public void testDispatchWithSafeArray() {
try {
String scriptCommand = "1+(2*4)-3";
String lang = "VBScript";
ActiveXComponent sControl = new ActiveXComponent("ScriptControl");
Dispatch.put(sControl, "Language", lang);
Variant result = Dispatch.call(sControl, "Eval", scriptCommand);
assertTrue(result.toString().equals("6"));
// wrap the script control in a variant
Variant v = new Variant(sControl);
// create a safe array of type dispatch
SafeArray sa = new SafeArray(Variant.VariantDispatch, 1);
// put the variant in the array
sa.setVariant(0, v);
// take it back out
Variant v2 = sa.getVariant(0);
Dispatch d = v2.toDispatch();
// make sure you can call eval on it
result = Dispatch.call(d, "Eval", scriptCommand);
assertTrue(result.toString().equals("6"));
} catch (ComException e) {
e.printStackTrace();
fail("script failure "+e);
}
}
}

View File

@@ -3,6 +3,7 @@ package com.jacob.test.safearray;
import com.jacob.com.ComThread; import com.jacob.com.ComThread;
import com.jacob.com.SafeArray; import com.jacob.com.SafeArray;
import com.jacob.com.Variant; import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/** /**
* <p> * <p>
@@ -73,13 +74,15 @@ import com.jacob.com.Variant;
+-----------+ | VT_ARRAY| +---------+ +-----------+ | VT_ARRAY| +---------+
| parray---->SAFEARRAY| | parray---->SAFEARRAY|
+------------+ +---------+ +------------+ +---------+
*
* <p>
* May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options.
*/ */
public class SafeArrayReleaseTest public class SafeArrayReleaseTest extends BaseTestCase {
{
final static int MAX = 300; final static int MAX = 300;
public static void main(String[] args) public void testSaveArrayRelease() {
{
int count; int count;
System.out.println("Starting test for max = "+MAX); System.out.println("Starting test for max = "+MAX);
for(count = 1; count<MAX; count++) for(count = 1; count<MAX; count++)
@@ -105,9 +108,7 @@ public class SafeArrayReleaseTest
} }
catch (Exception e) catch (Exception e)
{ {
System.out.println("\nTest fails with i = " + i + " (max = "+MAX+")"); fail("Test fails with i = " + i + " (max = "+MAX+")");
e.printStackTrace();
break;
} }
} }
System.gc(); System.gc();

View File

@@ -1,12 +1,19 @@
package com.jacob.test.safearray; package com.jacob.test.safearray;
import com.jacob.com.*; import com.jacob.com.*;
import com.jacob.test.BaseTestCase;
import com.jacob.activeX.*; import com.jacob.activeX.*;
public class SafeArrayViaExcel /**
{ * This does simple tests with SafeArray using Excel as a source
public static void main(java.lang.String[] args) * <p>
{ * May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options.
* <p>
* This relies on BaseTestCase to provide the root path to the file under test
*/
public class SafeArrayViaExcel extends BaseTestCase {
public void testSafeArrayViaExcel() {
// deprecated // deprecated
// System.runFinalizersOnExit(true); // System.runFinalizersOnExit(true);
@@ -16,11 +23,15 @@ public class SafeArrayViaExcel
SafeArray sAProdText; SafeArray sAProdText;
Dispatch workbooks = xl.getProperty("Workbooks").toDispatch(); Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
System.out.println("have workbooks"); System.out.println("have workbooks");
Dispatch workbook = Dispatch.call(workbooks, "Open", "d:\\jacob\\samples\\test\\ExcelSafeArray" + Dispatch workbook = Dispatch.call(
".xls").toDispatch(); workbooks,
System.out.println("Opened File - jacobtest.xls\n"); "Open",
getWindowsFilePathToPackageResource("SafeArrayViaExcel.xls",this.getClass()))
.toDispatch();
System.out.println("Opened File - SafeArrayViaExcel.xls\n");
Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch(); Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
cell = Dispatch.invoke(sheet,"Range",Dispatch.Get,new Object[] {"A1:D1000"},new int[1]).toDispatch(); cell = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { "A1:D1000" }, new int[1]).toDispatch();
System.out.println("have cell:" + cell); System.out.println("have cell:" + cell);
sAProdText = Dispatch.get(cell, "Value").toSafeArray(); sAProdText = Dispatch.get(cell, "Value").toSafeArray();
System.out.println("sa: dim=" + sAProdText.getNumDim()); System.out.println("sa: dim=" + sAProdText.getNumDim());
@@ -31,20 +42,17 @@ public class SafeArrayViaExcel
int i; int i;
int lineNumber = 1; int lineNumber = 1;
int n = 0; int n = 0;
for(lineNumber=1; lineNumber < 1000; lineNumber++) for (lineNumber = 1; lineNumber < 1000; lineNumber++) {
{
for (i = 1; i < 4; i++) { for (i = 1; i < 4; i++) {
System.out.println((n++) + " " + lineNumber+" "+i+" " +sAProdText.getString(lineNumber,i)); System.out.println((n++) + " " + lineNumber + " " + i + " "
+ sAProdText.getString(lineNumber, i));
/* /*
if (sAProdText.getString(lineNumber,i).compareTo("aaaa") != 0 ) { * if (sAProdText.getString(lineNumber,i).compareTo("aaaa") !=
System.out.println("Invalid String in line " + lineNumber + " Cell " + i + " Value = " + sAProdText.getString(lineNumber,i)); * 0 ) { System.out.println("Invalid String in line " +
stringFound = false; * lineNumber + " Cell " + i + " Value = " +
} * sAProdText.getString(lineNumber,i)); stringFound = false; } }
} * if (stringFound) { System.out.println("Valid Strings in
if (stringFound) { * line " + lineNumber); lineNumber++; }
System.out.println("Valid Strings in line " + lineNumber);
lineNumber++;
}
*/ */
} }
} }
@@ -53,6 +61,7 @@ public class SafeArrayViaExcel
System.out.println("Closed File\n"); System.out.println("Closed File\n");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
fail("Caught Exception "+e);
} finally { } finally {
xl.invoke("Quit", new Variant[] {}); xl.invoke("Quit", new Variant[] {});
} }

View File

@@ -1,42 +0,0 @@
package com.jacob.test.safearray;
import com.jacob.com.*;
import com.jacob.activeX.*;
class sa_dispatch
{
public static void main(String args[])
{
// deprecated
//System.runFinalizersOnExit(true);
try {
String lang = "VBScript";
ActiveXComponent sC = new ActiveXComponent("ScriptControl");
Dispatch sControl = (Dispatch)sC.getObject();
Dispatch.put(sControl, "Language", lang);
Variant result = Dispatch.call(sControl, "Eval", args[0]);
System.out.println("eval("+args[0]+") = "+ result);
// wrap the script control in a variant
Variant v = new Variant(sControl);
// create a safe array of type dispatch
SafeArray sa = new SafeArray(Variant.VariantDispatch, 1);
// put the variant in the array
sa.setVariant(0, v);
// take it back out
Variant v2 = sa.getVariant(0);
Dispatch d = v2.toDispatch();
// make sure you can call eval on it
result = Dispatch.call(d, "Eval", args[0]);
System.out.println("eval("+args[0]+") = "+ result);
} catch (ComException e) {
e.printStackTrace();
}
}
}

View File

@@ -1,2 +0,0 @@
java ScriptTest "1+2"
java ScriptTest "()1+2"

View File

@@ -1,21 +1,36 @@
package com.jacob.test.vbscript; package com.jacob.test.vbscript;
import com.jacob.com.*; import com.jacob.com.*;
import com.jacob.test.BaseTestCase;
import com.jacob.activeX.*; import com.jacob.activeX.*;
/** /**
* In this case the component is created and used in the same thread * In this case the component is created and used in the same thread and it's an
* and it's an Apartment Threaded component, so we call InitSTA. * Apartment Threaded component, so we call InitSTA.
* <p>
* May need to run with some command line options (including from inside
* Eclipse). Look in the docs area at the Jacob usage document for command line
* options.
*/ */
class ScriptTest public class ScriptTest extends BaseTestCase {
{
public static void main(String args[]) throws Exception public void testStupidSpeedTest() {
{ String lang = "VBScript";
ActiveXComponent sC = new ActiveXComponent("ScriptControl");
Dispatch sControl = sC.getObject();
Dispatch.put(sControl, "Language", lang);
for (int i = 0; i < 10000; i++) {
Dispatch.call(sControl, "Eval", "1+1");
}
}
public void testCreatingDispatchEvents() {
ComThread.InitSTA(true); ComThread.InitSTA(true);
DispatchEvents de = null; DispatchEvents de = null;
Dispatch sControl = null; Dispatch sControl = null;
try { try {
String scriptCommand = getSampleVPScriptForEval();
String lang = "VBScript"; String lang = "VBScript";
ActiveXComponent sC = new ActiveXComponent("ScriptControl"); ActiveXComponent sC = new ActiveXComponent("ScriptControl");
sControl = (Dispatch) sC.getObject(); sControl = (Dispatch) sC.getObject();
@@ -23,22 +38,21 @@ class ScriptTest
ScriptTestErrEvents te = new ScriptTestErrEvents(); ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sControl, te); de = new DispatchEvents(sControl, te);
if (de == null) { if (de == null) {
System.out.println("Received null when trying to create new DispatchEvents"); System.out
.println("Received null when trying to create new DispatchEvents");
} }
Variant result = Dispatch.call(sControl, "Eval", args[0]); Variant result = Dispatch.call(sControl, "Eval", scriptCommand);
// call it twice to see the objects reused // call it twice to see the objects reused
result = Dispatch.call(sControl, "Eval", args[0]); result = Dispatch.call(sControl, "Eval", scriptCommand);
// call it 3 times to see the objects reused // call it 3 times to see the objects reused
result = Dispatch.call(sControl, "Eval", args[0]); result = Dispatch.call(sControl, "Eval", scriptCommand);
System.out.println("eval("+args[0]+") = "+ result); System.out.println("eval(" + scriptCommand + ") = " + result);
} catch (ComException e) { } catch (ComException e) {
e.printStackTrace(); e.printStackTrace();
} fail("Caught Exception " + e);
finally } finally {
{
Integer I = null; Integer I = null;
for(int i=1;i<1000000;i++) for (int i = 1; i < 1000000; i++) {
{
I = new Integer(i); I = new Integer(i);
} }
System.out.println(I); System.out.println(I);
@@ -47,4 +61,3 @@ class ScriptTest
} }
} }
} }

View File

@@ -1,46 +1,80 @@
package com.jacob.test.vbscript; package com.jacob.test.vbscript;
import com.jacob.com.*; import com.jacob.com.*;
import com.jacob.test.BaseTestCase;
import com.jacob.activeX.*; import com.jacob.activeX.*;
/** /**
* This example demonstrates how to make calls between * This example demonstrates how to make calls between two different STA's.
* two different STA's. * First, to create an STA, you need to extend the STA class and override its
* First, to create an STA, you need to extend the STA class * OnInit() method. This method will be called in the STA's thread so you can
* and override its OnInit() method. This method will be called * use it to create your COM components that will run in that STA. If you then
* in the STA's thread so you can use it to create your COM * try to call methods on those components from other threads (STA or MTA) -
* components that will run in that STA. * this will fail. You cannot create a component in an STA and call its methods
* If you then try to call methods on those components from other * from another thread. You can use the DispatchProxy to get a proxy to any
* threads (STA or MTA) - this will fail. * Dispatch that lives in another STA. This object has to be created in the STA
* You cannot create a component in an STA and call its methods * that houses the Dispatch (in this case it's created in the OnInit method).
* from another thread. * Then, another thread can call the toDispatch() method of DispatchProxy to get
* You can use the DispatchProxy to get a proxy to any Dispatch * a local proxy. At most ONE (!) thread can call toDispatch(), and the call can
* that lives in another STA. This object has to be created in the * be made only once. This is because a IStream object is used to pass the
* STA that houses the Dispatch (in this case it's created in the * proxy, and it is only written once and closed when you read it. If you need
* OnInit method). Then, another thread can call the toDispatch() * multiple threads to access a Dispatch pointer, then create that many
* method of DispatchProxy to get a local proxy. At most ONE (!) * DispatchProxy objects.
* thread can call toDispatch(), and the call can be made only once. * <p>
* This is because a IStream object is used to pass the proxy, and * May need to run with some command line options (including from inside Eclipse).
* it is only written once and closed when you read it. * Look in the docs area at the Jacob usage document for command line options.
* If you need multiple threads to access a Dispatch pointer, then
* create that many DispatchProxy objects.
*/ */
class ScriptTest2 extends STA
{
public static ActiveXComponent sC;
public static DispatchEvents de = null;
public static Dispatch sControl = null;
public static DispatchProxy sCon = null;
public boolean OnInit() public class ScriptTest2 extends BaseTestCase {
{ public void testScript2() {
try try {
{ ComThread.InitSTA();
ScriptTestSTA script = new ScriptTestSTA();
try {
Thread.sleep(1000);
} catch (InterruptedException ie){
// should we get this?
}
String scriptCommand = getSampleVPScriptForEval();
// get a thread-local Dispatch from sCon
Dispatch sc = script.sCon.toDispatch();
// call a method on the thread-local Dispatch obtained
// from the DispatchProxy. If you try to make the same
// method call on the sControl object - you will get a
// ComException.
Variant result = Dispatch.call(sc, "Eval", scriptCommand);
System.out.println("eval(" + scriptCommand + ") = " + result);
script.quit();
System.out.println("called quit");
} catch (ComException e) {
e.printStackTrace();
fail("caught exception"+e);
} finally {
Integer I = null;
for (int i = 1; i < 1000000; i++) {
I = new Integer(i);
}
System.out.println(I);
ComThread.Release();
}
}
public class ScriptTestSTA extends STA {
public DispatchEvents de = null;
public Dispatch sControl = null;
public DispatchProxy sCon = null;
public boolean OnInit() {
try {
System.out.println("OnInit"); System.out.println("OnInit");
System.out.println(Thread.currentThread()); System.out.println(Thread.currentThread());
String lang = "VBScript"; String lang = "VBScript";
sC = new ActiveXComponent("ScriptControl"); sControl = new ActiveXComponent("ScriptControl");
sControl = (Dispatch)sC.getObject();
// sCon can be called from another thread // sCon can be called from another thread
sCon = new DispatchProxy(sControl); sCon = new DispatchProxy(sControl);
@@ -49,50 +83,16 @@ class ScriptTest2 extends STA
ScriptTestErrEvents te = new ScriptTestErrEvents(); ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sControl, te); de = new DispatchEvents(sControl, te);
return true; return true;
} } catch (Exception e) {
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
} }
public void OnQuit() public void OnQuit() {
{
System.out.println("OnQuit"); System.out.println("OnQuit");
} }
public static void main(String args[]) throws Exception
{
try {
ComThread.InitSTA();
ScriptTest2 script = new ScriptTest2();
Thread.sleep(1000);
// get a thread-local Dispatch from sCon
Dispatch sc = sCon.toDispatch();
// call a method on the thread-local Dispatch obtained
// from the DispatchProxy. If you try to make the same
// method call on the sControl object - you will get a
// ComException.
Variant result = Dispatch.call(sc, "Eval", args[0]);
System.out.println("eval("+args[0]+") = "+ result);
script.quit();
System.out.println("called quit");
} catch (ComException e) {
e.printStackTrace();
}
finally
{
Integer I = null;
for(int i=1;i<1000000;i++)
{
I = new Integer(i);
}
System.out.println(I);
ComThread.Release();
}
}
} }
}

View File

@@ -1,40 +1,80 @@
package com.jacob.test.vbscript; package com.jacob.test.vbscript;
import com.jacob.com.*; import com.jacob.activeX.ActiveXComponent;
import com.jacob.activeX.*; import com.jacob.com.ComException;
import com.jacob.com.ComThread;
import com.jacob.com.DispatchEvents;
import com.jacob.com.DispatchProxy;
import com.jacob.com.STA;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/** /**
* This example demonstrates how to make calls between * This example demonstrates how to make calls between two different STA's.
* two different STA's. * First, to create an STA, you need to extend the STA class and override its
* First, to create an STA, you need to extend the STA class * OnInit() method. This method will be called in the STA's thread so you can
* and override its OnInit() method. This method will be called * use it to create your COM components that will run in that STA. If you then
* in the STA's thread so you can use it to create your COM * try to call methods on those components from other threads (STA or MTA) -
* components that will run in that STA. * this will fail. You cannot create a component in an STA and call its methods
* If you then try to call methods on those components from other * from another thread. You can use the DispatchProxy to get a proxy to any
* threads (STA or MTA) - this will fail. * Dispatch that lives in another STA. This object has to be created in the STA
* You cannot create a component in an STA and call its methods * that houses the Dispatch (in this case it's created in the OnInit method).
* from another thread. * Then, another thread can call the toDispatch() method of DispatchProxy to get
* You can use the DispatchProxy to get a proxy to any Dispatch * a local proxy. At most ONE (!) thread can call toDispatch(), and the call can
* that lives in another STA. This object has to be created in the * be made only once. This is because a IStream object is used to pass the
* STA that houses the Dispatch (in this case it's created in the * proxy, and it is only written once and closed when you read it. If you need
* OnInit method). Then, another thread can call the toDispatch() * multiple threads to access a Dispatch pointer, then create that many
* method of DispatchProxy to get a local proxy. At most ONE (!) * DispatchProxy objects.
* thread can call toDispatch(), and the call can be made only once. * <p>
* This is because a IStream object is used to pass the proxy, and * May need to run with some command line options (including from inside Eclipse).
* it is only written once and closed when you read it. * Look in the docs area at the Jacob usage document for command line options.
* If you need multiple threads to access a Dispatch pointer, then
* create that many DispatchProxy objects.
*/ */
class ScriptTest2ActiveX extends STA public class ScriptTest2ActiveX extends BaseTestCase {
{
public static ActiveXComponent sC; public static ActiveXComponent sC;
public static DispatchEvents de = null; public static DispatchEvents de = null;
public static DispatchProxy sCon = null; public static DispatchProxy sCon = null;
public boolean OnInit() public void testActiveXSTA() {
{ try {
try ComThread.InitSTA();
{ ScriptTest2ActiveXSTA script = new ScriptTest2ActiveXSTA();
try {
Thread.sleep(1000);
} catch (InterruptedException ie){
// should we get this?
}
// get a thread-local Dispatch from sCon
ActiveXComponent sc = new ActiveXComponent(sCon.toDispatch());
// call a method on the thread-local Dispatch obtained
// from the DispatchProxy. If you try to make the same
// method call on the sControl object - you will get a
// ComException.
String scriptCommand = getSampleVPScriptForEval();
Variant result = sc.invoke("Eval", scriptCommand);
System.out.println("eval(" + scriptCommand + ") = " + result);
script.quit();
System.out.println("called quit");
} catch (ComException e) {
e.printStackTrace();
fail("blew up with Com Exception "+e);
} finally {
Integer I = null;
for (int i = 1; i < 1000000; i++) {
I = new Integer(i);
}
System.out.println(I);
ComThread.Release();
}
}
public class ScriptTest2ActiveXSTA extends STA {
public boolean OnInit() {
try {
System.out.println("OnInit"); System.out.println("OnInit");
System.out.println(Thread.currentThread()); System.out.println(Thread.currentThread());
String lang = "VBScript"; String lang = "VBScript";
@@ -47,50 +87,16 @@ class ScriptTest2ActiveX extends STA
ScriptTestErrEvents te = new ScriptTestErrEvents(); ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sC, te); de = new DispatchEvents(sC, te);
return true; return true;
} } catch (Exception e) {
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
} }
public void OnQuit() public void OnQuit() {
{
System.out.println("OnQuit"); System.out.println("OnQuit");
} }
public static void main(String args[]) throws Exception
{
try {
ComThread.InitSTA();
ScriptTest2ActiveX script = new ScriptTest2ActiveX();
Thread.sleep(1000);
// get a thread-local Dispatch from sCon
ActiveXComponent sc = new ActiveXComponent(sCon.toDispatch());
// call a method on the thread-local Dispatch obtained
// from the DispatchProxy. If you try to make the same
// method call on the sControl object - you will get a
// ComException.
Variant result = sc.invoke("Eval", args[0]);
System.out.println("eval("+args[0]+") = "+ result);
script.quit();
System.out.println("called quit");
} catch (ComException e) {
e.printStackTrace();
}
finally
{
Integer I = null;
for(int i=1;i<1000000;i++)
{
I = new Integer(i);
}
System.out.println(I);
ComThread.Release();
}
}
} }
}

View File

@@ -1,26 +1,55 @@
package com.jacob.test.vbscript; package com.jacob.test.vbscript;
import com.jacob.com.*; import com.jacob.com.*;
import com.jacob.test.BaseTestCase;
import com.jacob.activeX.*; import com.jacob.activeX.*;
/** /**
* Here we create the ScriptControl component in a separate MTA thread * Here we create the ScriptControl component in a separate MTA thread and then
* and then call the Eval method from the main thread. The main thread * call the Eval method from the main thread. The main thread must also be an
* must also be an MTA thread. If you try to create it as an STA * MTA thread. If you try to create it as an STA then you will not be able to
* then you will not be able to make calls into a component running * make calls into a component running in another thread.
* in another thread. * <p>
* May need to run with some command line options (including from inside Eclipse).
* Look in the docs area at the Jacob usage document for command line options.
*/ */
class ScriptTest3 extends Thread public class ScriptTest3 extends BaseTestCase {
{
public static ActiveXComponent sC; public static ActiveXComponent sC;
public static DispatchEvents de = null; public static DispatchEvents de = null;
public static Dispatch sControl = null; public static Dispatch sControl = null;
public static boolean quit = false; public static boolean quit = false;
public void run() public void testScript() {
{ try {
try ComThread.InitMTA();
{ ScriptTest3Inner script = new ScriptTest3Inner();
script.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ie){
// should we get this?
}
Variant result = Dispatch.call(sControl, "Eval", getSampleVPScriptForEval());
System.out.println("eval(" + getSampleVPScriptForEval() + ") = " + result);
System.out.println("setting quit");
ScriptTest3.quit = true;
} catch (ComException e) {
e.printStackTrace();
fail("Caught excpetion running script with MTA");
} finally {
System.out.println("main done");
ComThread.Release();
}
}
class ScriptTest3Inner extends Thread {
public void run() {
try {
ComThread.InitMTA(); ComThread.InitMTA();
System.out.println("OnInit"); System.out.println("OnInit");
String lang = "VBScript"; String lang = "VBScript";
@@ -30,39 +59,15 @@ class ScriptTest3 extends Thread
ScriptTestErrEvents te = new ScriptTestErrEvents(); ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sControl, te); de = new DispatchEvents(sControl, te);
System.out.println("sControl=" + sControl); System.out.println("sControl=" + sControl);
while (!quit) sleep(100); while (!quit)
sleep(100);
ComThread.Release(); ComThread.Release();
} } catch (Exception e) {
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} } finally {
finally
{
System.out.println("worker thread exits"); System.out.println("worker thread exits");
} }
} }
public static void main(String args[]) throws Exception
{
try {
ComThread.InitMTA();
ScriptTest3 script = new ScriptTest3();
script.start();
Thread.sleep(1000);
Variant result = Dispatch.call(sControl, "Eval", args[0]);
System.out.println("eval("+args[0]+") = "+ result);
System.out.println("setting quit");
ScriptTest3.quit = true;
} catch (ComException e) {
e.printStackTrace();
}
finally
{
System.out.println("main done");
ComThread.Release();
} }
} }
}

View File

@@ -1,25 +1,55 @@
package com.jacob.test.vbscript; package com.jacob.test.vbscript;
import com.jacob.com.*; import com.jacob.com.*;
import com.jacob.test.BaseTestCase;
import com.jacob.activeX.*; import com.jacob.activeX.*;
/** /**
* Here we create the ScriptControl component in a separate MTA thread * Here we create the ScriptControl component in a separate MTA thread and then
* and then call the Eval method from the main thread. The main thread * call the Eval method from the main thread. The main thread must also be an
* must also be an MTA thread. If you try to create it as an STA * MTA thread. If you try to create it as an STA then you will not be able to
* then you will not be able to make calls into a component running * make calls into a component running in another thread.
* in another thread. * <p>
* May need to run with some command line options (including from inside
* Eclipse). Look in the docs area at the Jacob usage document for command line
* options.
*/ */
class ScriptTest3ActiveX extends Thread public class ScriptTest3ActiveX extends BaseTestCase {
{
public static ActiveXComponent sC; public static ActiveXComponent sC;
public static DispatchEvents de = null; public static DispatchEvents de = null;
public static boolean quit = false; public static boolean quit = false;
public void run() public void testYetAnotherScriptTest() {
{ try {
try ComThread.InitMTA();
{ ScriptTest3ActiveXInner script = new ScriptTest3ActiveXInner();
script.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
// should we get this?
}
Variant result = sC.invoke("Eval", getSampleVPScriptForEval());
System.out
.println("eval(" + getSampleVPScriptForEval()
+ ") = " + result);
System.out.println("setting quit");
ScriptTest3ActiveX.quit = true;
} catch (ComException e) {
e.printStackTrace();
fail("Caught ComException " + e);
} finally {
System.out.println("main done");
ComThread.Release();
}
}
public class ScriptTest3ActiveXInner extends Thread {
public void run() {
try {
ComThread.InitMTA(); ComThread.InitMTA();
System.out.println("OnInit"); System.out.println("OnInit");
String lang = "VBScript"; String lang = "VBScript";
@@ -28,39 +58,15 @@ class ScriptTest3ActiveX extends Thread
ScriptTestErrEvents te = new ScriptTestErrEvents(); ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sC, te); de = new DispatchEvents(sC, te);
System.out.println("sControl=" + sC); System.out.println("sControl=" + sC);
while (!quit) sleep(100); while (!quit)
sleep(100);
ComThread.Release(); ComThread.Release();
} } catch (Exception e) {
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} } finally {
finally
{
System.out.println("worker thread exits"); System.out.println("worker thread exits");
} }
} }
public static void main(String args[]) throws Exception
{
try {
ComThread.InitMTA();
ScriptTest3ActiveX script = new ScriptTest3ActiveX();
script.start();
Thread.sleep(1000);
Variant result = sC.invoke("Eval", args[0]);
System.out.println("eval("+args[0]+") = "+ result);
System.out.println("setting quit");
ScriptTest3ActiveX.quit = true;
} catch (ComException e) {
e.printStackTrace();
}
finally
{
System.out.println("main done");
ComThread.Release();
} }
} }
}

View File

@@ -1,16 +1,19 @@
package com.jacob.test.vbscript; package com.jacob.test.vbscript;
import com.jacob.com.*; import com.jacob.com.*;
import com.jacob.test.BaseTestCase;
import com.jacob.activeX.*; import com.jacob.activeX.*;
/** /**
* In this case the component is created and used in the same thread * In this case the component is created and used in the same thread
* and it's an Apartment Threaded component, so we call InitSTA. * and it's an Apartment Threaded component, so we call InitSTA.
* <p>
* May need to run with some command line options (including from inside
* Eclipse). Look in the docs area at the Jacob usage document for command line
* options.
*/ */
class ScriptTestActiveX public class ScriptTestActiveX extends BaseTestCase {
{ public void testActiveXScript() {
public static void main(String args[]) throws Exception
{
ComThread.InitSTA(true); ComThread.InitSTA(true);
DispatchEvents de = null; DispatchEvents de = null;
@@ -24,12 +27,12 @@ class ScriptTestActiveX
System.out.println("null returned when trying to create DispatchEvents"); System.out.println("null returned when trying to create DispatchEvents");
} }
Variant result; Variant result;
result = sC.invoke("Eval",args[0]); result = sC.invoke("Eval",getSampleVPScriptForEval());
// call it twice to see the objects reused // call it twice to see the objects reused
result = sC.invoke("Eval",args[0]); result = sC.invoke("Eval",getSampleVPScriptForEval());
// call it 3 times to see the objects reused // call it 3 times to see the objects reused
result = sC.invoke("Eval",args[0]); result = sC.invoke("Eval",getSampleVPScriptForEval());
System.out.println("eval("+args[0]+") = "+ result); System.out.println("eval("+getSampleVPScriptForEval()+") = "+ result);
} catch (ComException e) { } catch (ComException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@@ -1,12 +1,13 @@
package com.jacob.test.vbscript; package com.jacob.test.vbscript;
import com.jacob.com.Variant; import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/** /**
* Extracted from ScriptTest so everyone can see this * Extracted from ScriptTest so everyone can see this
* Made a test solely because it made the ant test easier
*/ */
public class ScriptTestErrEvents { public class ScriptTestErrEvents extends BaseTestCase {
public void Error(Variant[] args) public void Error(Variant[] args)
{ {

View File

@@ -1,18 +0,0 @@
package com.jacob.test.vbscript;
import com.jacob.com.*;
import com.jacob.activeX.*;
class speed
{
public static void main(String args[])
{
String lang = "VBScript";
ActiveXComponent sC = new ActiveXComponent("ScriptControl");
Dispatch sControl = sC.getObject();
Dispatch.put(sControl, "Language", lang);
for(int i=0;i<10000;i++) {
Dispatch.call(sControl, "Eval", "1+1");
}
}
}

View File

@@ -9,18 +9,20 @@ package com.jacob.test.windowsmedia;
* Look in the docs area at the Jacob usage document for command line options. * Look in the docs area at the Jacob usage document for command line options.
*/ */
import com.jacob.activeX.*; import com.jacob.activeX.*;
import com.jacob.test.BaseTestCase;
public class WMPlayer { public class WMPlayer extends BaseTestCase {
public static void main(String[] args){ public void testOpenWMPlayer() {
ActiveXComponent wmp = null; ActiveXComponent wmp = null;
wmp = new ActiveXComponent("WMPlayer.OCX"); wmp = new ActiveXComponent("WMPlayer.OCX");
// the sourceforge posting didn't post all the code so this is all we have // the sourceforge posting didn't post all the code so this is all we
// we need some other information on how to set the document // have we need some other information on how to set the document
// so that we have a url to open // so that we have a url to open
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
System.out.println("the wmp url is "+ wmp.getProperty("URL").toString()); System.out.println("the wmp url is "
+ wmp.getProperty("URL").toString());
} }
} }