B-1_14-DEV merge back to main

This commit is contained in:
clay_shooter
2008-02-02 01:38:25 +00:00
parent cd58b57a99
commit df0ba33797
97 changed files with 12208 additions and 8816 deletions

View File

@@ -4,56 +4,112 @@ import com.jacob.activeX.ActiveXComponent;
import com.jacob.test.BaseTestCase;
/**
* This exercises the two Dispatch factor methods that let you
* control whether you create a new running COM object or connect to an existing one
* This exercises the two Dispatch factor methods that let you control whether
* you create a new running COM object or connect to an existing one
* <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.
* 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 ActiveXComponentFactoryTest extends BaseTestCase {
public void testActiveXComponentFactory(){
/**
* This test is supposed to verify we get multiple instances when we mean
* too. Unfortunately, it requires that the runner of the test verify via
* the "Windows Task Manager"
*/
public void testMultipleInstances() {
ComThread.InitMTA();
String mApplicationId = "Word.Application";
ActiveXComponent instance1 = ActiveXComponent
.createNewInstance(mApplicationId);
ActiveXComponent instance2 = ActiveXComponent
.createNewInstance(mApplicationId);
try {
Thread.sleep(10000);
} catch (InterruptedException ie) {
}
instance1.invoke("Quit", new Variant[] {});
instance2.invoke("Quit", new Variant[] {});
ComThread.Release();
}
/**
* This test is supposed to verify we can force multiple items through a
* single running instance. It requires that a user physically watch the
* "Windows Task Manager" to verify only one copy of MS Word is executing
*/
public void testOnlyOneInstance() {
ComThread.InitMTA();
String mApplicationId = "Word.Application";
ActiveXComponent instance1 = new ActiveXComponent(mApplicationId);
ActiveXComponent instance2 = ActiveXComponent
.connectToActiveInstance(mApplicationId);
assertNotNull(instance2);
try {
Thread.sleep(10000);
} catch (InterruptedException ie) {
}
instance1.invoke("Quit", new Variant[] {});
ComThread.Release();
}
/**
* Test that verifies function of the ActiveXComponentFactory
*/
public void testActiveXComponentFactory() {
ComThread.InitSTA(true);
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");
String mApplicationId = "Word.Application";
ActiveXComponent mTryConnectingFirst = ActiveXComponent.connectToActiveInstance(mApplicationId);
if (mTryConnectingFirst != null ){
mTryConnectingFirst.invoke("Quit",new Variant[] {});
System.out.println("Was able to connect to MSWord when hadn't started it");
ActiveXComponent mTryConnectingFirst = ActiveXComponent
.connectToActiveInstance(mApplicationId);
if (mTryConnectingFirst != null) {
mTryConnectingFirst.invoke("Quit", new Variant[] {});
System.out
.println("Was able to connect to MSWord when hadn't started it");
} else {
System.out.println("Correctly could not connect to running MSWord");
System.out
.println("Correctly could not connect to running MSWord");
}
System.out.println(" Word Starting");
ActiveXComponent mTryStartingSecond = ActiveXComponent.createNewInstance(mApplicationId);
if (mTryStartingSecond == null){
ActiveXComponent mTryStartingSecond = ActiveXComponent
.createNewInstance(mApplicationId);
if (mTryStartingSecond == null) {
System.out.println("was unable to start up MSWord ");
} else {
System.out.println("Correctly could start MSWord");
}
ActiveXComponent mTryConnectingThird = ActiveXComponent.connectToActiveInstance(mApplicationId);
if (mTryConnectingThird == null ){
ActiveXComponent mTryConnectingThird = ActiveXComponent
.connectToActiveInstance(mApplicationId);
if (mTryConnectingThird == null) {
fail("Was unable able to connect to MSWord after previous startup");
} else {
System.out.println("Stopping MSWord");
// stop it so we can fail trying to connect to a running
mTryConnectingThird.invoke("Quit",new Variant[] {});
mTryConnectingThird.invoke("Quit", new Variant[] {});
}
Thread.sleep(2000);
ActiveXComponent mTryConnectingFourth = ActiveXComponent.connectToActiveInstance(mApplicationId);
if (mTryConnectingFourth != null ){
mTryConnectingFourth.invoke("Quit",new Variant[] {});
ActiveXComponent mTryConnectingFourth = ActiveXComponent
.connectToActiveInstance(mApplicationId);
if (mTryConnectingFourth != null) {
mTryConnectingFourth.invoke("Quit", new Variant[] {});
fail("Was able to connect to MSWord that was stopped");
} 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 (InterruptedException ie) {
} catch (ComException e) {
e.printStackTrace();
fail("Caught COM exception");
} finally {
//System.out.println("About to sleep for 2 seconds so we can bask in the glory of this success");
//Thread.sleep(2000);
// System.out.println("About to sleep for 2 seconds so we can bask
// in the glory of this success");
// Thread.sleep(2000);
ComThread.Release();
ComThread.quitMainSTA();
}

View File

@@ -9,37 +9,45 @@ import junit.framework.TestCase;
/**
* test cases that should exercise the new date conversion code
* <p>
* This test does not require any command line options because it is only a utility test
* This test does not require any command line options because it is only a
* utility test
*/
public class DateUtilitiesTest extends TestCase {
public void testDateUtilities(){
Date now = new Date();
double comTimeForNow = DateUtilities.convertDateToWindowsTime(now);
Date retrievedNow = DateUtilities.convertWindowsTimeToDate(comTimeForNow);
if (!now.equals(retrievedNow)){
fail("DateUtilities Date Test failed " +now+ " != " +retrievedNow );
} else {
System.out.println("DateUtilities Date Test passed");
}
}
public void testBeginningOfWindowsTime(){
// this is a magic time in the windows world
Date beginningOfWindowsTime =
new GregorianCalendar(1899, Calendar.DECEMBER, 30).getTime();
double comTimeForBeginningOfWindowsTime =
DateUtilities.convertDateToWindowsTime(beginningOfWindowsTime);
if (comTimeForBeginningOfWindowsTime > 0){
fail("Beginning of windows time test failed "
+comTimeForBeginningOfWindowsTime);
} else {
System.out.println("Beginning of windows time test passed");
}
}
/**
* verify date conversion to and from java
*/
public void testDateUtilities() {
Date now = new Date();
double comTimeForNow = DateUtilities.convertDateToWindowsTime(now);
Date retrievedNow = DateUtilities
.convertWindowsTimeToDate(comTimeForNow);
if (!now.equals(retrievedNow)) {
fail("DateUtilities Date Test failed " + now + " != "
+ retrievedNow);
} else {
System.out.println("DateUtilities Date Test passed");
}
}
/**
* Verify that the start of time is when we think it is.
*/
public void testBeginningOfWindowsTime() {
// this is a magic time in the windows world
Date beginningOfWindowsTime = new GregorianCalendar(1899,
Calendar.DECEMBER, 30).getTime();
double comTimeForBeginningOfWindowsTime = DateUtilities
.convertDateToWindowsTime(beginningOfWindowsTime);
if (comTimeForBeginningOfWindowsTime > 0) {
fail("Beginning of windows time test failed "
+ comTimeForBeginningOfWindowsTime);
} else {
System.out.println("Beginning of windows time test passed");
}
}
}

View File

@@ -3,31 +3,35 @@ package com.jacob.com;
import com.jacob.test.BaseTestCase;
/**
* This test verifies that the Dispatch object protects itself when
* the constructor is called with a null program id.
* Prior to this protection, the VM might crash.m
* This test verifies that the Dispatch object protects itself when the
* constructor is called with a null program id. Prior to this protection, the
* VM might crash.m
* <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.
* 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 extends BaseTestCase {
public void testNullProgramId(){
/**
* Verify that dispatch constructors are protected from null program ids.
*/
public void testNullProgramId() {
try {
String nullParam = null;
new Dispatch(nullParam);
fail("the dispatch failed to protect itself from null program ids");
} catch (IllegalArgumentException iae){
System.out.println(
"the dispatch protected itself from null program ids");
} catch (IllegalArgumentException iae) {
System.out
.println("the dispatch protected itself from null program ids");
}
try {
String nullParam = "";
new Dispatch(nullParam);
fail("the dispatch failed to protect itself from empty string program ids");
} catch (IllegalArgumentException iae){
System.out.println(
"the dispatch protected itself from empty string program ids");
} catch (IllegalArgumentException iae) {
System.out
.println("the dispatch protected itself from empty string program ids");
}
}
}

View File

@@ -1,24 +1,20 @@
package com.jacob.com;
import java.util.Date;
import com.jacob.test.BaseTestCase;
/**
* Test some of the Dispatch utility methods
* <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>
* 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 DispatchTest extends BaseTestCase {
public void testDispatch() {
Date testDate = new Date();
Variant fromDate = Dispatch.obj2variant(testDate);
Date returnedDate = fromDate.getJavaDate();
//System.out.println("test date is "+testDate);
//System.out.println("VariantDate is "+fromDate.getJavaDate());
assertTrue("Could not call obj2variant(Date) and get it to work",
testDate.equals(returnedDate));
}
/**
* Dummy test until someone gets their act together
*/
public void testDispatch() {
// what should we test
}
}

View File

@@ -4,27 +4,38 @@ import com.jacob.test.BaseTestCase;
/**
* Test armoring of dispatch static methods
* <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>
* 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 DispatchValidDispatchTest extends BaseTestCase {
public void testThrowIllegalArgumentException() {
try {
Dispatch.call(null, 0);
fail("Failed to throw IllegalArgumentException");
} catch (IllegalArgumentException iae){
System.out.println("Caught correct IllegalArgumentException: "+iae);
}
}
public void testThrowIllegalStateException() {
try {
Dispatch foo = new Dispatch();
Dispatch.call(foo, 0);
fail("Failed to throw IllegalStateException");
} catch (IllegalStateException ise){
System.out.println("Caught correct IllegalStateException "+ise);
}
}
/**
* force an IllegalArgumentException to verify the utility method throws
* correctly.
*/
public void testThrowIllegalArgumentException() {
try {
Dispatch.call(null, 0);
fail("Failed to throw IllegalArgumentException");
} catch (IllegalArgumentException iae) {
System.out.println("Caught correct IllegalArgumentException: "
+ iae);
}
}
/**
* force an IllegalStateException to verify the utility method throws
* correctly.
*/
public void testThrowIllegalStateException() {
try {
Dispatch foo = new Dispatch();
Dispatch.call(foo, 0);
fail("Failed to throw IllegalStateException");
} catch (IllegalStateException ise) {
System.out.println("Caught correct IllegalStateException " + ise);
}
}
}

View File

@@ -5,16 +5,18 @@ import com.jacob.test.BaseTestCase;
/**
* This will eventually be changed to a unit 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.
* 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 JacobObjectTest extends BaseTestCase {
public void testBuildVersion(){
System.out.println("build version is "+JacobObject.getBuildVersion());
System.out.println("build date is "+JacobObject.getBuildDate());
}
/**
* verify the build version and date functions work correctly
*/
public void testBuildVersion() {
System.out.println("build version is " + JacobReleaseInfo.getBuildVersion());
System.out.println("build date is " + JacobReleaseInfo.getBuildDate());
}
}

View File

@@ -0,0 +1,79 @@
package com.jacob.com;
import junit.framework.TestCase;
/**
* Tests Library loader architecture methods This test requires that jacob.jar
* be compiled and added to the classpath. You will need to refresh the release
* directory so that eclipse knows about jacob.jar. Otherwise you will get a
* "jar not found" dialog.
*
* <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.
*
* @author clay_shooter
*
*/
public class LibraryLoaderTest extends TestCase {
/**
* verify the architecture switches work
*/
public void testArchitectureVersions() {
System.out.println("running on 32Bit? VM"
+ LibraryLoader.shouldLoad32Bit());
// verify no null pointer is thrown
LibraryLoader.shouldLoad32Bit();
}
/**
* verify LibraryLoader.JACOB_DLL_NAME is read by LibraryLoader
*/
public void testJacobDllNameSystemProperty() {
// fill with bad dll name
System.setProperty(LibraryLoader.JACOB_DLL_NAME, "xxx");
try {
LibraryLoader.loadJacobLibrary();
fail("Should have been unable to load dll with name xxx");
} catch (UnsatisfiedLinkError ule) {
// yes, this is what we want to see when using a bad name
}
// no way to clear a system property once set so lets try setting to
// default
System.setProperty(LibraryLoader.JACOB_DLL_NAME, LibraryLoader
.getPreferredDLLName());
try {
LibraryLoader.loadJacobLibrary();
} catch (UnsatisfiedLinkError ule) {
fail("Should have been able to load dll after setting "
+ LibraryLoader.JACOB_DLL_NAME + " to "
+ LibraryLoader.getPreferredDLLName() + " "
+ ule.getMessage());
}
}
/**
* Verifies that we get a preferred DLL name with X86 since we really only
* run the unit tests on 32 bit platforms.
*/
public void testDLLNameContainsProcessorAndVersion() {
System.out.println(LibraryLoader.getPreferredDLLName());
if (LibraryLoader.shouldLoad32Bit()) {
// we build the package and run the unit tests on X86
assertTrue(LibraryLoader.getPreferredDLLName()
+ "should have contained "
+ LibraryLoader.DLL_NAME_MODIFIER_32_BIT, LibraryLoader
.getPreferredDLLName().contains(
LibraryLoader.DLL_NAME_MODIFIER_32_BIT));
} else {
// we build the package and run the unit tests on X86
assertTrue(LibraryLoader.getPreferredDLLName()
+ "should have contained "
+ LibraryLoader.DLL_NAME_MODIFIER_64_BIT, LibraryLoader
.getPreferredDLLName().contains(
LibraryLoader.DLL_NAME_MODIFIER_64_BIT));
}
}
}

View File

@@ -14,6 +14,9 @@ import com.jacob.test.BaseTestCase;
*/
public class ROT2Test extends BaseTestCase {
/**
* runs a multi-threaded test
*/
public void testDoesNotBlowUp() {
ROT2TestThread threads[] = new ROT2TestThread[4];
for (int i = 0; i < threads.length; i++) {
@@ -29,12 +32,14 @@ public class ROT2Test extends BaseTestCase {
*/
public class ROT2TestThread extends Thread {
private java.util.List ThreadObjects;
private java.util.List<Variant> ThreadObjects;
private int initialRunSize = 0;
/**
* @param arg0
* @param iStartCount
* the initial number of threads
*/
public ROT2TestThread(String arg0, int iStartCount) {
super(arg0);
@@ -43,7 +48,7 @@ public class ROT2Test extends BaseTestCase {
}
/**
* A semi-complexe serie of steps to put the ROT under stress. 1)
* A semi-complex series of steps to put the ROT under stress. 1)
* discard half the objects we've created 2) if size is greater than 1
* but not a even number, add 1 new object 3) stop when size is 1.
*
@@ -54,7 +59,7 @@ public class ROT2Test extends BaseTestCase {
// so the gc can't collect them
// 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<Variant>(initialRunSize);
for (int i = 0; i < initialRunSize; i++) {
// create the object
Variant aNewVariant = new Variant(getName() + "_" + i);
@@ -105,8 +110,8 @@ public class ROT2Test extends BaseTestCase {
}
/**
* Another test would be to override this to always return the same name.
* That would really screw the ROT!
* Another test would be to override this to always return the same
* name. That would really screw the ROT!
*
* @see java.lang.Object#toString()
*/

View File

@@ -3,8 +3,9 @@ package com.jacob.com;
import com.jacob.test.BaseTestCase;
/**
* This tries to exercise ROT's garbage collection This is named this way because
* the build.xml ignores files ending in Test when building the binary zip file
* This tries to exercise ROT's garbage collection This is named this way
* because the build.xml ignores files ending in Test when building the binary
* zip file
*
* This will eventually be changed to a unit test.
*
@@ -15,6 +16,9 @@ import com.jacob.test.BaseTestCase;
*/
public class ROT3Test extends BaseTestCase {
/**
* runs a multi-threaded test
*/
public void testROTVersion3() {
ROT3TestThread threads[] = new ROT3TestThread[4];
for (int i = 0; i < threads.length; i++) {
@@ -30,12 +34,14 @@ public class ROT3Test extends BaseTestCase {
*/
public class ROT3TestThread extends Thread {
private java.util.List variansCreatedInThisThread;
private java.util.List<Variant> variansCreatedInThisThread;
private int initialRunSize = 0;
/**
* @param arg0
* @param iStartCount
* the number of initial threads
*/
public ROT3TestThread(String arg0, int iStartCount) {
super(arg0);
@@ -44,18 +50,20 @@ public class ROT3Test extends BaseTestCase {
}
/**
* A semi-complexe serie of steps to put the ROT under stress. 1)
* A semi-complex series of steps to put the ROT under stress. 1)
* discard half the objects we've created 2) if size is greater than 1
* but not a even number, add 1 new object 3) stop when size is 1.
*
* @see java.lang.Runnable#run()
*/
@SuppressWarnings("deprecation")
public void run() {
// something that keeps object references around
// so the gc can't collect them
// 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<Variant>(
initialRunSize);
for (int i = 0; i < initialRunSize; i++) {
// create the object
Variant aNewVariant = new Variant(getName() + "_" + i);
@@ -92,9 +100,8 @@ public class ROT3Test extends BaseTestCase {
if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) {
// uses deprecated API to set up a special situation
// because this is an ROT test
ROT
.removeObject((JacobObject) variansCreatedInThisThread
.get(i - 1));
ROT.removeObject(variansCreatedInThisThread
.get(i - 1));
}
variansCreatedInThisThread.remove(i - 1);
}

View File

@@ -1,121 +1,133 @@
package com.jacob.com;
import com.jacob.test.BaseTestCase;
/**
* This tries to exercise ROT's garbage collection
*
* This will eventually be changed to a unit 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.
* 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 ROTTest extends BaseTestCase {
/**
* verify the SystemProperty (classname).PutInROT functions as expected.
* A value of false means instances of the class are not put in the ROT
* Any o ther value means they are
*/
public void testDontFillROTSystemProperty(){
debug("testDontFillROTSystemProperty: started");
// Make sure the class is loaded before running any of the tests
// class to load and any pre-defined Variants (FALSE and TRUE) to be created immediately
VariantViaEvent.class.getName();
if (ROT.getThreadObjects(true).entrySet().size() < 1){
debug("Failure: ROT should have objects in it as soon as Variant class loaded.");
}
/**
* verify the SystemProperty (classname).PutInROT functions as expected. A
* value of false means instances of the class are not put in the ROT Any o
* ther value means they are
*/
public void testDontFillROTSystemProperty() {
debug("testDontFillROTSystemProperty: started");
// Make sure the class is loaded before running any of the tests
// class to load and any pre-defined Variants (FALSE and TRUE) to be
// created immediately
VariantViaEvent.class.getName();
if (ROT.getThreadObjects(true).entrySet().size() < 1) {
debug("Failure: ROT should have objects in it as soon as Variant class loaded.");
}
System.setProperty(VariantViaEvent.class.getName()+ROT.PUT_IN_ROT_SUFFIX,"false");
int countPriorToTest = ROT.getThreadObjects(true).entrySet().size();
new VariantViaEvent();
int countAfterAddWithoutROT = ROT.getThreadObjects(true).entrySet().size();
if (countAfterAddWithoutROT != countPriorToTest){
debug("Failure: count prior: "+countPriorToTest+
" and count after without ROT was: "+countAfterAddWithoutROT);
}
System.setProperty(VariantViaEvent.class.getName()+ROT.PUT_IN_ROT_SUFFIX,"true");
new VariantViaEvent();
int countAfterAddWithROT = ROT.getThreadObjects(true).entrySet().size();
if (countAfterAddWithROT != (countPriorToTest+1)){
debug("Failure: count prior: "+countPriorToTest+
" and count after with ROT was: "+countAfterAddWithROT);
}
debug("testDontFillROTSystemProperty: completed");
}
System.setProperty(VariantViaEvent.class.getName()
+ ROT.PUT_IN_ROT_SUFFIX, "false");
int countPriorToTest = ROT.getThreadObjects(true).entrySet().size();
new VariantViaEvent();
int countAfterAddWithoutROT = ROT.getThreadObjects(true).entrySet()
.size();
if (countAfterAddWithoutROT != countPriorToTest) {
debug("Failure: count prior: " + countPriorToTest
+ " and count after without ROT was: "
+ countAfterAddWithoutROT);
}
/**
* Needs documentation. This test looks broken
*
*/
public void testGCBehavior(){
int sizeBeforeBuild = 0;
int sizeAfterBuild = 0;
int sizeBeforeGC = 0;
int sizeAfterGC = 0;
int loopSize = 10000;
int sizeExpectedAfterBuild = 0;
System.setProperty(VariantViaEvent.class.getName()
+ ROT.PUT_IN_ROT_SUFFIX, "true");
new VariantViaEvent();
int countAfterAddWithROT = ROT.getThreadObjects(true).entrySet().size();
if (countAfterAddWithROT != (countPriorToTest + 1)) {
debug("Failure: count prior: " + countPriorToTest
+ " and count after with ROT was: " + countAfterAddWithROT);
}
debug("testDontFillROTSystemProperty: completed");
}
debug("testGCBehavior: started");
debug("creating 10,000 object sets");
// cause classes to get loaded and any static instances to be created
SafeArray.class.getName();
Variant.class.getName();
sizeBeforeBuild = ROT.getThreadObjects(false).size();
sizeExpectedAfterBuild = ((loopSize*3)+sizeBeforeBuild);
for ( int i = 0 ; i < loopSize; i++){
SafeArray a1 = new SafeArray(Variant.VariantVariant, 2);
a1.setVariant(0, new Variant("foo"));
a1.setVariant(1, new Variant("bar"));
}
sizeAfterBuild = ROT.getThreadObjects(false).size();
if (sizeAfterBuild < sizeExpectedAfterBuild){
debug("Something got GC'd: "+sizeAfterBuild);
} else if (sizeAfterBuild > sizeExpectedAfterBuild){
debug("More: "+sizeAfterBuild+" than expected: "+sizeExpectedAfterBuild);
} else {
debug("They're all there");
}
// add more to the VM
debug("Flooding Memory to force GC");
for ( int i = 0 ; i <= loopSize*2; i++){
new String("this is just some text to see if we can force gc "+i);
}
// storage will hold weak references until the next JacobObject is created
System.gc();
sizeBeforeGC = ROT.getThreadObjects(false).size();
debug("Objects left after flood and gc but before adding a new object that clean's up weak references: "+sizeBeforeGC);
debug("Creating single object. This adds one and causes ROT to clean up GC'd");
new JacobObject();
sizeAfterGC = ROT.getThreadObjects(false).size();
debug("Objects left after adding one (caused weak ref objects to be removed): "+sizeAfterGC);
new JacobObject();
if (ROT.getThreadObjects(false).size() != sizeAfterGC+1){
debug("Unexpected number of objects after adding only one more "+ROT.getThreadObjects(false).size());
} else {
debug("Found number expected after adding one more " +(sizeAfterGC+1) );
}
ROT.clearObjects();
if (ROT.getThreadObjects(false) == null){
debug("ROT pool was destroyed as expected after clearObjects called.");
} else {
debug("ROT pool for thread still exists when it shouldn't");
}
//========= part two ================================
debug("Verifying doesn't blow up with double release");
for ( int i = 0 ; i <= 10000; i++){
new JacobObject();
}
// force safeRelease call on all objects
ROT.clearObjects();
// now force the gc to go collect them, running safeRelease again
System.gc();
debug("testGCBehavior: finished");
}
private static void debug(String message){
System.out.println(Thread.currentThread().getName()+" "+message);
}
/**
* Needs documentation. This test looks broken
*
*/
public void testGCBehavior() {
int sizeBeforeBuild = 0;
int sizeAfterBuild = 0;
int sizeBeforeGC = 0;
int sizeAfterGC = 0;
int loopSize = 10000;
int sizeExpectedAfterBuild = 0;
debug("testGCBehavior: started");
debug("creating 10,000 object sets");
// cause classes to get loaded and any static instances to be created
SafeArray.class.getName();
Variant.class.getName();
sizeBeforeBuild = ROT.getThreadObjects(false).size();
sizeExpectedAfterBuild = ((loopSize * 3) + sizeBeforeBuild);
for (int i = 0; i < loopSize; i++) {
SafeArray a1 = new SafeArray(Variant.VariantVariant, 2);
a1.setVariant(0, new Variant("foo"));
a1.setVariant(1, new Variant("bar"));
}
sizeAfterBuild = ROT.getThreadObjects(false).size();
if (sizeAfterBuild < sizeExpectedAfterBuild) {
debug("Something got GC'd: " + sizeAfterBuild);
} else if (sizeAfterBuild > sizeExpectedAfterBuild) {
debug("More: " + sizeAfterBuild + " than expected: "
+ sizeExpectedAfterBuild);
} else {
debug("They're all there");
}
// add more to the VM
debug("Flooding Memory to force GC");
for (int i = 0; i <= loopSize * 2; i++) {
new String("this is just some text to see if we can force gc " + i);
}
// storage will hold weak references until the next JacobObject is
// created
System.gc();
sizeBeforeGC = ROT.getThreadObjects(false).size();
debug("Objects left after flood and gc but before adding a new object that clean's up weak references: "
+ sizeBeforeGC);
debug("Creating single object. This adds one and causes ROT to clean up GC'd");
new JacobObject();
sizeAfterGC = ROT.getThreadObjects(false).size();
debug("Objects left after adding one (caused weak ref objects to be removed): "
+ sizeAfterGC);
new JacobObject();
if (ROT.getThreadObjects(false).size() != sizeAfterGC + 1) {
debug("Unexpected number of objects after adding only one more "
+ ROT.getThreadObjects(false).size());
} else {
debug("Found number expected after adding one more "
+ (sizeAfterGC + 1));
}
ROT.clearObjects();
if (ROT.getThreadObjects(false) == null) {
debug("ROT pool was destroyed as expected after clearObjects called.");
} else {
debug("ROT pool for thread still exists when it shouldn't");
}
// ========= part two ================================
debug("Verifying doesn't blow up with double release");
for (int i = 0; i <= 10000; i++) {
new JacobObject();
}
// force safeRelease call on all objects
ROT.clearObjects();
// now force the gc to go collect them, running safeRelease again
System.gc();
debug("testGCBehavior: finished");
}
private static void debug(String message) {
System.out.println(Thread.currentThread().getName() + " " + message);
}
}

View File

@@ -7,53 +7,64 @@ import com.jacob.test.BaseTestCase;
/**
* test cases that should exercise the new date conversion code
* <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.
* 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 VariantDateTest extends BaseTestCase {
public void testVariantDate() {
Date now = new Date();
Variant holder = new Variant();
holder.putDate(now);
Date retrievedNow = holder.getJavaDate();
if (!now.equals(retrievedNow)){
fail("Variant Date Test failed " +now+ " != " +retrievedNow );
} else {
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++){
Variant dateVariant = new Variant(now);
Date retrievedNow = holder.getJavaDate();
retrievedNow = dateVariant.getJavaDate();
if (!now.equals(retrievedNow)){
fail("Variant Date Test (1) failed " +now+ " != " +retrievedNow );
} else {
//System.out.println("Variant Date Test (1) passed");
}
// verify auto typecasting works
retrievedNow = (Date)dateVariant.toJavaObject();
if (!now.equals(retrievedNow)){
fail("Variant Date Test (2) failed " +now+ " != " +retrievedNow );
} else {
//System.out.println("Variant Date Test (2) passed "+retrievedNow);
}
Variant intVariant = new Variant(4);
Object variantReturn = intVariant.toJavaObject();
// degenerate test to make sure date isn't always returned
if (variantReturn instanceof Date ){
System.out.println("int variant returned date");
}
}
System.out.print("Test finished. All tests passed.");
}
/**
* verify the conversion of Variants into java dates
*/
public void testVariantDate() {
Date now = new Date();
Variant holder = new Variant();
holder.putDate(now);
Date retrievedNow = holder.getJavaDate();
if (!now.equals(retrievedNow)) {
fail("Variant Date Test failed " + now + " != " + retrievedNow);
} else {
System.out.println("Variant Date Test passed");
}
}
/**
* verify that the Variant constructor accepts Java dates and converts them
* correctly
*/
public void testVariantDateToJavaObject() {
Date now = new Date();
Variant holder = new Variant(now);
for (int i = 0; i < 30000; i++) {
Variant dateVariant = new Variant(now);
Date retrievedNow = holder.getJavaDate();
retrievedNow = dateVariant.getJavaDate();
if (!now.equals(retrievedNow)) {
fail("Variant Date Test (1) failed " + now + " != "
+ retrievedNow);
} else {
// System.out.println("Variant Date Test (1) passed");
}
// verify auto typecasting works
retrievedNow = (Date) dateVariant.toJavaObject();
if (!now.equals(retrievedNow)) {
fail("Variant Date Test (2) failed " + now + " != "
+ retrievedNow);
} else {
// System.out.println("Variant Date Test (2) passed
// "+retrievedNow);
}
Variant intVariant = new Variant(4);
Object variantReturn = intVariant.toJavaObject();
// degenerate test to make sure date isn't always returned
if (variantReturn instanceof Date) {
System.out.println("int variant returned date");
}
}
System.out.print("Test finished. All tests passed.");
}
}

View File

@@ -1,6 +1,7 @@
package com.jacob.com;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import com.jacob.test.BaseTestCase;
@@ -9,474 +10,658 @@ import com.jacob.test.BaseTestCase;
* runs through some of the get and set methods on Variant
*
* <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.
* 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 VariantTest extends BaseTestCase {
/**
* This verifies that toJavaObject() works for all of the
* main data types when they exist as a byRef version.
* This verifies that toJavaObject() works for all of the main data types
* when they exist as a byRef version.
* <p>
* It compares the toJavaObject() for a byref against the
* toJavaObject() for the regular.
*
* It compares the toJavaObject() for a byref against the toJavaObject() for
* the regular.
*
*/
public void testByRefToJavaObject(){
public void testByRefToJavaObject() {
Variant v = null;
Variant vByRef = null;
v = new Variant(new Float(53.3),false);
vByRef = new Variant(new Float(53.3),true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){
fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same");
v = new Variant(new Float(53.3), false);
vByRef = new Variant(new Float(53.3), true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())) {
fail(v.toString() + " could not make type " + v.getvt() + " and "
+ vByRef.getvt() + " java objects come out the same");
}
v = new Variant(new Double(53.3),false);
vByRef = new Variant(new Double(53.3),true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){
fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same");
}
v = new Variant(new Boolean(true),false);
vByRef = new Variant(new Boolean(true),true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){
fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same");
}
v = new Variant(new Integer(53),false);
vByRef = new Variant(new Integer(53),true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){
fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same");
}
v = new Variant(new Short((short)53),false);
vByRef = new Variant(new Short((short)53),true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){
fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same");
v = new Variant(new Double(53.3), false);
vByRef = new Variant(new Double(53.3), true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())) {
fail(v.toString() + " could not make type " + v.getvt() + " and "
+ vByRef.getvt() + " java objects come out the same");
}
v = new Variant("53.33",false);
vByRef = new Variant("53.33",true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){
fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same");
v = new Variant(new Boolean(true), false);
vByRef = new Variant(new Boolean(true), true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())) {
fail(v.toString() + " could not make type " + v.getvt() + " and "
+ vByRef.getvt() + " java objects come out the same");
}
v = new Variant(new Integer(53), false);
vByRef = new Variant(new Integer(53), true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())) {
fail(v.toString() + " could not make type " + v.getvt() + " and "
+ vByRef.getvt() + " java objects come out the same");
}
v = new Variant(new Short((short) 53), false);
vByRef = new Variant(new Short((short) 53), true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())) {
fail(v.toString() + " could not make type " + v.getvt() + " and "
+ vByRef.getvt() + " java objects come out the same");
}
v = new Variant("53.33", false);
vByRef = new Variant("53.33", true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())) {
fail(v.toString() + " could not make type " + v.getvt() + " and "
+ vByRef.getvt() + " java objects come out the same");
}
// Ugh, you have to pick a magic number whose scale is less than 28
// 53.53 had a scale of 64 and 53.52 had a scale of 47
BigDecimal testDecimal = new BigDecimal(53.50);
v = new Variant(testDecimal,false);
vByRef = new Variant(testDecimal,true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){
fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same");
v = new Variant(testDecimal, false);
vByRef = new Variant(testDecimal, true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())) {
fail(v.toString() + " could not make type " + v.getvt() + " and "
+ vByRef.getvt() + " java objects come out the same");
}
Date now = new Date();
v = new Variant(now,false);
vByRef = new Variant(now,true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())){
fail(v.toString() + " could not make type "
+ v.getvt() +" and "+ vByRef.getvt()
+" java objects come out the same");
v = new Variant(now, false);
vByRef = new Variant(now, true);
if (!v.toJavaObject().equals(vByRef.toJavaObject())) {
fail(v.toString() + " could not make type " + v.getvt() + " and "
+ vByRef.getvt() + " java objects come out the same");
}
// need to do currency also
}
/**
* try and test VT_I8. This should only work on 64 bit machines
*/
public void testLong() {
Variant v = null;
Variant vByRef = null;
long longNumber = 1L << 40;
v = new Variant(new Long(longNumber), false);
vByRef = new Variant(new Long(longNumber), true);
assertEquals("Could recover long number " + longNumber, v.getLong(),
longNumber);
assertEquals("Could not make long number " + longNumber
+ " come out the same for get and getByRef()",
v.toJavaObject(), vByRef.toJavaObject());
v = new Variant("" + longNumber);
v.changeType(Variant.VariantLongInt);
assertEquals("Conversion from string to long didn't work ",
v.getLong(), longNumber);
}
/**
* do some testing around currencies
*/
public void testCurrencyHandling() {
Variant v = null;
Variant vByRef = null;
// need to do currency also
// currency is an integer scaled up by 10,000 to give 4 digits to the
// right of the decimal
int currencyScale = 10000;
long twentyThousand = 20000 * currencyScale;
Currency twentyThousandAsCurrency = new Currency(twentyThousand);
v = new Variant(twentyThousandAsCurrency, false);
vByRef = new Variant(twentyThousandAsCurrency, true);
if (!(v.toJavaObject() instanceof Currency)) {
fail("v.toJavaObject was not Long for currency but was: "
+ v.toJavaObject());
}
if (!v.toJavaObject().equals(vByRef.toJavaObject())) {
fail(v.toString() + " could not make type " + v.getvt() + " and "
+ vByRef.getvt() + " java objects come out the same");
}
long twentyThousandDotSeven = twentyThousand + 700;
Currency twentyThousandDotSevenAsCurrency = new Currency(
twentyThousandDotSeven);
// use the primitive constructor
v = new Variant(twentyThousandDotSevenAsCurrency);
assertEquals("failed test with " + twentyThousandDotSeven,
twentyThousandDotSeven, v.getCurrency().longValue());
}
/**
* 4/2007 bug report toObject on dispatch tries to call getDispatchRef
* instead of getDispatch so toString() on dispatch blows up.
*
*
*/
public void testDispatchToJavaObject(){
public void testDispatchToJavaObject() {
Variant v2 = new Variant();
v2.putNothing();
// this test fails even though the exact same code below works fine
//v2.toJavaObject();
// v2.toJavaObject();
}
/**
* see what happens when we conver to by ref
*
*
*/
public void testSomeChangeVT(){
public void testSomeChangeVT() {
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;
v = new Variant(53.3);
short originalVT = v.getvt();
short modifier;
modifier = Variant.VariantShort;
vConverted = v.changeType(modifier);
if (vConverted.getvt() != modifier){
fail("Failed to change Variant "+originalVT
+ " using mask "+modifier
+ " resulted in "+vConverted.getvt()
);
if (vConverted.getvt() != modifier) {
fail("Failed to change Variant " + originalVT + " using mask "
+ modifier + " resulted in " + vConverted.getvt());
}
modifier = Variant.VariantString;
vConverted = v.changeType(modifier);
if (vConverted.getvt() != modifier){
fail("Failed to change Variant "+originalVT
+ " using mask "+modifier
+ " resulted in "+vConverted.getvt()
);
if (vConverted.getvt() != modifier) {
fail("Failed to change Variant " + originalVT + " using mask "
+ modifier + " resulted in " + vConverted.getvt());
}
// can't convert to byref!
modifier = Variant.VariantByref | Variant.VariantShort;
modifier = Variant.VariantByref | Variant.VariantShort;
vConverted = v.changeType(modifier);
if (vConverted.getvt() == modifier){
fail("Should not have been able to change Variant "+originalVT
+ " using mask "+modifier
+ " resulted in "+vConverted.getvt()
);
if (vConverted.getvt() == modifier) {
fail("Should not have been able to change Variant " + originalVT
+ " using mask " + modifier + " resulted in "
+ vConverted.getvt());
}
}
/**
* make sure variant with no backing store works.
*
*
*/
public void testUninitializedVariant(){
public void testUninitializedVariant() {
Variant v;
// Variants created without parameters are auto set to VariantEmpty
v = new Variant();
try {
if (v.getvt() == Variant.VariantEmpty){
if (v.getvt() == Variant.VariantEmpty) {
// successful
// System.out.println("Variant initialized without parameters correctly set to empty");
// System.out.println("Variant initialized without parameters
// correctly set to empty");
} else {
throw new RuntimeException("getvt() on uninitialized variant shoud have returned VariantEmpty, instead returned "+v.getvt());
throw new RuntimeException(
"getvt() on uninitialized variant shoud have returned VariantEmpty, instead returned "
+ v.getvt());
}
} catch (IllegalStateException ise){
throw new RuntimeException("getvt() on uninitialized variant shoud have succeeded, but instead threw exception");
} catch (IllegalStateException ise) {
throw new RuntimeException(
"getvt() on uninitialized variant shoud have succeeded, but instead threw exception");
}
try {
v.toString();
} catch (IllegalStateException ise){
} catch (IllegalStateException ise) {
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");
}
}
/**
*
* verify the toString() method does not do type conversion
*/
public void testToStringDoesNotConvert(){
public void testToStringDoesNotConvert() {
Variant v;
v = new Variant(true);
v.toString();
if (v.getvt() != Variant.VariantBoolean){
throw new RuntimeException("toString() converted boolean to something else");
if (v.getvt() != Variant.VariantBoolean) {
throw new RuntimeException(
"toString() converted boolean to something else");
} else {
//fail("toString() correctly does not convert type");
// fail("toString() correctly does not convert type");
}
if (v.getBoolean() != true){
fail("toString() converted boolean true to "+ v.getBoolean());
if (v.getBoolean() != true) {
fail("toString() converted boolean true to " + v.getBoolean());
}
v = new Variant(false);
v.toString();
if (v.getvt() != Variant.VariantBoolean){
throw new RuntimeException("toString() converted boolean to something else");
if (v.getvt() != Variant.VariantBoolean) {
throw new RuntimeException(
"toString() converted boolean to something else");
} else {
//fail("toString() correctly does not convert type");
// fail("toString() correctly does not convert type");
}
if (v.getBoolean() != false){
fail("toString() converted boolean false to "+ v.getBoolean());
if (v.getBoolean() != false) {
fail("toString() converted boolean false to " + v.getBoolean());
}
}
public void testSafeReleaseBoolean(){
/**
* Verify that booleans can be released. Part of the suite that checks all
* types.
*/
public void testSafeReleaseBoolean() {
Variant v;
v = new Variant(true);
//System.out.println("Newly created Variant ("+ v.getBoolean()+") "+
// "trying to create access violation but it doesn't seem to be easy");
// System.out.println("Newly created Variant ("+ v.getBoolean()+") "+
// "trying to create access violation but it doesn't seem to be easy");
v.safeRelease();
try {
v.getBoolean();
fail("IllegalStateException should have been thrown when querying safeReleased object");
throw new RuntimeException("test failed");
} catch (IllegalStateException ise){
//System.out.println("IllegalStateException correctly thrown after safeRelease");
} catch (IllegalStateException ise) {
// System.out.println("IllegalStateException correctly thrown after
// safeRelease");
}
v = new Variant(true);
for ( int i = 0 ; i < 10; i ++){
new Variant ("xxx"+i);
for (int i = 0; i < 10; i++) {
new Variant("xxx" + i);
new Variant(i);
new Variant ("yyy"+i);
new Variant("yyy" + i);
}
ComThread.Release();
try {
v.getBoolean();
fail("IllegalStateException should have been thrown when querying ComThread.Release");
throw new RuntimeException("test failed");
} catch (IllegalStateException ise){
//System.out.println("IllegalStateException correctly thrown after ComThread.Release");
} catch (IllegalStateException ise) {
// System.out.println("IllegalStateException correctly thrown after
// ComThread.Release");
}
}
/**
* verify the constant values aren't released with safeRelease
*
*
*/
public void testSafeReleaseConstant(){
//System.out.println("Using Static constant Variant - should never throw access violation");
public void testSafeReleaseConstant() {
// System.out.println("Using Static constant Variant - should never
// throw access violation");
Variant.VT_TRUE.safeRelease();
if (Variant.VT_TRUE.getBoolean() != true){
if (Variant.VT_TRUE.getBoolean() != true) {
fail("VT_TRUE has been broken by SafeRelease()");
throw new RuntimeException("test failed");
} else {
//System.out.println("VT_TRUE survived SafeRelease()");
// System.out.println("VT_TRUE survived SafeRelease()");
}
for ( int i = 0 ; i < 10; i ++){
new Variant ("xxx"+i);
for (int i = 0; i < 10; i++) {
new Variant("xxx" + i);
new Variant(i);
new Variant ("yyy"+i);
new Variant("yyy" + i);
}
ComThread.Release();
if (Variant.VT_TRUE.getBoolean() != true){
if (Variant.VT_TRUE.getBoolean() != true) {
fail("VT_TRUE has been broken by ComThread.Release()");
throw new RuntimeException("test failed");
} else {
//System.out.println("VT_TRUE survived ComThread.Release()");
// System.out.println("VT_TRUE survived ComThread.Release()");
}
}
/**
* this used to try and and create an access violation but that
* didn't work and now the methods on the Variant are smarter about
* working after a release
*
* this used to try and and create an access violation but that didn't work
* and now the methods on the Variant are smarter about working after a
* release
*
*/
public void testSafeReleaseString(){
String mTestString = "Guitar Hero";
public void testSafeReleaseString() {
String mTestString = "Guitar Hero";
Variant v = new Variant(mTestString);
//System.out.println("Newly created Variant ("+ v.getString()+") "+
// "about to safe release and then access");
// System.out.println("Newly created Variant ("+ v.getString()+") "+
// "about to safe release and then access");
v.safeRelease();
try {
v.getString();
fail("IllegalStateException should have been thrown when querying safeReleased object");
throw new RuntimeException("test failed");
} catch (IllegalStateException ise){
//System.out.println("IllegalStateException correctly thrown after safeRelease");
} catch (IllegalStateException ise) {
// System.out.println("IllegalStateException correctly thrown after
// safeRelease");
}
}
/**
* verifies objectIsAConstant works as expected
*
*/
public void testObjectIsAConstant(){
Variant v = new Variant("d");
if (!v.objectIsAConstant(Variant.VT_FALSE)){
fail("did not recognize VT_FALSE");
}
if (!v.objectIsAConstant(Variant.VT_TRUE)){
fail("did not recognize VT_TRUE");
}
if (!v.objectIsAConstant(Variant.VT_MISSING)){
fail("did not recognize VT_MISSING");
}
if (!v.objectIsAConstant(Variant.DEFAULT)){
fail("did not recognize DEFAULT");
}
if (v.objectIsAConstant(new Variant(true))){
fail("confused a boolean with VT_TRUE");
}
if (v.objectIsAConstant(new Variant(false))){
fail("confused a boolean with VT_FALSE");
}
}
}
/**
* verifies objectIsAConstant works as expected
*
*/
public void testObjectIsAConstant() {
Variant v = new Variant("d");
if (!v.objectIsAConstant(Variant.VT_FALSE)) {
fail("did not recognize VT_FALSE");
}
if (!v.objectIsAConstant(Variant.VT_TRUE)) {
fail("did not recognize VT_TRUE");
}
if (!v.objectIsAConstant(Variant.VT_MISSING)) {
fail("did not recognize VT_MISSING");
}
if (!v.objectIsAConstant(Variant.DEFAULT)) {
fail("did not recognize DEFAULT");
}
if (v.objectIsAConstant(new Variant(true))) {
fail("confused a boolean with VT_TRUE");
}
if (v.objectIsAConstant(new Variant(false))) {
fail("confused a boolean with VT_FALSE");
}
}
/**
* tests put and get methods looking for obvious defects
*
*
*/
public void testPutsAndGets(){
public void testPutsAndGets() {
Variant v = new Variant();
v.putInt((int)10);
assertEquals("int test failed", (int)10, v.getInt());
v.putInt(10);
assertEquals("int test failed", 10, v.getInt());
v.putShort((short)20);
assertEquals("short test failed", (short)20, v.getShort());
v.putByte((byte)30);
assertEquals("byte test failed", (byte)30, v.getByte());
v.putShort((short) 20);
assertEquals("short test failed", (short) 20, v.getShort());
v.putByte((byte) 30);
assertEquals("byte test failed", (byte) 30, v.getByte());
v.putFloat(40);
if (v.getFloat() != 40.0){
if (v.getFloat() != 40.0) {
fail("float test failed");
}
v.putDouble(50);
if (v.getDouble() != 50.0){
if (v.getDouble() != 50.0) {
fail("double test failed");
}
v.putString("1234.567");
assertEquals("string test failed","1234.567", v.getString());
assertEquals("string test failed", "1234.567", v.getString());
v.putBoolean(true);
assertEquals("failed boolean test(true)",true, v.getBoolean());
assertEquals("failed boolean test(true)", true, v.getBoolean());
v.putBoolean(false);
assertEquals("failed boolean test(false)",false,v.getBoolean());
assertEquals("failed boolean test(false)", false, v.getBoolean());
long originalValue = 123456789123456789L;
v.putCurrency(new Currency(originalValue));
assertEquals("failed currency test", 123456789123456789L, v
.getCurrency().longValue());
v.putCurrency(123456789123456789L);
assertEquals("failed currency test",123456789123456789L, v.getCurrency());
BigDecimal testDecimal = new BigDecimal("22.222");
v.putDecimal(testDecimal);
assertEquals("failed BigDecimal test", testDecimal,v.getDecimal());
assertEquals("failed BigDecimal test", testDecimal, v.getDecimal());
Date ourDate = new Date();
v.putDate(ourDate);
Date retrievedDate = v.getJavaDate();
if (!retrievedDate.equals(ourDate)){
if (!retrievedDate.equals(ourDate)) {
fail("failed java date load and unload");
}
v.putNull();
if (!v.isNull()){
if (!v.isNull()) {
fail("failed detecting set null");
}
v.putString("something other than null");
if (v.isNull()){
if (v.isNull()) {
fail("failed null replacement with string");
}
v.putEmpty();
if (!v.isNull()){
if (!v.isNull()) {
fail("failed detecting set empty as null");
}
v.putString("something other than null");
if (v.isNull()){
if (v.isNull()) {
fail("failed empty replacement with string as isNull");
}
Variant v2 = new Variant();
v2.putNothing();
if (v2.getvt() != Variant.VariantDispatch){
if (v2.getvt() != Variant.VariantDispatch) {
fail("putNothing was supposed to set the type to VariantDispatch");
}
if (!v2.isNull()){
if (!v2.isNull()) {
fail("putNothing is supposed to cause isNull() to return true");
}
// this line blows up in the test above
if (v2.toJavaObject() == null){
if (v2.toJavaObject() == null) {
fail("putNothing() followed by toJavaObject() should return a Dispatch");
}
}
/**
* Spin up a lot of threads and have them all create variants
* 3/2007 there have been several reports in multi-threaded servers that show init() failing
*
* verify decimal works right
*/
public void testManyThreadedInit(){
VariantInitTestThread threads[] = new VariantInitTestThread[75];
System.out.println("Starting thread test ("+threads.length
public void testDecimalConversion() {
Variant v = new Variant();
v.changeType(Variant.VariantDecimal);
for (int i = 10; i >= -10; i--) {
v.putDecimal(new BigDecimal(i));
// first see if we can get it back as decimal
assertEquals("conversion back to decimal failed " + i,
new BigDecimal(i), v.getDecimal());
v.changeType(Variant.VariantFloat);
// now see if a float conversion would work
assertEquals("conversion to float failed " + i, new Float(i), v
.getFloat());
// now convert it back to decimal for reassignment
v.changeType(Variant.VariantDecimal);
assertTrue("Failed conversion of type back to Decimal " + i, v
.getvt() == Variant.VariantDecimal);
}
}
/**
* for(BigDecimal i in 79228162514264337593543950330.0 ..
* 79228162514264337593543950341.0) { com.jacob.com.Variant dv = new
* com.jacob.com.Variant(i, false) println i + " : " + dv.getDecimal() }
*
*/
public void testLargeDecimals() {
// the largest decimal number, not in hex is
// 7922816251426433759354395033.0
BigInteger theStartDigits = new BigInteger("ffffffffffffffffffffff00",
16);
BigInteger theMaxDigits = new BigInteger("ffffffffffffffffffffffff", 16);
BigDecimal startDecimal = new BigDecimal(theStartDigits);
BigDecimal endDecimal = new BigDecimal(theMaxDigits);
BigDecimal incrementDecimal = new BigDecimal(1);
BigDecimal testDecimal = startDecimal;
Variant testVariant;
while (endDecimal.compareTo(testDecimal) >= 0) {
testVariant = new Variant(testDecimal, false);
BigDecimal result = testVariant.getDecimal();
assertEquals(testDecimal, result);
testDecimal = testDecimal.add(incrementDecimal);
}
// test Decimal is now too large
try {
new Variant(testDecimal, false);
} catch (IllegalArgumentException iae) {
// System.out.println("Caught expected exception");
}
// lets try something different. we can call putVariant with rounding
// enabled
testVariant = new Variant();
testVariant.changeType(Variant.VariantDecimal);
try {
testVariant.putDecimal(endDecimal.setScale(30));
fail("Should have thrown exception with scale of 30 and no rounding");
} catch (IllegalArgumentException iae) {
// should have caught this exception
}
// now we test with a negative scale. Note that you can't do with
// without some magic, in this case scientific notation
try {
testVariant.putDecimal(new BigDecimal("700E24"));
assertTrue(new BigDecimal("700E24").compareTo(testVariant
.getDecimal()) == 0);
} catch (IllegalArgumentException iae) {
// should have caught this exception
}
testVariant.putDecimal(VariantUtilities
.roundToMSDecimal(new BigDecimal("700E24")));
// use compareTo because it takes into account varying scales
assertTrue(new BigDecimal("700E24").compareTo(testVariant.getDecimal()) == 0);
// This passes because the number is within range.
testVariant.putDecimal(endDecimal);
// this should pass because we have rounding turned on
// it turns out the max number gets more digits when
// it's scale is set to 30. so we can't use the max number when there is
// a scale
BigDecimal modifiedDecimal = endDecimal;
System.out.println("integer piece starts as "
+ modifiedDecimal.unscaledValue().toString(16) + " scale=: "
+ modifiedDecimal.scale());
System.out.println("integer piece after rounding without scale is "
+ VariantUtilities.roundToMSDecimal(modifiedDecimal)
.unscaledValue().toString(16) + " scale=: "
+ modifiedDecimal.scale());
System.out.println("integer piece after rounding with scale 30 is "
+ VariantUtilities.roundToMSDecimal(
modifiedDecimal.setScale(30)).unscaledValue().toString(
16) + " scale=: " + modifiedDecimal.scale());
try {
testVariant.putDecimal(VariantUtilities
.roundToMSDecimal(modifiedDecimal.setScale(30)));
fail("should have thrown an exception for a number whose scale "
+ "change created too many digits to be represented.");
} catch (IllegalArgumentException iae) {
// should catch an exception here because the rounding after scale
// change would have made the number too large
}
System.out.println("");
modifiedDecimal = endDecimal.subtract(incrementDecimal);
System.out.println("integer piece starts as "
+ modifiedDecimal.unscaledValue().toString(16) + " scale=: "
+ modifiedDecimal.scale());
System.out.println("integer piece after rounding without scale is "
+ VariantUtilities.roundToMSDecimal(modifiedDecimal)
.unscaledValue().toString(16) + " scale=: "
+ modifiedDecimal.scale());
System.out.println("integer piece after rounding with scale 30 is "
+ VariantUtilities.roundToMSDecimal(
modifiedDecimal.setScale(30)).unscaledValue().toString(
16) + " scale=: " + modifiedDecimal.scale());
testVariant.putDecimal(VariantUtilities
.roundToMSDecimal(modifiedDecimal.setScale(30)));
System.out.println("");
}
/**
* Spin up a lot of threads and have them all create variants 3/2007 there
* have been several reports in multi-threaded servers that show init()
* failing
*
*/
public void testManyThreadedInit() {
VariantInitTestThread threads[] = new VariantInitTestThread[75];
System.out.println("Starting thread test (" + threads.length
+ " threads each creating 10000 objects)."
+ " This may take 30 seconds or more.");
for (int i = 0; i < threads.length; i++)
{
threads[i] = new VariantInitTestThread("thread-" + i, 10000);
}
for (int i = 0; i < threads.length; i++)
{
threads[i].start();
}
int numComplete = 0;
while (numComplete < threads.length){
// give the works time to work
try {
Thread.sleep(333);
} catch (InterruptedException ie){
for (int i = 0; i < threads.length; i++) {
threads[i] = new VariantInitTestThread("thread-" + i, 10000);
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
int numComplete = 0;
while (numComplete < threads.length) {
// give the works time to work
try {
Thread.sleep(333);
} catch (InterruptedException ie) {
// do nothing
}
numComplete = 0;
for ( int i = 0; i < threads.length; i++){
if (threads[i].isComplete){
numComplete++;
}
}
//System.out.print("["+numComplete+"/"+threads.length+"]");
}
numComplete = 0;
for (int i = 0; i < threads.length; i++) {
if (threads[i].isComplete) {
numComplete++;
}
}
// System.out.print("["+numComplete+"/"+threads.length+"]");
}
System.out.println("Finished thread test");
}
/**
* a class to create variants in seperate threads
* @author joe
*
*/
class VariantInitTestThread extends Thread
{
private boolean isComplete = false;
private int initialRunSize = 0;
/**
* @param arg0
*/
public VariantInitTestThread(String newThreadName, int iStartCount)
{
super(newThreadName);
initialRunSize = iStartCount;
}
public boolean isComplete(){
return isComplete;
}
/**
* Blow out a bunch of Variants
*
* @see java.lang.Runnable#run()
*/
public void run()
{
for (int variantIndex = 0; variantIndex < initialRunSize; variantIndex ++ ){
try {
Thread.yield();
Thread.sleep(0);
} catch (InterruptedException ie){
/**
* a class to create variants in separate threads
*
*/
class VariantInitTestThread extends Thread {
private boolean isComplete = false;
private int initialRunSize = 0;
/**
* @param newThreadName
* the name for the thread
* @param iStartCount
* number of threads to start with
*/
public VariantInitTestThread(String newThreadName, int iStartCount) {
super(newThreadName);
initialRunSize = iStartCount;
}
/**
* getter so master can see if thread is done
*
* @return state of complete flag
*/
public boolean isComplete() {
return isComplete;
}
/**
* Blow out a bunch of Variants
*
* @see java.lang.Runnable#run()
*/
public void run() {
for (int variantIndex = 0; variantIndex < initialRunSize; variantIndex++) {
try {
Thread.yield();
Thread.sleep(0);
} catch (InterruptedException ie) {
// do nothing
}
//System.out.println(Thread.currentThread().getName());
Variant testSubject = new Variant(variantIndex);
testSubject.getvt();
testSubject.getInt();
}
isComplete = true;
}
// System.out.println(Thread.currentThread().getName());
Variant testSubject = new Variant(variantIndex);
testSubject.getvt();
testSubject.getInt();
}
isComplete = true;
}
}
}

View File

@@ -0,0 +1,33 @@
package com.jacob.com;
import java.util.Date;
import com.jacob.test.BaseTestCase;
/**
* This class should test some of the converter capabilities
*
*/
public class VariantUtilitiesTest extends BaseTestCase {
/**
* verify that dispatch can convert from object to variant and that the
* variant holds the right value
*/
public void testConverters() {
Date testDate = new Date();
Variant fromDate = VariantUtilities.objectToVariant(testDate);
Date returnedDate = fromDate.getJavaDate();
// System.out.println("test date is "+testDate);
// System.out.println("VariantDate is "+fromDate.getJavaDate());
assertTrue("Could not call obj2variant(Date) and get it to work",
testDate.equals(returnedDate));
Currency someMoney = new Currency(12349876L);
Variant fromMoney = VariantUtilities.objectToVariant(someMoney);
Currency someMoneyConverted = fromMoney.getCurrency();
assertTrue("Could not call obj2variant(Long) and get it to work",
someMoney.equals(someMoneyConverted));
System.out.println("currency returned was: " + someMoneyConverted);
}
}

View File

@@ -7,6 +7,9 @@ import junit.framework.TestCase;
import com.jacob.com.JacobObject;
/**
* This base test class may require that the unittest package be
* 'jacob-project/unittest' be on the classpath to find some resources.
*
* 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:
@@ -35,10 +38,11 @@ public class BaseTestCase extends TestCase {
/**
* this test exists just to test the setup.
*/
public void testSetup(){
public void testSetup() {
JacobObject foo = new JacobObject();
assertNotNull(foo);
}
/**
*
* @return a simple VB script that generates the result "3"
@@ -49,15 +53,17 @@ public class BaseTestCase extends TestCase {
}
/**
* 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.
* Converts the class name into a path and appends the resource name. Used
* to derive the path to a resource 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
* @return a class loader compatible fully qualified file system path to a
* resource
*/
public String getJavaFilePathToPackageResource(String resourceName,
@SuppressWarnings("unchecked")
private String getJavaFilePathToPackageResource(String resourceName,
Class classInSamePackageAsResource) {
String classPackageName = classInSamePackageAsResource.getName();
@@ -65,14 +71,15 @@ public class BaseTestCase extends TestCase {
if (i == -1) {
classPackageName = "";
} else {
classPackageName = classPackageName.substring(0,i);
classPackageName = classPackageName.substring(0, i);
}
// change all "." to ^ for later conversion to "/" so we can append resource names with "."
// change all "." to ^ for later conversion to "/" so we can append
// resource names with "."
classPackageName = classPackageName.replace('.', '^');
System.out.println("classPackageName: " + classPackageName);
String fullPathToResource;
if (classPackageName.length()> 0){
if (classPackageName.length() > 0) {
fullPathToResource = classPackageName + "^" + resourceName;
} else {
fullPathToResource = resourceName;
@@ -81,30 +88,35 @@ public class BaseTestCase extends TestCase {
fullPathToResource = fullPathToResource.replace('^', '/');
System.out.println("fullPathToResource: " + fullPathToResource);
URL urlToLibrary =
classInSamePackageAsResource.getClassLoader().getResource(fullPathToResource);
assertNotNull("URL to resource "+resourceName+" should not be null",urlToLibrary);
URL urlToLibrary = classInSamePackageAsResource.getClassLoader()
.getResource(fullPathToResource);
assertNotNull("URL to resource " + resourceName
+ " should not be null."
+ " You probably need to add 'unittest' to the"
+ " classpath so the tests can find resources", urlToLibrary);
String fullPathToResourceAsFile = urlToLibrary.getFile();
System.out.println("url to library: "+urlToLibrary);
System.out.println("fullPathToResourceAsFile: "+fullPathToResourceAsFile);
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.
* Converts the class name into a path and appends the resource name. Used
* to derive the path to a resource 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
* @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);
@SuppressWarnings("unchecked")
public String getWindowsFilePathToPackageResource(String resourceName,
Class classInSamePackageAsResource) {
String javaFilePath = getJavaFilePathToPackageResource(resourceName,
classInSamePackageAsResource);
javaFilePath = javaFilePath.replace('/', '\\');
return javaFilePath.substring(1);
}
@@ -115,10 +127,11 @@ public class BaseTestCase extends TestCase {
* @param classInSamePackageAsResource
* @return a resource located in the same package as the passed in class
*/
public Object getPackageResource(String resourceName,
@SuppressWarnings( { "unused", "unchecked" })
private Object getPackageResource(String resourceName,
Class classInSamePackageAsResource) {
String fullPathToResource = getJavaFilePathToPackageResource(resourceName,
classInSamePackageAsResource);
String fullPathToResource = getJavaFilePathToPackageResource(
resourceName, classInSamePackageAsResource);
ClassLoader localClassLoader = classInSamePackageAsResource
.getClassLoader();
if (null == localClassLoader) {
@@ -129,16 +142,16 @@ public class BaseTestCase extends TestCase {
}
/**
* load a library from same place in the file system that the class was
* loaded from.
* 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.
* This is an attempt to let unit tests run without having to run regsvr32.
*
* @param libraryName
* @param classInSamePackageAsResource
*/
public void loadLibraryFromClassPackage(String libraryName,
@SuppressWarnings( { "unchecked", "unused" })
private void loadLibraryFromClassPackage(String libraryName,
Class classInSamePackageAsResource) {
String libraryNameWithSuffix = "";
String fullLibraryNameWithPath = "";
@@ -149,12 +162,13 @@ public class BaseTestCase extends TestCase {
} else {
fail("can't create full library name " + libraryName);
}
// generate the path the classloader would use to find this on the classpath
// 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);
// System.loadLibrary(fullLibraryNameWithPath);
}
}

View File

@@ -5,24 +5,30 @@ import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComException;
/**
* This test verifies patch SF 1794811 .
* It shows how unicode filenames throw exceptions in 1.13M4 and earlier.
* This test verifies patch SF 1794811 . It shows how unicode filenames throw
* exceptions in 1.13M4 and earlier.
*
* @author justme84
*
*
*/
public class UnicodeErrorTest extends BaseTestCase {
/**
* verifies that messages can now have unicode in them like when the file
* names have unicode characters
*/
public void testUnicodeCharactersInErrorMessage() {
ActiveXComponent application = new ActiveXComponent("Word.Application");
ActiveXComponent documents = application.getPropertyAsComponent("Documents");
ActiveXComponent documents = application
.getPropertyAsComponent("Documents");
String fileName = "abc\u0411\u0412\u0413\u0414def";
try {
documents.invoke("Open", fileName);
fail("Should have thrown an exception");
} catch (ComException e) {
assertTrue("Error message should contain file name with unicode " +
"characters in it. "+e.getMessage(),
e.getMessage().indexOf(fileName) > 0);
assertTrue("Error message should contain file name with unicode "
+ "characters in it. " + e.getMessage(), e.getMessage()
.indexOf(fileName) > 0);
}
}
}

View File

@@ -2,6 +2,7 @@ package com.jacob.test.events;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComException;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.DispatchEvents;
import com.jacob.com.InvocationProxy;
@@ -10,41 +11,34 @@ import com.jacob.test.BaseTestCase;
/**
* This test was lifted from a forum posting and shows how you can't listen to
* Excel events (added post 1.9.1 Eclipse Settings.) This also uses the 1.9.1
* InvocationProxy to receive the events.
* Excel events (added post 1.9.1 Eclipse Settings.) This also uses the 1.9.1
* InvocationProxy to receive the events. The test was modified in 1.14 to show
* how to hook up multiple event listeners to various Excel components
* <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.
* 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 ExcelEventTest extends BaseTestCase {
/**
* load up excel, register for events and make stuff happen
*
* @param args
*/
public void testExcelWithInvocationProxy() {
String pid = "Excel.Application";
ComThread.InitSTA();
// we are going to listen to events on Application.
// You can probably also listen Excel.Sheet and Excel.Chart
String excelApplicationProgramId = "Excel.Application";
String excelSheetProgramId = "Excel.Sheet";
String typeLibLocation = "C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE";
// Grab The Component.
ActiveXComponent axc = new ActiveXComponent(pid);
try {
// Add a listener (doesn't matter what it is).
DispatchEvents de;
if (typeLibLocation == null) {
de = new DispatchEvents(axc, new ExcelEvents());
} else {
de = new DispatchEvents(axc, new ExcelEvents(), pid,
typeLibLocation);
}
if (de == null) {
System.out
.println("No exception thrown but no dispatch returned for Excel events");
} else {
// Yea!
System.out.println("Successfully attached to " + pid);
ActiveXComponent axc = new ActiveXComponent(excelApplicationProgramId);
hookupListener(axc, excelApplicationProgramId, typeLibLocation);
}
try {
System.out.println("version=" + axc.getProperty("Version"));
System.out.println("version=" + Dispatch.get(axc, "Version"));
@@ -52,6 +46,7 @@ public class ExcelEventTest extends BaseTestCase {
Dispatch workbooks = axc.getPropertyAsComponent("Workbooks");
Dispatch workbook = Dispatch.get(workbooks, "Add").toDispatch();
Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
hookupListener(sheet, excelSheetProgramId, typeLibLocation);
Dispatch a1 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { "A1" }, new int[1]).toDispatch();
Dispatch a2 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
@@ -60,36 +55,83 @@ public class ExcelEventTest extends BaseTestCase {
System.out.println("Inserting calculation 2xA1 into A2");
Dispatch.put(a1, "Value", "123.456");
Dispatch.put(a2, "Formula", "=A1*2");
System.out.println("Retrieved a1 from excel:" + Dispatch.get(a1, "Value"));
System.out.println("Retrieved a2 from excel:" + Dispatch.get(a2, "Value"));
System.out.println("Retrieved a1 from excel:"
+ Dispatch.get(a1, "Value"));
System.out.println("Retrieved a2 from excel:"
+ Dispatch.get(a2, "Value"));
Variant f = new Variant(false);
Dispatch.call(workbook, "Close", f);
axc.invoke("Quit", new Variant[] {});
} catch (ComException cfe) {
cfe.printStackTrace();
fail("Failed to attach to " + pid + ": "
fail("Failed to attach to " + excelApplicationProgramId + ": "
+ cfe.getMessage());
}
try {
// the sleep is required to let everything clear out after the quit
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ComThread.Release();
}
/**
* extracted the listener hookup so we could try multiple listeners.
*
* @param axc
* @param programId
* @param typeLibLocation
*/
private void hookupListener(Dispatch axc, String programId,
String typeLibLocation) {
// Add a listener (doesn't matter what it is).
DispatchEvents applicationEvents;
if (typeLibLocation == null) {
applicationEvents = new DispatchEvents(axc, new ExcelEvents(
programId));
} else {
applicationEvents = new DispatchEvents(axc, new ExcelEvents(
programId), programId, typeLibLocation);
}
if (applicationEvents == null) {
System.out
.println("No exception thrown but no dispatch returned for Excel events");
} else {
// Yea!
System.out.println("Successfully attached to " + programId);
}
}
public class ExcelEvents extends InvocationProxy {
/**
* Constructor so we can create an instance that implements invoke()
* Proxy class to verify we receive expected events
*/
public ExcelEvents() {
}
public class ExcelEvents extends InvocationProxy {
/**
* Override the invoke method to log all the events so that we don't have to
* implement all of the specific events.
*/
public Variant invoke(String methodName, Variant targetParameter[]) {
System.out.println("Received event from Windows program" + methodName);
return null;
}
private String listenerPrefix = "-";
}
/**
* Constructor so we can create an instance that implements invoke()
*
* @param interfaceIdentifier
* a string that identifies which listener is speaking
*/
public ExcelEvents(String interfaceIdentifier) {
listenerPrefix = interfaceIdentifier;
}
/**
* Override the invoke method to log all the events so that we don't
* have to implement all of the specific events.
*/
public Variant invoke(String methodName, Variant targetParameter[]) {
System.out.println("Received event from " + listenerPrefix + ": "
+ methodName);
return null;
}
}
}

View File

@@ -6,212 +6,406 @@ 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 demonstrates the new event handling code in jacob 1.7
* This example will open up IE and print out some of the events
* it listens to as it havigates to web sites.
* contributed by Niels Olof Bouvin mailto:n.o.bouvin@daimi.au.dk
* and Henning Jae jehoej@daimi.au.dk
* This demonstrates the new event handling code in jacob 1.7 This example will
* open up IE and print out some of the events it listens to as it havigates to
* web sites. contributed by Niels Olof Bouvin mailto:n.o.bouvin@daimi.au.dk and
* Henning Jae jehoej@daimi.au.dk
* <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.
* 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 IETest extends BaseTestCase {
/**
* runs the IE test and feeds it commands
*/
public void testRunIE() {
// this line starts the pump but it runs fine without it
ComThread.startMainSTA();
// remove this line and it dies
///ComThread.InitMTA(true);
IETestThread aThread = new IETestThread();
aThread.start();
while (aThread.isAlive()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// doen with the sleep
//e.printStackTrace();
}
}
System.out.println("Main: Thread quit, about to quit main sta in thread "
+Thread.currentThread().getName());
// this line only does someting if startMainSTA() was called
ComThread.quitMainSTA();
System.out.println("Main: did quit main sta in thread "
+Thread.currentThread().getName());
if (aThread.threadFailedWithException != null){
fail("caught an unexpected exception "+aThread.threadFailedWithException);
}
}
// this line starts the pump but it runs fine without it
ComThread.startMainSTA();
// remove this line and it dies
// /ComThread.InitMTA(true);
IETestThread aThread = new IETestThread();
aThread.start();
while (aThread.isAlive()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// doen with the sleep
// e.printStackTrace();
}
}
System.out
.println("Main: Thread quit, about to quit main sta in thread "
+ Thread.currentThread().getName());
// this line only does someting if startMainSTA() was called
ComThread.quitMainSTA();
System.out.println("Main: did quit main sta in thread "
+ Thread.currentThread().getName());
if (aThread.threadFailedWithException != null) {
fail("caught an unexpected exception "
+ aThread.threadFailedWithException);
}
}
}
class IETestThread extends Thread
{
class IETestThread extends Thread {
/** flag that says we got a quit message from IE */
public static boolean quitHandled = false;
/**
* holds any caught exception so the main/test case can see them
*/
public Throwable threadFailedWithException = null;
public IETestThread(){
super();
}
public void run()
{
// this used to be 5 seconds but sourceforge is slow
int delay = 5000; // msec
// paired with statement below that blows up
ComThread.InitMTA();
ActiveXComponent ie = new ActiveXComponent("InternetExplorer.Application");
try {
Dispatch.put(ie, "Visible", new Variant(true));
Dispatch.put(ie, "AddressBar", new Variant(true));
System.out.println("IETestThread: " + Dispatch.get(ie, "Path"));
Dispatch.put(ie, "StatusText", new Variant("My Status Text"));
System.out.println("IETestThread: About to hookup event listener");
IEEvents ieE = new IEEvents();
new DispatchEvents(ie, ieE,"InternetExplorer.Application.1");
System.out.println("IETestThread: Did hookup event listener");
/// why is this here? Was there some other code here in the past?
Variant optional = new Variant();
optional.putNoParam();
System.out.println("IETestThread: About to call navigate to sourceforge");
Dispatch.call(ie, "Navigate", new Variant("http://sourceforge.net/projects/jacob-project"));
System.out.println("IETestThread: Did call navigate to sourceforge");
try { Thread.sleep(delay); } catch (Exception e) {}
System.out.println("IETestThread: About to call navigate to yahoo");
Dispatch.call(ie, "Navigate", new Variant("http://groups.yahoo.com/group/jacob-project"));
System.out.println("IETestThread: Did call navigate to yahoo");
try { Thread.sleep(delay); } catch (Exception e) {}
} catch (Exception e) {
threadFailedWithException = e;
e.printStackTrace();
} catch (Throwable re){
threadFailedWithException = re;
re.printStackTrace();
} finally {
System.out.println("IETestThread: About to send Quit");
ie.invoke("Quit", new Variant[] {});
System.out.println("IETestThread: Did send Quit");
}
// this blows up when it tries to release a DispatchEvents object
// I think this is because there is still one event we should get back
// "OnQuit" that will came after we have released the thread pool
// this is probably messed up because DispatchEvent object will have been
// freed before the callback
// commenting out ie.invoke(quit...) causes this to work without error
// this code tries to wait until the quit has been handled but that doesn't work
System.out.println("IETestThread: Waiting until we've received the quit callback");
while (!quitHandled){
try { Thread.sleep(delay/5);} catch (InterruptedException e) {}
}
System.out.println("IETestThread: Received the quit callback");
// wait a little while for it to end
//try {Thread.sleep(delay); } catch (InterruptedException e) {}
System.out.println("IETestThread: about to call ComThread.Release in thread " +
Thread.currentThread().getName());
ComThread.Release();
}
/**
* constructor for the test thread
*/
public IETestThread() {
super();
}
/**
* The events class must be publicly accessable for reflection to work.
* The list of available events is located at http://msdn2.microsoft.com/en-us/library/aa768280.aspx
*/
public class IEEvents
{
public void BeforeNavigate2(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): BeforeNavigate2 "+args.length);
}
public void run() {
// this used to be 5 seconds but sourceforge is slow
int delay = 5000; // msec
// paired with statement below that blows up
ComThread.InitMTA();
ActiveXComponent ie = new ActiveXComponent(
"InternetExplorer.Application");
try {
Dispatch.put(ie, "Visible", new Variant(true));
Dispatch.put(ie, "AddressBar", new Variant(true));
System.out.println("IETestThread: " + Dispatch.get(ie, "Path"));
Dispatch.put(ie, "StatusText", new Variant("My Status Text"));
public void CommandStateChange(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): CommandStateChange "+args.length);
}
System.out.println("IETestThread: About to hookup event listener");
IEEvents ieE = new IEEvents();
new DispatchEvents(ie, ieE, "InternetExplorer.Application.1");
System.out.println("IETestThread: Did hookup event listener");
// / why is this here? Was there some other code here in the past?
Variant optional = new Variant();
optional.putNoParam();
public void DocumentComplete(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): DocumentComplete "+args.length);
}
System.out
.println("IETestThread: About to call navigate to sourceforge");
Dispatch.call(ie, "Navigate", new Variant(
"http://sourceforge.net/projects/jacob-project"));
System.out
.println("IETestThread: Did call navigate to sourceforge");
try {
Thread.sleep(delay);
} catch (Exception e) {
}
System.out.println("IETestThread: About to call navigate to yahoo");
Dispatch.call(ie, "Navigate", new Variant(
"http://groups.yahoo.com/group/jacob-project"));
System.out.println("IETestThread: Did call navigate to yahoo");
try {
Thread.sleep(delay);
} catch (Exception e) {
}
} catch (Exception e) {
threadFailedWithException = e;
e.printStackTrace();
} catch (Throwable re) {
threadFailedWithException = re;
re.printStackTrace();
} finally {
System.out.println("IETestThread: About to send Quit");
ie.invoke("Quit", new Variant[] {});
System.out.println("IETestThread: Did send Quit");
}
// this blows up when it tries to release a DispatchEvents object
// I think this is because there is still one event we should get back
// "OnQuit" that will came after we have released the thread pool
// this is probably messed up because DispatchEvent object will have
// been
// freed before the callback
// commenting out ie.invoke(quit...) causes this to work without error
// this code tries to wait until the quit has been handled but that
// doesn't work
System.out
.println("IETestThread: Waiting until we've received the quit callback");
while (!quitHandled) {
try {
Thread.sleep(delay / 5);
} catch (InterruptedException e) {
}
}
System.out.println("IETestThread: Received the quit callback");
// wait a little while for it to end
// try {Thread.sleep(delay); } catch (InterruptedException e) {}
System.out
.println("IETestThread: about to call ComThread.Release in thread "
+ Thread.currentThread().getName());
public void DownloadBegin(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): DownloadBegin "+args.length);
}
ComThread.Release();
}
public void DownloadComplete(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): DownloadComplete "+args.length);
}
/**
* The events class must be publicly accessable for reflection to work. The
* list of available events is located at
* http://msdn2.microsoft.com/en-us/library/aa768280.aspx
*/
public class IEEvents {
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void BeforeNavigate2(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): BeforeNavigate2 "
+ args.length);
}
public void NavigateError(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): NavigateError "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void CommandStateChange(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName()
+ "): CommandStateChange " + args.length);
}
public void NavigateComplete2(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): NavigateComplete "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void DocumentComplete(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): DocumentComplete "
+ args.length);
}
public void NewWindow2(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): NewWindow2 "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void DownloadBegin(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): DownloadBegin "
+ args.length);
}
public void OnFullScreen(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): OnFullScreen "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void DownloadComplete(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): DownloadComplete "
+ args.length);
}
public void OnMenuBar(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): OnMenuBar "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void NavigateError(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): NavigateError "
+ args.length);
}
public void OnQuit(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): OnQuit "+args.length);
IETestThread.quitHandled = true;
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void NavigateComplete2(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): NavigateComplete "
+ args.length);
}
public void OnStatusBar(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): OnStatusBar "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void NewWindow2(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): NewWindow2 "
+ args.length);
}
public void OnTheaterMode(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): OnTheaterMode "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void OnFullScreen(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnFullScreen "
+ args.length);
}
public void OnToolBar(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): OnToolBar "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void OnMenuBar(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnMenuBar "
+ args.length);
}
public void OnVisible(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): OnVisible "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void OnQuit(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnQuit "
+ args.length);
IETestThread.quitHandled = true;
}
public void ProgressChange(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): ProgressChange "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void OnStatusBar(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnStatusBar "
+ args.length);
}
public void PropertyChange(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): PropertyChange "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void OnTheaterMode(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnTheaterMode "
+ args.length);
}
public void SetSecureLockIcon(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): setSecureLockIcon "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void OnToolBar(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnToolBar "
+ args.length);
}
public void StatusTextChange(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): StatusTextChange "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void OnVisible(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnVisible "
+ args.length);
}
public void TitleChange(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): TitleChange "+args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void ProgressChange(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): ProgressChange "
+ args.length);
}
public void WindowClosing(Variant[] args) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): WindowClosing "+args.length);
}
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void PropertyChange(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): PropertyChange "
+ args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void SetSecureLockIcon(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName()
+ "): setSecureLockIcon " + args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void StatusTextChange(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): StatusTextChange "
+ args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void TitleChange(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): TitleChange "
+ args.length);
}
/**
* Internet explorer event this proxy can receive
*
* @param args
* the COM Variant objects that this event passes in.
*/
public void WindowClosing(Variant[] args) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): WindowClosing "
+ args.length);
}
}
}

View File

@@ -6,213 +6,284 @@ import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/**
* This test runs fine against jdk 1.4 and 1.5
*
* This demonstrates the new event handling code in jacob 1.7
* This example will open up IE and print out some of the events
* it listens to as it havigates to web sites.
* contributed by Niels Olof Bouvin mailto:n.o.bouvin@daimi.au.dk
* and Henning Jae jehoej@daimi.au.dk
* This demonstrates the new event handling code in jacob 1.7 This example will
* open up IE and print out some of the events it listens to as it havigates to
* web sites. contributed by Niels Olof Bouvin mailto:n.o.bouvin@daimi.au.dk and
* Henning Jae jehoej@daimi.au.dk
* <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.
* 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 IETestActiveXProxy extends BaseTestCase {
public void testIEActiveProxyCallback() {
// this line starts the pump but it runs fine without it
ComThread.startMainSTA();
// remove this line and it dies
///ComThread.InitMTA(true);
IETestActiveProxyThread aThread = new IETestActiveProxyThread();
aThread.start();
while (aThread.isAlive()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// doen with the sleep
//e.printStackTrace();
}
}
System.out.println("Main: Thread quit, about to quit main sta in thread "
+Thread.currentThread().getName());
// this line only does someting if startMainSTA() was called
ComThread.quitMainSTA();
System.out.println("Main: did quit main sta in thread "
+Thread.currentThread().getName());
if (aThread.threadFailedWithException != null){
fail("caught an unexpected exception "+aThread.threadFailedWithException);
}
}
/**
* the main test method that builds up the connection and runs the test
*/
public void testIEActiveProxyCallback() {
// this line starts the pump but it runs fine without it
ComThread.startMainSTA();
// remove this line and it dies
// /ComThread.InitMTA(true);
IETestActiveProxyThread aThread = new IETestActiveProxyThread();
aThread.start();
while (aThread.isAlive()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// doen with the sleep
// e.printStackTrace();
}
}
System.out
.println("Main: Thread quit, about to quit main sta in thread "
+ Thread.currentThread().getName());
// this line only does someting if startMainSTA() was called
ComThread.quitMainSTA();
System.out.println("Main: did quit main sta in thread "
+ Thread.currentThread().getName());
if (aThread.threadFailedWithException != null) {
fail("caught an unexpected exception "
+ aThread.threadFailedWithException);
}
}
}
class IETestActiveProxyThread extends Thread
{
class IETestActiveProxyThread extends Thread {
/** says that the quit message has been received from the target application */
public static boolean quitHandled = false;
/**
* holds any caught exception so the main/test case can see them
*/
public Throwable threadFailedWithException = null;
public IETestActiveProxyThread(){
super();
}
public void run()
{
// this used to be 5 seconds but sourceforge is slow
int delay = 5000; // msec
// paired with statement below that blows up
ComThread.InitMTA();
ActiveXComponent ie = new ActiveXComponent("InternetExplorer.Application");
try {
Dispatch.put(ie, "Visible", new Variant(true));
Dispatch.put(ie, "AddressBar", new Variant(true));
System.out.println("IETestActiveProxyThread: " + Dispatch.get(ie, "Path"));
Dispatch.put(ie, "StatusText", new Variant("My Status Text"));
System.out.println("IETestActiveProxyThread: About to hookup event listener");
IEEventsActiveProxy ieE = new IEEventsActiveProxy();
new ActiveXDispatchEvents(ie, ieE,"InternetExplorer.Application.1");
System.out.println("IETestActiveProxyThread: Did hookup event listener");
/// why is this here? Was there some other code here in the past?
Variant optional = new Variant();
optional.putNoParam();
System.out.println("IETestActiveProxyThread: About to call navigate to sourceforge");
Dispatch.call(ie, "Navigate", new Variant("http://sourceforge.net/projects/jacob-project"));
System.out.println("IETestActiveProxyThread: Did call navigate to sourceforge");
try { Thread.sleep(delay); } catch (Exception e) {}
System.out.println("IETestActiveProxyThread: About to call navigate to yahoo");
Dispatch.call(ie, "Navigate", new Variant("http://groups.yahoo.com/group/jacob-project"));
System.out.println("IETestActiveProxyThread: Did call navigate to yahoo");
try { Thread.sleep(delay); } catch (Exception e) {}
} catch (Exception e) {
threadFailedWithException = e;
e.printStackTrace();
} catch (Throwable re){
threadFailedWithException = re;
re.printStackTrace();
} finally {
System.out.println("IETestActiveProxyThread: About to send Quit");
ie.invoke("Quit", new Variant[] {});
System.out.println("IETestActiveProxyThread: Did send Quit");
}
// this blows up when it tries to release a DispatchEvents object
// I think this is because there is still one event we should get back
// "OnQuit" that will came after we have released the thread pool
// this is probably messed up because DispatchEvent object will have been
// freed before the callback
// commenting out ie.invoke(quit...) causes this to work without error
// this code tries to wait until the quit has been handled but that doesn't work
System.out.println("IETestActiveProxyThread: Waiting until we've received the quit callback");
while (!quitHandled){
try { Thread.sleep(delay/5);} catch (InterruptedException e) {}
}
System.out.println("IETestActiveProxyThread: Received the quit callback");
// wait a little while for it to end
//try {Thread.sleep(delay); } catch (InterruptedException e) {}
System.out.println("IETestActiveProxyThread: about to call ComThread.Release in thread " +
Thread.currentThread().getName());
ComThread.Release();
}
/** the thread's constructor */
public IETestActiveProxyThread() {
super();
}
/**
* The events class must be publicly accessable for reflection to work.
* The list of available events is located at http://msdn2.microsoft.com/en-us/library/aa768280.aspx
*/
public class IEEventsActiveProxy
{
public void BeforeNavigate2(Dispatch pDisp, String url, Integer flags,
String targetFrameName, Variant postData, String headers, Boolean cancel) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): BeforeNavigate2 "+url);
}
public void run() {
// this used to be 5 seconds but sourceforge is slow
int delay = 5000; // msec
// paired with statement below that blows up
ComThread.InitMTA();
ActiveXComponent ie = new ActiveXComponent(
"InternetExplorer.Application");
try {
Dispatch.put(ie, "Visible", new Variant(true));
Dispatch.put(ie, "AddressBar", new Variant(true));
System.out.println("IETestActiveProxyThread: "
+ Dispatch.get(ie, "Path"));
Dispatch.put(ie, "StatusText", new Variant("My Status Text"));
public void CommandStateChange(Integer command, Boolean enable) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): CommandStateChange "+command);
}
System.out
.println("IETestActiveProxyThread: About to hookup event listener");
IEEventsActiveProxy ieE = new IEEventsActiveProxy();
new ActiveXDispatchEvents(ie, ieE, "InternetExplorer.Application.1");
System.out
.println("IETestActiveProxyThread: Did hookup event listener");
// / why is this here? Was there some other code here in the past?
Variant optional = new Variant();
optional.putNoParam();
public void DocumentComplete(Dispatch pDisp, String url) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): DocumentComplete "+url);
}
System.out
.println("IETestActiveProxyThread: About to call navigate to sourceforge");
Dispatch.call(ie, "Navigate", new Variant(
"http://sourceforge.net/projects/jacob-project"));
System.out
.println("IETestActiveProxyThread: Did call navigate to sourceforge");
try {
Thread.sleep(delay);
} catch (Exception e) {
}
System.out
.println("IETestActiveProxyThread: About to call navigate to yahoo");
Dispatch.call(ie, "Navigate", new Variant(
"http://groups.yahoo.com/group/jacob-project"));
System.out
.println("IETestActiveProxyThread: Did call navigate to yahoo");
try {
Thread.sleep(delay);
} catch (Exception e) {
}
} catch (Exception e) {
threadFailedWithException = e;
e.printStackTrace();
} catch (Throwable re) {
threadFailedWithException = re;
re.printStackTrace();
} finally {
System.out.println("IETestActiveProxyThread: About to send Quit");
ie.invoke("Quit", new Variant[] {});
System.out.println("IETestActiveProxyThread: Did send Quit");
}
// this blows up when it tries to release a DispatchEvents object
// I think this is because there is still one event we should get back
// "OnQuit" that will came after we have released the thread pool
// this is probably messed up because DispatchEvent object will have
// been
// freed before the callback
// commenting out ie.invoke(quit...) causes this to work without error
// this code tries to wait until the quit has been handled but that
// doesn't work
System.out
.println("IETestActiveProxyThread: Waiting until we've received the quit callback");
while (!quitHandled) {
try {
Thread.sleep(delay / 5);
} catch (InterruptedException e) {
}
}
System.out
.println("IETestActiveProxyThread: Received the quit callback");
// wait a little while for it to end
// try {Thread.sleep(delay); } catch (InterruptedException e) {}
System.out
.println("IETestActiveProxyThread: about to call ComThread.Release in thread "
+ Thread.currentThread().getName());
public void DownloadBegin() {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): DownloadBegin ");
}
ComThread.Release();
}
public void DownloadComplete() {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): DownloadComplete ");
}
/**
* The events class must be publicly accessable for reflection to work. The
* list of available events is located at
* http://msdn2.microsoft.com/en-us/library/aa768280.aspx
*/
public class IEEventsActiveProxy {
public void NavigateComplete2(Dispatch pDisp, String url) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): NavigateComplete "+url);
}
public void BeforeNavigate2(Dispatch pDisp, String url, Integer flags,
String targetFrameName, Variant postData, String headers,
Boolean cancel) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): BeforeNavigate2 "
+ url);
}
public void NavigateError(Dispatch pDispatch, String url, String targetFrameName, Integer statusCode, Boolean Cancel) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): NavigateError "+statusCode);
}
public void CommandStateChange(Integer command, Boolean enable) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName()
+ "): CommandStateChange " + command);
}
public void NewWindow2(Dispatch pDisp, Boolean cancel) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): NewWindow2 "+pDisp);
}
public void DocumentComplete(Dispatch pDisp, String url) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): DocumentComplete "
+ url);
}
public void OnFullScreen(Boolean fullScreen) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): OnFullScreen "+fullScreen);
}
public void DownloadBegin() {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): DownloadBegin ");
}
public void OnMenuBar(Boolean menuBar) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): OnMenuBar "+menuBar);
}
public void DownloadComplete() {
System.out
.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName()
+ "): DownloadComplete ");
}
public void OnQuit() {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): OnQuit ");
IETestActiveProxyThread.quitHandled = true;
}
public void NavigateComplete2(Dispatch pDisp, String url) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): NavigateComplete "
+ url);
}
public void OnStatusBar(Boolean statusBar) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): OnStatusBar "+statusBar);
}
public void NavigateError(Dispatch pDispatch, String url,
String targetFrameName, Integer statusCode, Boolean Cancel) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): NavigateError "
+ statusCode);
}
public void OnTheaterMode(Boolean theaterMode) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): OnTheaterMode "+theaterMode);
}
public void NewWindow2(Dispatch pDisp, Boolean cancel) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): NewWindow2 "
+ pDisp);
}
public void OnToolBar(Boolean onToolBar) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): OnToolBar "+onToolBar);
}
public void OnFullScreen(Boolean fullScreen) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnFullScreen "
+ fullScreen);
}
public void OnVisible(Boolean onVisible) {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): onVisible "+ onVisible);
}
public void OnMenuBar(Boolean menuBar) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnMenuBar "
+ menuBar);
}
public void ProgressChange() {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): ProgressChange ");
}
public void OnQuit() {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnQuit ");
IETestActiveProxyThread.quitHandled = true;
}
public void PropertyChange() {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): PropertyChange ");
}
public void OnStatusBar(Boolean statusBar) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnStatusBar "
+ statusBar);
}
public void SetSecureLockIcon(Integer secureLockIcon) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): setSecureLockIcon "+secureLockIcon);
}
public void OnTheaterMode(Boolean theaterMode) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnTheaterMode "
+ theaterMode);
}
public void StatusTextChange() {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): StatusTextChange ");
}
public void OnToolBar(Boolean onToolBar) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnToolBar "
+ onToolBar);
}
public void TitleChange() {
System.out.println("IEEventsActiveProxy Received ("+Thread.currentThread().getName()+"): TitleChange ");
}
public void OnVisible(Boolean onVisible) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): onVisible "
+ onVisible);
}
public void WindowClosing(Boolean isChildWindow) {
System.out.println("IEEvents Received ("+Thread.currentThread().getName()+"): WindowClosing "+isChildWindow);
}
}
public void ProgressChange() {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): ProgressChange ");
}
public void PropertyChange() {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): PropertyChange ");
}
public void SetSecureLockIcon(Integer secureLockIcon) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName()
+ "): setSecureLockIcon " + secureLockIcon);
}
public void StatusTextChange() {
System.out
.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName()
+ "): StatusTextChange ");
}
public void TitleChange() {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): TitleChange ");
}
public void WindowClosing(Boolean isChildWindow) {
System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): WindowClosing "
+ isChildWindow);
}
}
}

View File

@@ -9,19 +9,20 @@ import com.jacob.test.BaseTestCase;
/**
* This test was lifted from a forum posting and shows how you can't listen to
* Excel events (added post 1.9.1 Eclipse Settings.)
* That test was modified make this a MSWord event listener to demonstrate
* that the InvocationProxy code works with MS Word Events
* This also uses the 1.10
* InvocationProxy to receive the events.
* Excel events (added post 1.9.1 Eclipse Settings.) That test was modified make
* this a MSWord event listener to demonstrate that the InvocationProxy code
* works with MS Word Events This also uses the 1.10 InvocationProxy to receive
* the events.
* <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.
* 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 WordEventTest extends BaseTestCase {
/**
* load up word, register for events and make stuff happen
*
* @param args
*/
public void testCaptureWordEvents() {
@@ -49,38 +50,44 @@ public class WordEventTest extends BaseTestCase {
// this is different from the ExcelEventTest because it uses
// the jacob active X api instead of the Dispatch api
System.out.println("version=" + axc.getPropertyAsString("Version"));
axc.setProperty("Visible",true);
ActiveXComponent documents = axc.getPropertyAsComponent("Documents");
if (documents == null){
axc.setProperty("Visible", true);
ActiveXComponent documents = axc
.getPropertyAsComponent("Documents");
if (documents == null) {
fail("unable to get documents");
}
axc.invoke("Quit", new Variant[] {});
} catch (ComException cfe) {
cfe.printStackTrace();
fail("Failed to attach to " + pid + ": " + cfe.getMessage());
fail("Failed to attach to " + pid + ": " + cfe.getMessage());
}
System.out.println(
"Someone needs to add some MSWord commands to this to " +
"make some on screen stuff happens so the tester " +
"thinks we tested something");
}
public class WordEvents extends InvocationProxy {
/**
* Constructor so we can create an instance that implements invoke()
*/
public WordEvents() {
System.out
.println("Someone needs to add some MSWord commands to this to "
+ "make some on screen stuff happens so the tester "
+ "thinks we tested something");
}
/**
* override the invoke() method to log all the events without writing a bunch of code
* a class that receives messages from word
*/
public Variant invoke(String methodName, Variant targetParameter[]) {
System.out.println("Received event from Windows program" + methodName);
return null;
}
public class WordEvents extends InvocationProxy {
/**
* Constructor so we can create an instance that implements invoke()
*/
public WordEvents() {
}
}
/**
* override the invoke() method to log all the events without writing a
* bunch of code
*/
public Variant invoke(String methodName, Variant targetParameter[]) {
System.out.println("Received event from Windows program"
+ methodName);
return null;
}
}
}

View File

@@ -0,0 +1,236 @@
package com.jacob.test.excel;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/**
* this test verifies that you can call toString() on a Variant extracted from
* Excel that contains a 2 dimensional array of doubles. 1.14M5 and earlier blew
* up on this because two objects pointed at the same windows memory space SF 1840487
*/
public class ControllerTest extends BaseTestCase {
private Controller controller;
protected void setUp() {
controller = new Controller();
}
public void testGetColumnA() {
List<String> list = controller.getColumnA(super
.getWindowsFilePathToPackageResource("teste.xls", this
.getClass()));
assertEquals(50, list.size());
}
public void testGetColumnB() {
List<String> list = controller.getColumnB(super
.getWindowsFilePathToPackageResource("teste.xls", this
.getClass()));
assertEquals(40, list.size());
}
/**
* This class looks bad because it is a compressed version that was
* originally in 3 different files as part of a bug submission. I didn't
* want to simplify it because it might no longer demonstrate the problem we
* were trying to fix
*/
public class Controller {
private List<String> columnA;
private List<String> columnB;
public List<String> getColumnA(String pathToTest) {
load(pathToTest);
return columnA;
}
public List<String> getColumnB(String pathToTest) {
load(pathToTest);
return columnB;
}
public void load(String pathToTest) {
if (columnA == null || columnB == null) {
File excelFile = new File(pathToTest);
executaExcelCallBack(excelFile.getAbsolutePath(), "password");
}
}
public void executaExcelCallBack(String path, String password) {
// ComThread.InitSTA();
ComThread.InitMTA();
ActiveXComponent excel = new ActiveXComponent("Excel.Application");
try {
excel.setProperty("Visible", false);
Dispatch workbooks = excel.getProperty("Workbooks")
.toDispatch();
Dispatch workbook = Dispatch.call(workbooks, "Open", path, // FileName
3, // UpdateLinks
false, // Readonly
5, // Format
password // Password
).toDispatch();
Dispatch sheets = Dispatch.call(workbook, "Worksheets")
.toDispatch();
System.out.println("Before executa");
executa(excel, sheets);
System.out.println("After executa");
Dispatch.call(workbook, "Close", new Variant(false));
Dispatch.call(workbooks, "Close");
System.out.println("After Close");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Before Quit");
excel.invoke("Quit", new Variant[] {});
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("After Quit, Before Release()");
ComThread.Release();
System.out.println("After Release()");
}
}
/**
* Constante para configurar a planilha em modo "Calculation" autom<6F>tico
*/
public static final int CALC_AUTOMATICO = -4105;
/**
* Constante para configurar a planilha em modo "Calculation" manual
*/
public static final int CALC_MANUAL = -4135;
/**
* Escreve um determinado valor em uma c<>lula da pasta em quest<73>o. O
* valor <20> escrito configurando a propriedade Value da c<>lula
*
* @param celula -
* c<>lula para escrever novo valor
* @param sheet -
* pasta da planilha em quest<73>o
* @param valor -
* valor a ser escrito na celula
*/
public void informarValorCelula(String celula, Dispatch sheet,
String valor) {
System.out.println("Entered informarValorCelula");
Dispatch cel = obterCelula(celula, sheet);
Dispatch.put(cel, "Value", valor);
System.out.println("Exiting informarValorCelula");
}
/**
* Obtem o valor de contido em uma c<>lula. O valor representa o conte<74>do
* da propriedade Value da c<>lula
*
* @param celula -
* c<>lula a ser lida
* @param sheet -
* pasta da planilha que cont<6E>m a c<>lula
* @return - conte<74>do da propriedade Value
*/
public Variant obterValorCelula(String celula, Dispatch sheet) {
System.out.println("Entered obterValorCelula");
Dispatch d = obterCelula(celula, sheet);
Variant returnedValue = Dispatch.get(d, "Value");
System.out.println("Exiting obterValorCelula");
return returnedValue;
}
/**
* Obtem refer<65>ncia para a c<>lua ou conjunto de c<>lulas especificado no
* parametro
*
* @param celula -
* Refer<65>ncia para c<>lula ou conjunto de c<>lulas. A String
* "A1" referencia a coluna A e linha 1. A Sting "A1:A10"
* referencia as c<>lulas compreendidas no intervalo entre a
* c<>lua A1 e a c<>lula A10
* @param sheet -
* pasta da planilha qye cont<6E>m as c<>lulas
* @return - referencia para um c<>lula ou conjunto de c<>lulas,
* dependendo do par<61>metro passado
*/
public Dispatch obterCelula(String celula, Dispatch sheet) {
System.out.println("Entered obterCelula");
Dispatch d = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { celula }, new int[1]).toDispatch();
System.out.println("Exiting obterCelula");
return d;
}
/**
* Obtem os valores de um conjunto de c<>lulas
*
* @param celulas -
* Refer<65>ncia para conjunto de c<>lulas
* @param sheet -
* Pasta que cont<6E>m as c<>lulas referenciadas
* @return - Lista onde cada elemento <20> o valor de uma c<>lula
* referenciada na conjunto
*/
public List<String> obterValoresRange(String celulas, Dispatch sheet) {
List<String> valores = new LinkedList<String>();
// obtem valor das celulas como um Variant
Variant var = obterValorCelula(celulas, sheet);
// toString da Variant <20> interpretado por um StringTokenizer e os
// tokens
// inseridos na lista de retorno
String arrayAsString = null;
System.out
.println("Calling toString() on the Variant that is an array will blow up "
+ var.getvt() + " --> " + arrayAsString);
arrayAsString = var.toString();
StringTokenizer st = new StringTokenizer(arrayAsString, "\n");
while (st.hasMoreTokens()) {
valores.add(st.nextToken().trim());
}
return valores;
}
/**
* M<>todo para execu<63><75>o de a<><61>o a ser executada em planilha excel.
*
* @param xl -
* Referencia para aplica<63><61>o excel
* @param sheets -
* Referencia para conjunto de pastas da planilha
*/
public void executa(ActiveXComponent xl, Dispatch sheets) {
System.out.println("Entered private ExcellCallBack executa()");
Dispatch sheet = Dispatch.call(sheets, "Item", "Plan1")
.toDispatch();
columnA = obterValoresRange("A1:A50", sheet);
columnB = obterValoresRange("B1:B40", sheet);
System.out.println("Exiting private ExcellCallBack executa()");
}
}
}

Binary file not shown.

View File

@@ -1,13 +1,13 @@
package com.jacob.test.powerpoint;
/**
* $Id$
*
* This is really more of a multi threaded tester
* <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.
*/
/**
* $Id$
*
* This is really more of a multi threaded tester
* <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.
*/
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.ComThread;
@@ -17,117 +17,136 @@ import com.jacob.test.BaseTestCase;
/**
*
* power point test program posted to sourceforge to demonstrate memory problem.
* 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 am comitting this to the tree just in case we need to come back to it.
* 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 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.
* 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 BaseTestCase {
public class PowerpointTest extends BaseTestCase {
private static final int NUM_THREADS = 5;
protected static final int NUM_ITERATIONS = 50;
protected static final int NUM_ITERATIONS = 50;
/**
* main program that lets us run this as a test
* @param args
*/
public void testPowerpoint() {
ComThread.InitMTA();
ActiveXComponent component = new ActiveXComponent("Powerpoint.Application");
Dispatch comPowerpoint = component.getObject();
try {
PowerpointTestThread[] threads = new PowerpointTestThread[NUM_THREADS];
for (int i=0; i<NUM_THREADS; i++) {
threads[i] = new PowerpointTestThread(i+1, comPowerpoint);
threads[i].start();
}
boolean allThreadsFinished = false;
while (!allThreadsFinished) {
allThreadsFinished = true;
for (int i=0; i<NUM_THREADS; i++) {
if (threads[i].isAlive()) {
allThreadsFinished = false;
break;
}
}
if (!allThreadsFinished) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// no op
}
}
}
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 {
ComThread.Release();
}
}
public class PowerpointTestThread extends Thread {
/**
* holds any caught exception so the main/test case can see them
* main program that lets us run this as a test
*
* @param args
*/
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();
}
}
}
public void testPowerpoint() {
ComThread.InitMTA();
ActiveXComponent component = new ActiveXComponent(
"Powerpoint.Application");
Dispatch comPowerpoint = component.getObject();
try {
PowerpointTestThread[] threads = new PowerpointTestThread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new PowerpointTestThread(i + 1, comPowerpoint);
threads[i].start();
}
boolean allThreadsFinished = false;
while (!allThreadsFinished) {
allThreadsFinished = true;
for (int i = 0; i < NUM_THREADS; i++) {
if (threads[i].isAlive()) {
allThreadsFinished = false;
break;
}
}
if (!allThreadsFinished) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// no op
}
}
}
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 {
ComThread.Release();
}
}
/**
* the thread class that runs power point
*/
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;
/**
* thread constructor
*
* @param threadID
* @param 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

@@ -6,67 +6,195 @@ import com.jacob.test.BaseTestCase;
/**
* SafeArrayTest Program
*
* This is more of an exerciser. It doesn't verify that it gets back
* what it expects like a junit test would
*
* This is more of an exerciser. It doesn't verify that it gets back 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.
*
* 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 SafeArrayBasicTest extends BaseTestCase {
public void testBasicSafeArray(){
//System.runFinalizersOnExit(true);
SafeArray sa = new SafeArray(Variant.VariantVariant, 3);
sa.fromShortArray(new short[] { 1, 2, 3 });
System.out.println("sa short=" + sa);
int[] ai = sa.toIntArray();
for (int i = 0; i < ai.length; i++) {
System.out.println("toInt=" + ai[i]);
/**
*
*/
public void testShortSafeArray() {
short sourceData[] = new short[] { 1, 2, 3 };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromShortArray(sourceData);
short[] extractedFromSafeArray = saUnderTest.toShortArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
}
double[] ad = sa.toDoubleArray();
for (int i = 0; i < ad.length; i++) {
System.out.println("toDouble=" + ad[i]);
assertEquals("single get failed: ", sourceData[2], saUnderTest
.getShort(2));
// test conversion
int[] extractedFromSafeArrayInt = saUnderTest.toIntArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArrayInt[i]);
}
sa.fromIntArray(new int[] { 100000, 200000, 300000 });
System.out.println("sa int=" + sa);
ai = sa.toIntArray();
for (int i = 0; i < ai.length; i++) {
System.out.println("toInt=" + ai[i]);
// test conversion
double[] extractedFromSafeArrayDouble = saUnderTest.toDoubleArray();
for (int i = 0; i < extractedFromSafeArrayDouble.length; i++) {
assertEquals("" + i, new Double(sourceData[i]).doubleValue(),
extractedFromSafeArrayDouble[i]);
}
ad = sa.toDoubleArray();
for (int i = 0; i < ad.length; i++) {
System.out.println("toDouble=" + ad[i]);
// test conversion
Variant extractedFromSafeArrayVariant[] = saUnderTest.toVariantArray();
for (int i = 0; i < extractedFromSafeArrayVariant.length; i++) {
assertEquals("" + i, sourceData[i],
extractedFromSafeArrayVariant[i].getShort());
}
Variant av[] = sa.toVariantArray();
for (int i = 0; i < av.length; i++) {
System.out.println("toVariant=" + av[i]);
}
/**
*
*/
public void testIntSafeArray() {
int sourceData[] = new int[] { 100000, 200000, 300000 };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromIntArray(sourceData);
int[] extractedFromSafeArray = saUnderTest.toIntArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
}
sa.fromDoubleArray(new double[] { 1.5, 2.5, 3.5 });
System.out.println("sa double=" + sa);
sa.fromFloatArray(new float[] { 1.5F, 2.5F, 3.5F });
System.out.println("sa float=" + sa);
sa.fromBooleanArray(new boolean[] { true, false, true, false });
System.out.println("sa bool=" + sa);
av = sa.toVariantArray();
for (int i = 0; i < av.length; i++) {
System.out.println("toVariant=" + av[i]);
}
sa.fromCharArray(new char[] { 'a', 'b', 'c', 'd' });
System.out.println("sa char=" + sa);
sa.fromStringArray(new String[] { "hello", "from", "java", "com" });
System.out.println("sa string=" + sa);
av = sa.toVariantArray();
for (int i = 0; i < av.length; i++) {
System.out.println("toVariant=" + av[i]);
}
sa.fromVariantArray(new Variant[] {
new Variant(1), new Variant(2.3), new Variant("hi") });
System.out.println("sa variant=" + sa);
assertEquals("single get failed: ", sourceData[2], saUnderTest
.getInt(2));
}
/**
*
*/
public void testLongSafeArray() {
long sourceData[] = new long[] { 2L << 40, 3L << 41, 4L << 42 };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromLongArray(sourceData);
long[] extractedFromSafeArray = saUnderTest.toLongArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
}
assertEquals("single get failed: ", sourceData[2], saUnderTest
.getLong(2));
}
/**
*
*/
public void testDoubleSafeArray() {
double sourceData[] = new double[] { 1.5, 2.5, 3.5 };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromDoubleArray(sourceData);
double[] extractedFromSafeArray = saUnderTest.toDoubleArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
}
assertEquals("single get failed: ", sourceData[2], saUnderTest
.getDouble(2));
}
/**
*
*/
public void testFloatSafeArray() {
float sourceData[] = new float[] { 1.5F, 2.5F, 3.5F };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromFloatArray(sourceData);
float[] extractedFromSafeArray = saUnderTest.toFloatArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
}
}
/**
*
*/
public void testBooleanSafeArray() {
boolean sourceData[] = new boolean[] { true, false, true, false };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromBooleanArray(sourceData);
boolean[] extractedFromSafeArray = saUnderTest.toBooleanArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
}
assertEquals("single get failed: ", sourceData[2], saUnderTest
.getBoolean(2));
// test conversion
Variant extractedFromSafeArrayVariant[] = saUnderTest.toVariantArray();
for (int i = 0; i < extractedFromSafeArrayVariant.length; i++) {
assertEquals("" + i, sourceData[i],
extractedFromSafeArrayVariant[i].getBoolean());
}
}
/**
*
*/
public void testCharSafeArray() {
char sourceData[] = new char[] { 'a', 'b', 'c', 'd' };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromCharArray(sourceData);
char[] extractedFromSafeArray = saUnderTest.toCharArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
}
assertEquals("single get failed: ", sourceData[2], saUnderTest
.getChar(2));
}
/**
*
*/
public void testStringSaveArray() {
String sourceData[] = new String[] { "hello", "from", "java", "com" };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromStringArray(sourceData);
String[] extractedFromSafeArray = saUnderTest.toStringArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
}
assertEquals("single get failed: ", sourceData[2], saUnderTest
.getString(2));
// test conversion
Variant extractedFromSafeArrayVariant[] = saUnderTest.toVariantArray();
for (int i = 0; i < extractedFromSafeArrayVariant.length; i++) {
assertEquals("" + i, sourceData[i],
extractedFromSafeArrayVariant[i].getString());
}
}
/**
*
*/
public void testVariantSafeArray() {
Variant sourceData[] = new Variant[] { new Variant(1),
new Variant(2.3), new Variant("hi") };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromVariantArray(sourceData);
Variant[] extractedFromSafeArray = saUnderTest.toVariantArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i].toString(),
extractedFromSafeArray[i].toString());
}
assertEquals("single get failed: ", sourceData[2].toString(),
saUnderTest.getVariant(2).toString());
}
/**
* test method that verifies setting of bounds in multi-dimensional arrays
*/
public void testSafeArrayNumDimensions() {
int[] lowerBounds = new int[] { 0, 0, 0 };
int[] dimensionSizes = new int[] { 3, 3, 3 };
@@ -75,13 +203,29 @@ public class SafeArrayBasicTest extends BaseTestCase {
dimensionSizes);
System.out.println("Num Dimensions = " + sa3x3.getNumDim());
for (int i = 1; i <= sa3x3.getNumDim(); i++) {
System.out.println("Dimension number = " + i);
System.out.println("Lower bound = " + sa3x3.getLBound(i));
System.out.println("Upper bound = " + sa3x3.getUBound(i));
for (int safeArrayDimension = 1; safeArrayDimension <= sa3x3
.getNumDim(); safeArrayDimension++) {
int configArrayIndex = safeArrayDimension - 1;
assertEquals("unexpected lower bound value ",
lowerBounds[configArrayIndex], sa3x3
.getLBound(safeArrayDimension));
assertEquals("unexpeced upper bound value ",
(dimensionSizes[configArrayIndex] - 1)
+ lowerBounds[configArrayIndex], sa3x3
.getUBound(safeArrayDimension));
}
}
int fill = 0;
/**
* test the set and get method on multi-dimensional arrays
*/
public void testSafeArrayMultiDimension() {
int[] lowerBounds = new int[] { 0, 0, 0 };
int[] dimensionSizes = new int[] { 3, 3, 3 };
SafeArray sa3x3 = new SafeArray(Variant.VariantVariant, lowerBounds,
dimensionSizes);
int[] indices = new int[] { 0, 0, 0 };
for (int i = 0; i < 3; i++) {
@@ -90,10 +234,17 @@ public class SafeArrayBasicTest extends BaseTestCase {
indices[1] = j;
for (int k = 0; k < 3; k++) {
indices[2] = k;
int fill = 0;
fill = i * 100 + j * 10 + k;
sa3x3.setInt(indices, fill);
System.out.println("sa[" + i + "][" + j + "][" + k + "] = "
+ sa3x3.getInt(indices));
assertEquals(fill, sa3x3.getInt(indices));
long fillLong = 0L;
// Pick a number bigger than 2^31
fillLong = 100000000000000L * fill;
sa3x3.setLong(indices, fillLong);
assertEquals(fillLong, sa3x3.getLong(indices));
}
}
}

View File

@@ -267,7 +267,7 @@ public class SafeArrayContents extends BaseTestCase {
fail("Failed to catch expected exception");
} catch (ComFailException cfe) {
// do nothing
//cfe.printStackTrace();
// cfe.printStackTrace();
}
}
}

View File

@@ -7,6 +7,9 @@ import com.jacob.com.SafeArray;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/**
* Test class to verify dispatch with SafeArray
*/
public class SafeArrayDispatchTest extends BaseTestCase {
public void testDispatchWithSafeArray() {
try {
@@ -36,7 +39,7 @@ public class SafeArrayDispatchTest extends BaseTestCase {
assertTrue(result.toString().equals("6"));
} catch (ComException e) {
e.printStackTrace();
fail("script failure "+e);
fail("script failure " + e);
}
}
}

View File

@@ -3,191 +3,175 @@ package com.jacob.test.safearray;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.JacobObject;
import com.jacob.com.JacobReleaseInfo;
import com.jacob.com.SafeArray;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/**
* This test program demonstrates a weak in the setString(int[],String) method in SafeArray.
* To see the leak:
* This test program demonstrates a weak in the setString(int[],String) method
* in SafeArray. To see the leak:
* <ul>
* <li>Bring up the windows task manager and click on the performance tab.
* <li>Run the test program
* </ul>
* You should see the Page File Usage History graph rise at te end of every cycle.
* Running the same program with setString(r,c,String) does not show the same symptoms
* You should see the Page File Usage History graph rise at te end of every
* cycle. Running the same program with setString(r,c,String) does not show the
* same symptoms
*/
public class SafeArrayLeak extends BaseTestCase {
public class SafeArrayLeak extends BaseTestCase {
/**
/**
* ----------------------------------------------------------------------------------------------------------------------------
*
* ----------------------------------------------------------------------------------------------------------------------------
*/
public void testLeakWithSetString() {
ActiveXComponent xl = null;
Dispatch workbooks = null;
Dispatch workbook = null;
Dispatch workSheets = null;
Dispatch sheet = null;
Dispatch tabCells = null;
SafeArray sa = null;
//-Dcom.jacob.autogc=true
System.out.println("Jacob version: "+JacobObject.getBuildVersion());
for(int t = 0; t < 10; t++) {
// look at a large range of cells
ActiveXComponent xl = null;
Dispatch workbooks = null;
Dispatch workbook = null;
Dispatch workSheets = null;
Dispatch sheet = null;
Dispatch tabCells = null;
SafeArray sa = null;
// -Dcom.jacob.autogc=true
System.out.println("Jacob version: " + JacobReleaseInfo.getBuildVersion());
for (int t = 0; t < 10; t++) {
// look at a large range of cells
String position = "A7:DM8934";
try {
xl = new ActiveXComponent("Excel.Application");
System.out.println("Excel version=" + xl.getProperty("Version"));
try {
xl = new ActiveXComponent("Excel.Application");
System.out
.println("Excel version=" + xl.getProperty("Version"));
xl.setProperty("Visible", new Variant(false));
workbooks = xl.getProperty("Workbooks").toDispatch();
workbook = Dispatch.get(workbooks,"Add").toDispatch();
workbook = Dispatch.get(workbooks, "Add").toDispatch();
workSheets = Dispatch.get(workbook, "Worksheets").toDispatch();
sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
// grab the whole range specified above.
tabCells = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { position },
new int[1]).toDispatch();
tabCells = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { position }, new int[1]).toDispatch();
sa = Dispatch.get(tabCells, "Value").toSafeArray(true);
System.out.println("Ub0=" + sa.getUBound(1)); // nbCol
System.out.println("Ub1=" + sa.getUBound(2)); // nbLgn
// number of rows
int nbLgn = sa.getUBound(2);
// number of columns
int nbCol = sa.getUBound(1);
int[] colLgn = new int[] { 0, 0 };
// now set a value on every cell in the range we retrieved
for(int i = 1; i <= nbLgn; i++) {
for (int i = 1; i <= nbLgn; i++) {
colLgn[1] = i;
for(int j = 1; j <= nbCol; j++) {
for (int j = 1; j <= nbCol; j++) {
colLgn[0] = j;
// this one works with out a leak 1.13-M3
//sa.setString(j, i, "test");
// sa.setString(j, i, "test");
// This one leaks with 1.13-M3 and earlier
sa.setString(colLgn, "test");
}
}
Dispatch.put(tabCells, "Value", sa);
Variant f = new Variant(false);
Dispatch.call(workbook, "Close", f);
System.out.println("Close");
}
catch(Exception e) {
e.printStackTrace();
}
finally {
if (sa != null) {
try {
sa.safeRelease();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
sa = null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sa != null) {
try {
sa.safeRelease();
} catch (Exception e) {
e.printStackTrace();
} finally {
sa = null;
}
}
if (tabCells != null) {
try {
tabCells.safeRelease();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
tabCells = null;
}
}
if (sheet != null) {
try {
sheet.safeRelease();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
sheet = null;
}
}
if (workSheets != null) {
try {
workSheets.safeRelease();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
workSheets = null;
}
try {
tabCells.safeRelease();
} catch (Exception e) {
e.printStackTrace();
} finally {
tabCells = null;
}
}
if (sheet != null) {
try {
sheet.safeRelease();
} catch (Exception e) {
e.printStackTrace();
} finally {
sheet = null;
}
}
if (workSheets != null) {
try {
workSheets.safeRelease();
} catch (Exception e) {
e.printStackTrace();
} finally {
workSheets = null;
}
}
if (workbook != null) {
try {
workbook.safeRelease();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
workbook = null;
}
}
if (workbooks != null) {
try {
workbooks.safeRelease();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
workbooks = null;
}
}
if (xl != null) {
try {
xl.invoke("Quit", new Variant[] {});
}
catch(Exception e) {
e.printStackTrace();
}
try {
xl.safeRelease();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
xl = null;
}
}
ComThread.Release();
}
}
try {
workbook.safeRelease();
} catch (Exception e) {
e.printStackTrace();
} finally {
workbook = null;
}
}
if (workbooks != null) {
try {
workbooks.safeRelease();
} catch (Exception e) {
e.printStackTrace();
} finally {
workbooks = null;
}
}
if (xl != null) {
try {
xl.invoke("Quit", new Variant[] {});
} catch (Exception e) {
e.printStackTrace();
}
try {
xl.safeRelease();
} catch (Exception e) {
e.printStackTrace();
} finally {
xl = null;
}
}
ComThread.Release();
}
}
}
}

View File

@@ -7,111 +7,83 @@ import com.jacob.test.BaseTestCase;
/**
* <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>
* SF 1085370
In my understatnding, an instance of SafeArray java
class has a
value of a pointer to VARIANT structure that contains a
pointer to
a SAFEARRAY strucuture.
On the other hand, we can create a Variant object from
the
SafeArray object like this:
SafeArray sa = ...;
Variant val = new Variant(sa);
the val object has a pointer to another VARIANT
structure that
contains a pointer to the same SAFEARRAY structure.
In this case, the val object has a pointer to another
VARIANT that
contains a pointer to the same SAFEARRAY like this:
+-----------+
|SafeArray | +------------+
| m_pV--->VARIANT(a) |
+-----------+ | VT_ARRAY| +---------+
| parray---->SAFEARRAY|
+------------+ +^--------+
|
+-----------+ |
|Variant | +------------+ |
| m_pVariant--->VARIANT(b) | |
+-----------+ | VT_ARRAY| |
| parray-----+
+------------+
When previous objects are rereased by
ComThread.Release(),
first the VARIANT(a) is released by VariantClear()
function,
and second the VARIANT(b) is released by VariantClear()
function too.
But the SAFEARRAY was already released by the
VARIANT(a).
So, in my enviroment (WinXP + J2SDK 1.4.1) the
following java program
is sometimes crash with EXCEPTION_ACCESS_VIOLATION.
To solve this problem, it is nessesary to copy the
SAFEARRAY like this:
+-----------+
|Variant | +------------+
| m_pVariant--->VARIANT(a) |
+-----------+ | VT_ARRAY| +---------+
| parray---->SAFEARRAY|
+------------+ +|--------+
|
+-----------+ | copySA()
|SafeArray | +------------+ |
| m_pV--->VARIANT(b) | V
+-----------+ | VT_ARRAY| +---------+
| parray---->SAFEARRAY|
+------------+ +---------+
*
* 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>
* 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.
* SF 1085370 In my understatnding, an instance of SafeArray java class has a
* value of a pointer to VARIANT structure that contains a pointer to a
* SAFEARRAY strucuture.
*
* On the other hand, we can create a Variant object from the SafeArray object
* like this: SafeArray sa = ...; Variant val = new Variant(sa); the val object
* has a pointer to another VARIANT structure that contains a pointer to the
* same SAFEARRAY structure.
*
* In this case, the val object has a pointer to another VARIANT that contains a
* pointer to the same SAFEARRAY like this:
*
* +-----------+ |SafeArray | +------------+ | m_pV--->VARIANT(a) |
* +-----------+ | VT_ARRAY| +---------+ | parray---->SAFEARRAY| +------------+
* +^--------+ | +-----------+ | |Variant | +------------+ | |
* m_pVariant--->VARIANT(b) | | +-----------+ | VT_ARRAY| | | parray-----+
* +------------+
*
* When previous objects are rereased by ComThread.Release(), first the
* VARIANT(a) is released by VariantClear() function, and second the VARIANT(b)
* is released by VariantClear() function too. But the SAFEARRAY was already
* released by the VARIANT(a).
*
* So, in my enviroment (WinXP + J2SDK 1.4.1) the following java program is
* sometimes crash with EXCEPTION_ACCESS_VIOLATION.
*
*
* To solve this problem, it is nessesary to copy the SAFEARRAY like this:
*
* +-----------+ |Variant | +------------+ | m_pVariant--->VARIANT(a) |
* +-----------+ | VT_ARRAY| +---------+ | parray---->SAFEARRAY| +------------+
* +|--------+ | +-----------+ | copySA() |SafeArray | +------------+ | |
* m_pV--->VARIANT(b) | V +-----------+ | VT_ARRAY| +---------+ |
* 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 extends BaseTestCase {
final static int MAX = 300;
public void testSaveArrayRelease() {
int count;
System.out.println("Starting test for max = "+MAX);
for(count = 1; count<MAX; count++)
{
int i = 0;
try
{
ComThread.InitMTA();
for (i = 0; i < count; i++)
{
SafeArray a1 = new SafeArray(Variant.VariantVariant, 2);
a1.setVariant(0, new Variant("foo"));
a1.setVariant(1, new Variant("bar"));
Variant v = new Variant(a1);
SafeArray a2 = v.toSafeArray(true);
if (a2 == null){
System.out.println("got null back from toSafeArray()");
}
}
ComThread.Release();
System.gc();
//System.out.print(".");
}
catch (Exception e)
{
fail("Test fails with i = " + i + " (max = "+MAX+")");
}
}
System.gc();
System.out.println("\nTest ends with count = " + count + " (max = "+MAX+")");
}
final static int MAX = 300;
/**
* verifies the release works on SafeArray
*/
public void testSaveArrayRelease() {
int count;
System.out.println("Starting test for max = " + MAX);
for (count = 1; count < MAX; count++) {
int i = 0;
try {
ComThread.InitMTA();
for (i = 0; i < count; i++) {
SafeArray a1 = new SafeArray(Variant.VariantVariant, 2);
a1.setVariant(0, new Variant("foo"));
a1.setVariant(1, new Variant("bar"));
Variant v = new Variant(a1);
SafeArray a2 = v.toSafeArray(true);
if (a2 == null) {
System.out.println("got null back from toSafeArray()");
}
}
ComThread.Release();
System.gc();
// System.out.print(".");
} catch (Exception e) {
fail("Test fails with i = " + i + " (max = " + MAX + ")");
}
}
System.gc();
System.out.println("\nTest ends with count = " + count + " (max = "
+ MAX + ")");
}
}

View File

@@ -1,21 +1,26 @@
package com.jacob.test.safearray;
import com.jacob.com.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.SafeArray;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
import com.jacob.activeX.*;
/**
* This does simple tests with SafeArray using Excel as a source
* <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.
* 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 {
/**
* verify safe arrays work with standard applications, Excel in this case
*/
public void testSafeArrayViaExcel() {
// deprecated
// System.runFinalizersOnExit(true);
ActiveXComponent xl = new ActiveXComponent("Excel.Application");
try {
@@ -26,8 +31,9 @@ public class SafeArrayViaExcel extends BaseTestCase {
Dispatch workbook = Dispatch.call(
workbooks,
"Open",
getWindowsFilePathToPackageResource("SafeArrayViaExcel.xls",this.getClass()))
.toDispatch();
getWindowsFilePathToPackageResource(
"SafeArrayViaExcel.xls", this.getClass()))
.toDispatch();
System.out.println("Opened File - SafeArrayViaExcel.xls\n");
Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
cell = Dispatch.invoke(sheet, "Range", Dispatch.Get,
@@ -61,7 +67,7 @@ public class SafeArrayViaExcel extends BaseTestCase {
System.out.println("Closed File\n");
} catch (Exception e) {
e.printStackTrace();
fail("Caught Exception "+e);
fail("Caught Exception " + e);
} finally {
xl.invoke("Quit", new Variant[] {});
}

View File

@@ -1,8 +1,12 @@
package com.jacob.test.vbscript;
import com.jacob.com.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComException;
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;
import com.jacob.activeX.*;
/**
* In this case the component is created and used in the same thread and it's an
@@ -33,7 +37,7 @@ public class ScriptTest extends BaseTestCase {
String scriptCommand = getSampleVPScriptForEval();
String lang = "VBScript";
ActiveXComponent sC = new ActiveXComponent("ScriptControl");
sControl = (Dispatch) sC.getObject();
sControl = sC.getObject();
Dispatch.put(sControl, "Language", lang);
ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sControl, te);

View File

@@ -1,8 +1,14 @@
package com.jacob.test.vbscript;
import com.jacob.com.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComException;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
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;
import com.jacob.activeX.*;
/**
* This example demonstrates how to make calls between two different STA's.
@@ -21,8 +27,9 @@ import com.jacob.activeX.*;
* multiple threads to access a Dispatch pointer, then create that many
* DispatchProxy objects.
* <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.
* 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 ScriptTest2 extends BaseTestCase {
@@ -31,8 +38,8 @@ public class ScriptTest2 extends BaseTestCase {
ComThread.InitSTA();
ScriptTestSTA script = new ScriptTestSTA();
try {
Thread.sleep(1000);
} catch (InterruptedException ie){
Thread.sleep(1000);
} catch (InterruptedException ie) {
// should we get this?
}
@@ -50,7 +57,7 @@ public class ScriptTest2 extends BaseTestCase {
System.out.println("called quit");
} catch (ComException e) {
e.printStackTrace();
fail("caught exception"+e);
fail("caught exception" + e);
} finally {
Integer I = null;
for (int i = 1; i < 1000000; i++) {
@@ -63,11 +70,11 @@ public class ScriptTest2 extends BaseTestCase {
public class ScriptTestSTA extends STA {
public DispatchEvents de = null;
public DispatchEvents de = null;
public Dispatch sControl = null;
public Dispatch sControl = null;
public DispatchProxy sCon = null;
public DispatchProxy sCon = null;
public boolean OnInit() {
try {

View File

@@ -26,8 +26,9 @@ import com.jacob.test.BaseTestCase;
* multiple threads to access a Dispatch pointer, then create that many
* DispatchProxy objects.
* <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.
* 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 ScriptTest2ActiveX extends BaseTestCase {
public static ActiveXComponent sC;
@@ -42,9 +43,9 @@ public class ScriptTest2ActiveX extends BaseTestCase {
ScriptTest2ActiveXSTA script = new ScriptTest2ActiveXSTA();
try {
Thread.sleep(1000);
} catch (InterruptedException ie){
// should we get this?
}
} catch (InterruptedException ie) {
// should we get this?
}
// get a thread-local Dispatch from sCon
ActiveXComponent sc = new ActiveXComponent(sCon.toDispatch());
@@ -60,7 +61,7 @@ public class ScriptTest2ActiveX extends BaseTestCase {
System.out.println("called quit");
} catch (ComException e) {
e.printStackTrace();
fail("blew up with Com Exception "+e);
fail("blew up with Com Exception " + e);
} finally {
Integer I = null;
for (int i = 1; i < 1000000; i++) {

View File

@@ -1,8 +1,12 @@
package com.jacob.test.vbscript;
import com.jacob.com.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComException;
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;
import com.jacob.activeX.*;
/**
* Here we create the ScriptControl component in a separate MTA thread and then
@@ -10,8 +14,9 @@ import com.jacob.activeX.*;
* MTA thread. If you try to create it as an STA then you will not be able to
* make calls into a component running 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.
* 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 ScriptTest3 extends BaseTestCase {
@@ -29,13 +34,15 @@ public class ScriptTest3 extends BaseTestCase {
ScriptTest3Inner script = new ScriptTest3Inner();
script.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ie){
Thread.sleep(1000);
} catch (InterruptedException ie) {
// should we get this?
}
Variant result = Dispatch.call(sControl, "Eval", getSampleVPScriptForEval());
System.out.println("eval(" + getSampleVPScriptForEval() + ") = " + result);
Variant result = Dispatch.call(sControl, "Eval",
getSampleVPScriptForEval());
System.out.println("eval(" + getSampleVPScriptForEval() + ") = "
+ result);
System.out.println("setting quit");
ScriptTest3.quit = true;
} catch (ComException e) {
@@ -54,13 +61,14 @@ public class ScriptTest3 extends BaseTestCase {
System.out.println("OnInit");
String lang = "VBScript";
sC = new ActiveXComponent("ScriptControl");
sControl = (Dispatch) sC.getObject();
sControl = sC.getObject();
Dispatch.put(sControl, "Language", lang);
ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sControl, te);
System.out.println("sControl=" + sControl);
while (!quit)
while (!quit) {
sleep(100);
}
ComThread.Release();
} catch (Exception e) {
e.printStackTrace();

View File

@@ -1,8 +1,11 @@
package com.jacob.test.vbscript;
import com.jacob.com.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComException;
import com.jacob.com.ComThread;
import com.jacob.com.DispatchEvents;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
import com.jacob.activeX.*;
/**
* Here we create the ScriptControl component in a separate MTA thread and then
@@ -33,9 +36,8 @@ public class ScriptTest3ActiveX extends BaseTestCase {
}
Variant result = sC.invoke("Eval", getSampleVPScriptForEval());
System.out
.println("eval(" + getSampleVPScriptForEval()
+ ") = " + result);
System.out.println("eval(" + getSampleVPScriptForEval() + ") = "
+ result);
System.out.println("setting quit");
ScriptTest3ActiveX.quit = true;
} catch (ComException e) {
@@ -58,8 +60,9 @@ public class ScriptTest3ActiveX extends BaseTestCase {
ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sC, te);
System.out.println("sControl=" + sC);
while (!quit)
while (!quit) {
sleep(100);
}
ComThread.Release();
} catch (Exception e) {
e.printStackTrace();

View File

@@ -1,52 +1,53 @@
package com.jacob.test.vbscript;
import com.jacob.com.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComException;
import com.jacob.com.ComThread;
import com.jacob.com.DispatchEvents;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
import com.jacob.activeX.*;
/**
* In this case the component is created and used in the same thread
* and it's an Apartment Threaded component, so we call InitSTA.
* In this case the component is created and used in the same thread 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.
*/
public class ScriptTestActiveX extends BaseTestCase {
public void testActiveXScript() {
public void testActiveXScript() {
ComThread.InitSTA(true);
DispatchEvents de = null;
DispatchEvents de = null;
try {
String lang = "VBScript";
ActiveXComponent sC = new ActiveXComponent("ScriptControl");
sC.setProperty("Language",lang);
ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sC, te);
if (de == null){
System.out.println("null returned when trying to create DispatchEvents");
}
Variant result;
result = sC.invoke("Eval",getSampleVPScriptForEval());
// call it twice to see the objects reused
result = sC.invoke("Eval",getSampleVPScriptForEval());
// call it 3 times to see the objects reused
result = sC.invoke("Eval",getSampleVPScriptForEval());
System.out.println("eval("+getSampleVPScriptForEval()+") = "+ result);
} catch (ComException e) {
e.printStackTrace();
}
finally
{
Integer I = null;
for(int i=1;i<1000000;i++)
{
I = new Integer(i);
}
System.out.println(I);
try {
String lang = "VBScript";
ActiveXComponent sC = new ActiveXComponent("ScriptControl");
sC.setProperty("Language", lang);
ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sC, te);
if (de == null) {
System.out
.println("null returned when trying to create DispatchEvents");
}
Variant result;
result = sC.invoke("Eval", getSampleVPScriptForEval());
// call it twice to see the objects reused
result = sC.invoke("Eval", getSampleVPScriptForEval());
// call it 3 times to see the objects reused
result = sC.invoke("Eval", getSampleVPScriptForEval());
System.out.println("eval(" + getSampleVPScriptForEval() + ") = "
+ result);
} 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();
ComThread.quitMainSTA();
}
}
}
}
}

View File

@@ -4,17 +4,16 @@ import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/**
* Extracted from ScriptTest so everyone can see this
* Made a test solely because it made the ant test easier
* Extracted from ScriptTest so everyone can see this Made a test solely because
* it made the ant test easier
*/
public class ScriptTestErrEvents extends BaseTestCase {
public void Error(Variant[] args)
{
System.out.println("java callback for error!");
}
public void Timeout(Variant[] args)
{
System.out.println("java callback for error!");
}
public void Error(Variant[] args) {
System.out.println("java callback for error!");
}
public void Timeout(Variant[] args) {
System.out.println("java callback for error!");
}
}

View File

@@ -8,7 +8,7 @@ package com.jacob.test.windowsmedia;
* 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.
*/
import com.jacob.activeX.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.test.BaseTestCase;
public class WMPlayer extends BaseTestCase {