Move source files

This commit is contained in:
2014-11-23 17:05:14 +00:00
parent aeca6e8dc2
commit 458d614ee1
96 changed files with 0 additions and 0 deletions

View File

@@ -1,117 +0,0 @@
package com.jacob.com;
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
* <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 ActiveXComponentFactoryTest extends BaseTestCase {
/**
* 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");
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");
} else {
System.out
.println("Correctly could not connect to running MSWord");
}
System.out.println(" Word Starting");
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) {
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[] {});
}
Thread.sleep(2000);
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");
}
} 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);
ComThread.Release();
ComThread.quitMainSTA();
}
}
}

View File

@@ -1,53 +0,0 @@
package com.jacob.com;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
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
*/
public class DateUtilitiesTest extends TestCase {
/**
* 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

@@ -1,37 +0,0 @@
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
* <p>
* May need to run with some command line options (including from inside
* Eclipse). Look in the docs area at the Jacob usage document for command line
* options.
*/
public class DispatchNullProgramId extends BaseTestCase {
/**
* 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");
}
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");
}
}
}

View File

@@ -1,33 +0,0 @@
package com.jacob.com;
import com.jacob.activeX.ActiveXComponent;
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.
*/
public class DispatchTest extends BaseTestCase {
/**
* Verify this detects word's exit
*/
public void testDispatchHasExited() {
String pid = "Word.Application";
ActiveXComponent axc = new ActiveXComponent(pid);
assertEquals(0, Dispatch.hasExited(axc));
axc.invoke("Quit", new Variant[] {});
// should take some amount of time for Word to Quit so should = !exited
assertEquals(0, Dispatch.hasExited(axc));
try {
// sleep some reasonable amount of time waiting for it to quit
Thread.sleep(2000);
} catch (InterruptedException e) {
fail("should not have been interrupted");
}
assertEquals(1, Dispatch.hasExited(axc));
}
}

View File

@@ -1,41 +0,0 @@
package com.jacob.com;
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.
*/
public class DispatchValidDispatchTest extends BaseTestCase {
/**
* 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

@@ -1,120 +0,0 @@
package com.jacob.com;
import com.jacob.test.BaseTestCase;
/**
* Sourceforge defect report 1986987 July 2008. This test case demonstrated a
* deadlock issue.
* <UL>
* <LI>One thread attempts to create an object in a thread where InitMTA has
* not been called. This results in ROT.addObject being called which then calls
* ComThread.InitMTA
* <LI>One thread attempts to call ComThread.release() which then calls ROT
* .clear objects.
* </UL>
* The result is one thread with a call sequence ComThread--ROT and the other
* with a sequence ROT--ComThread resulting in deadlock.
* <p>
* This test will fail with debug logging turned on because of the amount of
* time it takes to write the debug output.
*
* @author jsamarziya
*
*/
public class JacobDeadlockTest extends BaseTestCase {
private static final long TIMEOUT = 5000l;
/** Thread component */
public static class TestThread extends Thread {
private final int id;
private final boolean initCOM;
private final boolean writeOutput;
/**
* constructor for ThestThread
*
* @param id
* @param initCOM
* @param writeOutput
*
*/
public TestThread(int id, boolean initCOM, boolean writeOutput) {
this.id = id;
this.initCOM = initCOM;
this.writeOutput = writeOutput;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
log("iteration " + i);
if (initCOM) {
log("Initializing COM thread");
ComThread.InitMTA(false);
}
log("Creating JacobObject");
new JacobObject();
log("Releasing COM thread");
ComThread.Release();
}
log("Exiting Java Thread");
}
private void log(String message) {
if (writeOutput) {
System.out.println(Thread.currentThread().getName()
+ ": TestThread[" + id + "] " + " " + " - " + message);
}
}
}
/**
* This test shows that if ComThread.Init() is called explicitly, no problem
* occurs.
*
* @throws InterruptedException
*/
public void testShowNoProblemIfCOMIsInitialized()
throws InterruptedException {
runTest(2, true, false);
runTest(100, true, false);
}
/**
* This test shows that if only one thread is creating COM objects, no
* problem occurs.
*
* @throws InterruptedException
*/
public void testShowNoProblemIfSingleThreaded() throws InterruptedException {
runTest(1, false, false);
runTest(1, true, false);
}
/**
* Runs the test with two threads, which don't initialize the COM thread.
*
* This test will always fail.
*
* @throws InterruptedException
*/
public void testShowDeadlockProblem() throws InterruptedException {
runTest(2, false, true);
}
private void runTest(int numberOfThreads, boolean initCOM,
boolean writeOutput) throws InterruptedException {
Thread[] threads = new Thread[numberOfThreads];
for (int i = 0; i < threads.length; i++) {
threads[i] = new TestThread(i, initCOM, writeOutput);
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
threads[i].join(TIMEOUT);
if (threads[i].isAlive()) {
fail("thread " + i + " failed to finish in " + TIMEOUT
+ " milliseconds");
}
}
}
}

View File

@@ -1,22 +0,0 @@
package com.jacob.com;
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.
*/
public class JacobObjectTest extends BaseTestCase {
/**
* 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

@@ -1,84 +0,0 @@
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() {
// this test used to run in the reverse order but that caused
// ClassDefNotFound on DEBUG
// 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());
}
// fill with bad dll name and try again
System.setProperty(LibraryLoader.JACOB_DLL_NAME, "xxx");
try {
LibraryLoader.loadJacobLibrary();
fail("Should have been unable to load dll with name xxx");
} catch (UnsatisfiedLinkError ule) {
System.out.println("correctly caught UnsatisfiedLinkError");
// yes, this is what we want to see when using a bad name
}
}
/**
* 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

@@ -1 +0,0 @@
This package exists in case folks need to test the Jacob COM objects and need access to protected methods

View File

@@ -1,122 +0,0 @@
package com.jacob.com;
import com.jacob.test.BaseTestCase;
/**
* This test class exists to test the WeakRefernce implementation .
*
* It is not useful if there isn't one at this time
*
* <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 ROT2Test extends BaseTestCase {
/**
* runs a multi-threaded test
*/
public void testDoesNotBlowUp() {
ROT2TestThread threads[] = new ROT2TestThread[4];
for (int i = 0; i < threads.length; i++) {
threads[i] = new ROT2TestThread("thread-" + i, 3000);
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
}
/**
* This will try and exercise the thread support in the ROT
*/
public class ROT2TestThread extends Thread {
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);
initialRunSize = iStartCount;
}
/**
* 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()
*/
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
ThreadObjects = new java.util.ArrayList<Variant>(initialRunSize);
for (int i = 0; i < initialRunSize; i++) {
// create the object
Variant aNewVariant = new Variant(getName() + "_" + i);
// create a hard reference to it
ThreadObjects.add(aNewVariant);
}
while (ThreadObjects.size() > 1) {
String message = "";
message = getName() + " Workingset=" + ThreadObjects.size()
+ " ROT: ";
message += "(before additions and gc "
+ ROT.getThreadObjects(false).size() + ")";
// if there is an odd number of objects greater than 2
if (ThreadObjects.size() > 2 && ThreadObjects.size() % 2 != 0) {
// add a new object
Variant aNewVariant = new Variant(getName() + "_*"
+ ThreadObjects.size());
ThreadObjects.add(aNewVariant);
}
// now iterate across all the objects in our list
for (int i = ThreadObjects.size(); i > 0; i--) {
// removing every other one?
if (i % 2 == 0) {
// remove the reference so gc can get it
ThreadObjects.remove(i - 1);
}
}
try {
// simulate the system under load and run the GC
// should end up with weak references with no objects
// attached
Thread.sleep(9);
} catch (InterruptedException e) {
// the VM doesn't want us to sleep anymore,
// so get back to work
}
message += " (before gc, after additions "
+ ROT.getThreadObjects(false).size() + ")";
System.gc();
message += " (after System.gc "
+ ROT.getThreadObjects(false).size() + ")";
System.out.println(message);
}
}
/**
* Another test would be to override this to always return the same
* name. That would really screw the ROT!
*
* @see java.lang.Object#toString()
*/
public String toString() {
return super.toString();
}
}
}

View File

@@ -1,141 +0,0 @@
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 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.
*/
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++) {
threads[i] = new ROT3TestThread("thread-" + i, 3000 + i * 10);
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
}
/**
* This will try and exercise the thread support in the ROT
*/
public class ROT3TestThread extends Thread {
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);
initialRunSize = iStartCount;
}
/**
* 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<Variant>(
initialRunSize);
for (int i = 0; i < initialRunSize; i++) {
// create the object
Variant aNewVariant = new Variant(getName() + "_" + i);
// create a hard reference to it
variansCreatedInThisThread.add(aNewVariant);
}
while (variansCreatedInThisThread.size() > 1) {
String message = "";
message = getName() + " Workingset="
+ variansCreatedInThisThread.size()
+ " ROT threadObject hashCode: "
+ ROT.getThreadObjects(true).hashCode();
message += " size before mods and gc "
+ ROT.getThreadObjects(true).size() + ")";
// If there are more than 10 objects in our cache then add 1/4
// of that again
if (variansCreatedInThisThread.size() > 10) {
message += " (adding) ";
// add an additional 1/4 of our current number
for (int i = 0; i < variansCreatedInThisThread.size() / 4; i++) {
// add a new object
Variant aNewVariant = new Variant(getName() + "_*"
+ variansCreatedInThisThread.size());
variansCreatedInThisThread.add(aNewVariant);
}
}
// now iterate across 1/2 the objects in our list
message += " (removing) ";
for (int i = variansCreatedInThisThread.size(); i > 0; i--) {
// removing every other one?
if (i % 2 == 0) {
// remove the reference so gc can get it
if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) {
// uses deprecated API to set up a special situation
// because this is an ROT test
ROT.removeObject(variansCreatedInThisThread
.get(i - 1));
}
variansCreatedInThisThread.remove(i - 1);
}
}
message += " (after mods " + ROT.getThreadObjects(true).size()
+ ")";
// comm
if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) {
ROT.clearObjects();
}
System.gc();
try {
// vain attempt at letting the gc run
Thread.sleep(200);
} catch (InterruptedException ie) {
}
message += " (after gc " + ROT.getThreadObjects(true).size()
+ ")";
message += " Should see GC if debug turned on...";
System.out.println(message);
}
}
/**
* Another test would be to overide this to always return the same name.
* That would really screw the ROT!
*
* @see java.lang.Object#toString()
*/
public String toString() {
return super.toString();
}
}
}

View File

@@ -1,133 +0,0 @@
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.
*/
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.");
}
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");
}
/**
* 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

@@ -1,70 +0,0 @@
package com.jacob.com;
import java.util.Date;
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.
*/
public class VariantDateTest extends BaseTestCase {
/**
* 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,745 +0,0 @@
package com.jacob.com;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
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.
*/
public class VariantTest extends BaseTestCase {
/**
* 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.
*
*/
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 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("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");
}
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");
}
}
/**
* 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() {
Variant v2 = new Variant();
v2.putNothing();
// this test fails even though the exact same code below works fine
// v2.toJavaObject();
}
/**
* see what happens when we conver to by ref
*
*/
public void testSomeChangeVT() {
Variant v;
// 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());
}
modifier = Variant.VariantString;
vConverted = v.changeType(modifier);
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;
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());
}
}
/**
* make sure variant with no backing store works.
*
*/
public void testUninitializedVariant() {
Variant v;
// Variants created without parameters are auto set to VariantEmpty
v = new Variant();
try {
if (v.getvt() == Variant.VariantEmpty) {
// successful
// 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());
}
} catch (IllegalStateException ise) {
throw new RuntimeException(
"getvt() on uninitialized variant shoud have succeeded, but instead threw exception");
}
try {
v.toString();
} catch (IllegalStateException ise) {
fail("toString() should never throw a runtime exception");
throw new RuntimeException(
"toString() should not blow up even with uninitialized Variant");
}
}
/**
*
* verify the toString() method does not do type conversion
*/
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");
} else {
// fail("toString() correctly does not convert type");
}
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");
} else {
// fail("toString() correctly does not convert type");
}
if (v.getBoolean() != false) {
fail("toString() converted boolean false to " + v.getBoolean());
}
}
/**
* Exercise ToString special cases
*/
public void testToStringEmptyValues() {
Variant v;
// create an empty variant
v = new Variant();
// check date per
v.changeType(Variant.VariantDate);
assertEquals("null", v.toString());
v.putDate(new Date());
assertNotNull(v.toString());
assertFalse("null".equals(v.toString()));
v.changeType(Variant.VariantInt);
v.putInt(1);
assertEquals("1", v.toString());
v.changeType(Variant.VariantEmpty);
assertEquals("null", v.toString());
v.changeType(Variant.VariantNull);
assertEquals("null", v.toString());
v.changeType(Variant.VariantError);
assertEquals("null", v.toString());
}
/**
* 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");
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");
}
v = new Variant(true);
for (int i = 0; i < 10; i++) {
new Variant("xxx" + i);
new Variant(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");
}
}
/**
* verify the constant values aren't released with safeRelease
*
*/
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) {
fail("VT_TRUE has been broken by SafeRelease()");
throw new RuntimeException("test failed");
} else {
// System.out.println("VT_TRUE survived SafeRelease()");
}
for (int i = 0; i < 10; i++) {
new Variant("xxx" + i);
new Variant(i);
new Variant("yyy" + i);
}
ComThread.Release();
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()");
}
}
/**
* 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";
Variant v = new Variant(mTestString);
// 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");
}
}
/**
* 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() {
Variant v = new Variant();
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.putFloat(40);
if (v.getFloat() != 40.0) {
fail("float test failed");
}
v.putDouble(50);
if (v.getDouble() != 50.0) {
fail("double test failed");
}
v.putString("1234.567");
assertEquals("string test failed", "1234.567", v.getString());
v.putBoolean(true);
assertEquals("failed boolean test(true)", true, v.getBoolean());
v.putBoolean(false);
assertEquals("failed boolean test(false)", false, v.getBoolean());
long originalValue = 123456789123456789L;
v.putCurrency(new Currency(originalValue));
assertEquals("failed currency test", 123456789123456789L, v
.getCurrency().longValue());
BigDecimal testDecimal = new BigDecimal("22.222");
v.putDecimal(testDecimal);
assertEquals("failed BigDecimal test", testDecimal, v.getDecimal());
Date ourDate = new Date();
v.putDate(ourDate);
Date retrievedDate = v.getJavaDate();
if (!retrievedDate.equals(ourDate)) {
fail("failed java date load and unload");
}
v.putNull();
if (!v.isNull()) {
fail("failed detecting set null");
}
v.putString("something other than null");
if (v.isNull()) {
fail("failed null replacement with string");
}
v.putEmpty();
if (!v.isNull()) {
fail("failed detecting set empty as null");
}
v.putString("something other than null");
if (v.isNull()) {
fail("failed empty replacement with string as isNull");
}
Variant v2 = new Variant();
v2.putNothing();
if (v2.getvt() != Variant.VariantDispatch) {
fail("putNothing was supposed to set the type to VariantDispatch");
}
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) {
fail("putNothing() followed by toJavaObject() should return a Dispatch");
}
}
/**
* verify decimal works right
*/
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) {
// do nothing
}
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 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()
*/
@Override
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;
}
}
/**
* there was a bitwise masking error that let booleans be seen as dispatch
* objects Bug Report SF3065265
*/
public void testGetDispatch() {
Variant testVariant = new Variant();
testVariant.putBooleanRef(true);
try {
// throws IllegalStateException if Jacob detects the type
// throws some other bad exception if COM blows up failing the
// conversion
testVariant.getDispatchRef();
fail("Should not have converted boolean to dispatch");
} catch (IllegalStateException e) {
// yeah! can't get dispatch from boolean
}
}
/**
* there was a bitwise masking error that let booleans be seen as dispatch
* objects Bug Report SF3065265
*/
public void testGetError() {
Variant testVariant = new Variant();
testVariant.putErrorRef(3);
try {
// throws IllegalStateException if Jacob detects the type
// throws some other bad exception if COM blows up failing the
// conversion
testVariant.getStringRef();
fail("Should not have converted error to string");
} catch (IllegalStateException e) {
// yeah! can't get dispatch from boolean
}
}
/**
* Verify SF 3435567 null and empty behavior change
*/
public void testGetNullString() {
Variant testVariant = new Variant();
testVariant.putNull();
assertNull(testVariant.getString());
testVariant.putEmpty();
assertNull(testVariant.getString());
testVariant.putString("dog");
assertEquals("dog", testVariant.getString());
}
}

View File

@@ -1,132 +0,0 @@
package com.jacob.com;
import java.util.Arrays;
import java.util.Date;
import com.jacob.test.BaseTestCase;
/**
* This class should test some of the converter capabilities
*
*/
public class VariantUtilitiesTest extends BaseTestCase {
/**
* verifies our unpacking stuff
*/
public void testObjectsToVariants() {
Object testArray[] = new Object[] { Integer.valueOf(1),
Integer.valueOf(2) };
Variant resultArray[] = VariantUtilities.objectsToVariants(testArray);
assertEquals(2, resultArray.length);
Variant resultArray2[] = VariantUtilities
.objectsToVariants(resultArray);
assertEquals(2, resultArray2.length);
assertSame(resultArray[0], resultArray2[0]);
assertSame(resultArray[1], resultArray2[1]);
}
/**
* test nested arrays
*/
public void testObjectsToVariantNestedArray() {
Object testArray[] = new Object[] { Integer.valueOf(1),
Integer.valueOf(2) };
Object testArrayOuter[] = new Object[] { testArray };
Variant resultArray[] = VariantUtilities
.objectsToVariants(testArrayOuter);
// should be a SafeArray
assertEquals(1, resultArray.length);
}
/**
* 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);
}
public void testPrimitiveByteArray() {
byte[] arr = new byte[] { 1, 2, 3 };
Variant arrVar = VariantUtilities.objectToVariant(arr);
assertNotNull(arrVar);
SafeArray sa = arrVar.toSafeArray();
assertNotNull(sa);
assertEquals(Variant.VariantByte, sa.getvt());
assertEquals(0, sa.getLBound());
assertEquals(2, sa.getUBound());
byte[] bytes = sa.toByteArray();
assertTrue(Arrays.equals(bytes, arr));
}
public void testPrimitiveIntArray() {
int[] arr = new int[] { 1000, 2000, 3 };
Variant arrVar = VariantUtilities.objectToVariant(arr);
assertNotNull(arrVar);
SafeArray sa = arrVar.toSafeArray();
assertNotNull(sa);
assertEquals(Variant.VariantInt, sa.getvt());
assertEquals(0, sa.getLBound());
assertEquals(2, sa.getUBound());
int[] ints = sa.toIntArray();
assertTrue(Arrays.equals(ints, arr));
}
public void testPrimitiveDoubleArray() {
double[] arr = new double[] { 1000, 2000, 3 };
Variant arrVar = VariantUtilities.objectToVariant(arr);
assertNotNull(arrVar);
SafeArray sa = arrVar.toSafeArray();
assertNotNull(sa);
assertEquals(Variant.VariantDouble, sa.getvt());
assertEquals(0, sa.getLBound());
assertEquals(2, sa.getUBound());
double[] doubles = sa.toDoubleArray();
assertTrue(Arrays.equals(doubles, arr));
}
public void testPrimitiveLongArray() {
long[] arr = new long[] { 0xcafebabecafebabeL, 42, 0xbabecafebabeL };
Variant arrVar = VariantUtilities.objectToVariant(arr);
assertNotNull(arrVar);
SafeArray sa = arrVar.toSafeArray();
assertNotNull(sa);
assertEquals(Variant.VariantLongInt, sa.getvt());
assertEquals(0, sa.getLBound());
assertEquals(2, sa.getUBound());
long[] longs = sa.toLongArray();
assertTrue(Arrays.equals(longs, arr));
}
}

View File

@@ -1,174 +0,0 @@
package com.jacob.test;
import java.net.URL;
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:
*
* <pre>
* -Djava.library.path=d:/jacob/release/x86
* -Dcom.jacob.autogc=false
* -Dcom.jacob.debug=false
* -Xcheck:jni
* </pre>
*/
public class BaseTestCase extends TestCase {
protected void setUp() {
// verify we have run with the dll in the lib path
try {
JacobObject foo = new JacobObject();
if (foo == null) {
fail("Failed basic sanity test: Can't create JacobObject (-D<java.library.path=xxx>)");
}
} catch (UnsatisfiedLinkError ule) {
fail("Did you remember to run with the jacob.dll in the libpath ?");
}
}
/**
* this test exists just to test the setup.
*/
public void testSetup() {
JacobObject foo = new JacobObject();
assertNotNull(foo);
}
/**
*
* @return a simple VB script that generates the result "3"
*/
public String getSampleVPScriptForEval() {
return "1+(2*4)-3";
}
/**
* Converts the class name into a path and appends the resource name. Used
* to derive the path to a 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
*/
@SuppressWarnings("unchecked")
private String getJavaFilePathToPackageResource(String resourceName,
Class classInSamePackageAsResource) {
String classPackageName = classInSamePackageAsResource.getName();
int i = classPackageName.lastIndexOf('.');
if (i == -1) {
classPackageName = "";
} else {
classPackageName = classPackageName.substring(0, i);
}
// change all "." to ^ for later conversion to "/" so we can append
// resource names with "."
classPackageName = classPackageName.replace('.', '^');
System.out.println("classPackageName: " + classPackageName);
String fullPathToResource;
if (classPackageName.length() > 0) {
fullPathToResource = classPackageName + "^" + resourceName;
} else {
fullPathToResource = resourceName;
}
fullPathToResource = fullPathToResource.replace('^', '/');
System.out.println("fullPathToResource: " + fullPathToResource);
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);
return fullPathToResourceAsFile;
}
/**
* 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
*/
@SuppressWarnings("unchecked")
public String getWindowsFilePathToPackageResource(String resourceName,
Class classInSamePackageAsResource) {
String javaFilePath = getJavaFilePathToPackageResource(resourceName,
classInSamePackageAsResource);
javaFilePath = javaFilePath.replace('/', '\\');
return javaFilePath.substring(1);
}
/**
*
* @param resourceName
* @param classInSamePackageAsResource
* @return a resource located in the same package as the passed in class
*/
@SuppressWarnings( { "unused", "unchecked" })
private Object getPackageResource(String resourceName,
Class classInSamePackageAsResource) {
String fullPathToResource = getJavaFilePathToPackageResource(
resourceName, classInSamePackageAsResource);
ClassLoader localClassLoader = classInSamePackageAsResource
.getClassLoader();
if (null == localClassLoader) {
return ClassLoader.getSystemResource(fullPathToResource);
} else {
return localClassLoader.getResource(fullPathToResource);
}
}
/**
* load a library from same place in the file system that the class was
* loaded from.
* <p>
* This is an attempt to let unit tests run without having to run regsvr32.
*
* @param libraryName
* @param classInSamePackageAsResource
*/
@SuppressWarnings( { "unchecked", "unused" })
private void loadLibraryFromClassPackage(String libraryName,
Class classInSamePackageAsResource) {
String libraryNameWithSuffix = "";
String fullLibraryNameWithPath = "";
if (libraryName != null && libraryName.endsWith("dll")) {
libraryNameWithSuffix = libraryName;
} else if (libraryName != null) {
libraryNameWithSuffix = libraryName + ".dll";
} else {
fail("can't create full library name " + libraryName);
}
// generate the path the classloader would use to find this on the
// classpath
fullLibraryNameWithPath = getJavaFilePathToPackageResource(
libraryNameWithSuffix, classInSamePackageAsResource);
System.load(fullLibraryNameWithPath);
// requires that the dll be on the library path
// System.loadLibrary(fullLibraryNameWithPath);
}
}

View File

@@ -1,34 +0,0 @@
package com.jacob.test.errors;
import com.jacob.test.BaseTestCase;
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.
*
* @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");
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);
}
}
}

View File

@@ -1,152 +0,0 @@
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;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/**
* This test was lifted from a forum posting and shows how you can't listen to
* 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.
*/
public class ExcelEventTest extends BaseTestCase {
/**
* load up excel, register for events and make stuff happen
*
* @param args
*/
public void testExcelWithInvocationProxy() {
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;
// office 2003
typeLibLocation = "C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE";
// office 2007
typeLibLocation = "C:\\Program Files\\Microsoft Office\\OFFICE12\\EXCEL.EXE";
// office 2013 322 bit
typeLibLocation = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\EXCEL.EXE";
// Grab The Component.
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"));
axc.setProperty("Visible", true);
Dispatch workbooks = axc.getPropertyAsComponent("Workbooks");
Dispatch workbook = Dispatch.get(workbooks, "Add").toDispatch();
Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
System.out.println("Workbook: " + workbook);
System.out.println("Sheet: " + sheet);
if (typeLibLocation.contains("OFFICE11")) {
// office 2007 throws crashes the VM
System.out.println("Hooking up sheet listener");
hookupListener(sheet, excelSheetProgramId, typeLibLocation);
}
System.out.println("Retrieving cells");
Dispatch a1 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { "A1" }, new int[1]).toDispatch();
Dispatch a2 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { "A2" }, new int[1]).toDispatch();
System.out.println("Inserting value into A1");
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"));
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 " + 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 listener to " + programId);
}
}
/**
* Proxy class to verify we receive expected events
*/
public class ExcelEvents extends InvocationProxy {
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.
*/
@Override
public Variant invoke(String methodName, Variant targetParameter[]) {
System.out.println("Received event from " + listenerPrefix + ": "
+ methodName);
return null;
}
}
}

View File

@@ -1,439 +0,0 @@
package com.jacob.test.events;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.DispatchEvents;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/**
* This test runs fine against jdk 1.4 and 1.5
*
* This 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 navigates 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.
*/
public class IETest extends BaseTestCase {
/**
* well known address we can navigate to
*/
private final String testUrls[] = {
"http://sourceforge.net/projects/jacob-project",
"http://www.google.com" };
/**
* runs the IE test and feeds it commands
*/
public void testRunIECleanly() {
runTheTest(true, testUrls);
}
/**
* runs the IE test and feeds it commands
*/
public void testRunIETerminateWithoutWait() {
runTheTest(false, testUrls);
}
/**
* The actual work of running the test.
*
* @param waitForQuit
* @param urls
*/
private void runTheTest(boolean waitForQuit, String[] urls) {
// this line starts the pump but it runs fine without it
ComThread.startMainSTA();
// Run the test in a thread. Lets us test running out of "main" thread
IETestThread aThread = new IETestThread(waitForQuit, urls);
aThread.start();
while (aThread.isAlive()) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
// done with the sleep
}
}
System.out.println("Main: Thread quit, about to quitMainSTA in thread "
+ Thread.currentThread().getName());
// this line only does something if startMainSTA() was called
ComThread.quitMainSTA();
System.out.println("Main: did quit main sta in thread "
+ Thread.currentThread().getName());
if (aThread.threadFailedWithException != null) {
aThread.threadFailedWithException.printStackTrace();
fail("caught an unexpected exception "
+ aThread.threadFailedWithException);
}
}
}
class IETestThread extends Thread {
/** flag that says we got a quit message from IE */
public static boolean quitHandled = false;
/**
* determines if we wait until last quit call back received before
* terminating
*/
private static boolean waitUntilReceivedQuitCallback = true;
/**
* the places we should navigate to
*/
private static String[] targets = null;
/**
* holds any caught exception so the main/test case can see them
*/
public Throwable threadFailedWithException = null;
/**
* constructor for the test thread
*
* @param beNeat
* should we wait until quit received
* @param urls
* the web pages we will navigate to
*/
public IETestThread(boolean beNeat, String urls[]) {
super();
waitUntilReceivedQuitCallback = beNeat;
targets = urls;
}
/**
* Run through the addresses passed in via the constructor
*/
@Override
public void run() {
// pick a time that lets sourceforge respond (in msec)
int delay = 3000;
// pre-1.14 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"));
// Some version of IE broke this. Not sure which one
// 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");
for (String url : targets) {
System.out.println("IETestThread: About to call navigate to "
+ url);
Dispatch.call(ie, "Navigate", new Variant(url));
System.out.println("IETestThread: Did call navigate to " + url);
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");
}
// a value is set to false if we try to crash VM by leaving before
// callbacks all received
if (waitUntilReceivedQuitCallback) {
System.out
.println("IETestThread: Waiting until we've received quit callback");
// wait a little while for it to end
while (!quitHandled) {
try {
Thread.sleep(delay / 10);
} catch (InterruptedException e) {
}
}
System.out.println("IETestThread: Received the OnQuit callback");
} else {
System.out.println("IETestThread: Not waiting for OnQuit callback");
}
System.out.println("IETestThread: Calling ComThread.Release in thread "
+ Thread.currentThread().getName());
ComThread.Release();
}
/**
* The events class must be publicly accessible 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
IETestThread.quitHandled = true;
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
/**
* 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 + " parameters");
}
}
}

View File

@@ -1,289 +0,0 @@
package com.jacob.test.events;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.activeX.ActiveXDispatchEvents;
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
* <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 IETestActiveXProxy extends BaseTestCase {
/**
* 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 {
/** 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;
/** the thread's constructor */
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 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 CommandStateChange(Integer command, Boolean enable) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName()
+ "): CommandStateChange " + command);
}
public void DocumentComplete(Dispatch pDisp, String url) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): DocumentComplete "
+ url);
}
public void DownloadBegin() {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): DownloadBegin ");
}
public void DownloadComplete() {
System.out
.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName()
+ "): DownloadComplete ");
}
public void NavigateComplete2(Dispatch pDisp, String url) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): NavigateComplete "
+ 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 NewWindow2(Dispatch pDisp, Boolean cancel) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): NewWindow2 "
+ pDisp);
}
public void OnFullScreen(Boolean fullScreen) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnFullScreen "
+ fullScreen);
}
public void OnMenuBar(Boolean menuBar) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnMenuBar "
+ menuBar);
}
public void OnQuit() {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnQuit ");
IETestActiveProxyThread.quitHandled = true;
}
public void OnStatusBar(Boolean statusBar) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnStatusBar "
+ statusBar);
}
public void OnTheaterMode(Boolean theaterMode) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnTheaterMode "
+ theaterMode);
}
public void OnToolBar(Boolean onToolBar) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnToolBar "
+ onToolBar);
}
public void OnVisible(Boolean onVisible) {
System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): onVisible "
+ onVisible);
}
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

@@ -1,93 +0,0 @@
package com.jacob.test.events;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComException;
import com.jacob.com.DispatchEvents;
import com.jacob.com.InvocationProxy;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/**
* This test was lifted from a forum posting and shows how you can't listen to
* 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.
*/
public class WordEventTest extends BaseTestCase {
/**
* load up word, register for events and make stuff happen
*
* @param args
*/
public void testCaptureWordEvents() {
String pid = "Word.Application";
String typeLibLocation = null;
// 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 WordEventTest());
} else {
de = new DispatchEvents(axc, new WordEventTest(), pid,
typeLibLocation);
}
if (de == null) {
fail("No exception thrown but no dispatch returned for Word events");
} else {
// Yea!
System.out.println("Successfully attached to " + pid);
}
// 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) {
fail("unable to get documents");
}
axc.invoke("Quit", new Variant[] {});
} catch (ComException cfe) {
cfe.printStackTrace();
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");
}
/**
* a class that receives messages from word
*/
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

@@ -1,236 +0,0 @@
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()");
}
}
}

View File

@@ -1,161 +0,0 @@
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.
*/
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
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 adding
* this to the tree just in case we need to come back to it.
* <P>
* This test was modified for office 2007 to synchronize communication with Excel.
* Office 2003 didn't require this.
* <p>
* This relies on BaseTestCase to provide the root path to the file under test
* <p>
* May need to run with some command line options (including from inside
* Eclipse). Look in the docs area at the Jacob usage document for command line
* options.
*/
public class PowerpointTest extends BaseTestCase {
private static final int NUM_THREADS = 5;
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();
}
}
/**
* 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();
}
// office 2003 seems to have been able to handle more
// multi-threaded requests than office 2007
// office 2003 could handle 5 threads @ 50 iterations
// office 2007 can only handle 1 thread at a time
synchronized(comPowerpoint){
Dispatch comPresentations = Dispatch.get(comPowerpoint,
"Presentations").toDispatch();
Dispatch comPresentation = Dispatch.call(
comPresentations,
"Open",
getWindowsFilePathToPackageResource("test"
+ threadID + ".ppt", this.getClass()),
new Integer(0), new Integer(0), new Integer(0))
.toDispatch();
Dispatch.call(comPresentation, "Close");
}
}
} catch (ComFailException cfe) {
threadFailedWithException = cfe;
System.err.println(Thread.currentThread().getName()
+ "\" while working on: "
+ getWindowsFilePathToPackageResource("test" + threadID
+ ".ppt", this.getClass()));
cfe.printStackTrace();
} catch (Exception e) {
threadFailedWithException = e;
System.err.println("Error in Thread \""
+ Thread.currentThread().getName() + "\":");
e.printStackTrace();
} finally {
ComThread.Release();
System.out.println("Thread \""
+ Thread.currentThread().getName() + "\" finished");
System.out.flush();
}
}
}
}

View File

@@ -1,273 +0,0 @@
package com.jacob.test.safearray;
import com.jacob.com.ComFailException;
import com.jacob.com.SafeArray;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
/**
* A safe array contents test (old test)
*
* <p>
* May need to run with some command line options (including from inside
* Eclipse). Look in the docs area at the Jacob usage document for command line
* options.
*/
public class SafeArrayContents extends BaseTestCase {
public static void printArray(boolean a[]) {
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " ");
}
System.out.println("]");
}
public static void printArray(int a[]) {
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " ");
}
System.out.println("]");
}
public static void printArray(short a[]) {
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " ");
}
System.out.println("]");
}
public static void printArray(byte a[]) {
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " ");
}
System.out.println("]");
}
public static void printArray(double a[]) {
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " ");
}
System.out.println("]");
}
public static void printArray(float a[]) {
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " ");
}
System.out.println("]");
}
public static void printArray(String a[]) {
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " ");
}
System.out.println("]");
}
public static void printArray(Variant a[]) {
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " ");
}
System.out.println("]");
}
public static void printArray(char a[]) {
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " ");
}
System.out.println("]");
}
public void testSafeArrayContents() {
// int
System.out.println("Int");
SafeArray ia = new SafeArray(Variant.VariantInt, 4);
System.out.println("elem size:" + ia.getElemSize());
int iack[] = new int[] { 100000, 200000, 300000, 400000 };
printArray(iack);
ia.fromIntArray(iack);
iack = ia.toIntArray();
printArray(iack);
int i4[] = new int[4];
ia.getInts(0, 4, i4, 0);
printArray(i4);
SafeArray ia2 = new SafeArray(Variant.VariantInt, 4);
ia2.setInts(0, 4, i4, 0);
iack = ia2.toIntArray();
printArray(iack);
// double
System.out.println("Double");
SafeArray da = new SafeArray(Variant.VariantDouble, 4);
System.out.println("elem size:" + da.getElemSize());
double dack[] = new double[] { 123.456, 456.123, 1234567.89, 12.3456789 };
printArray(dack);
da.fromDoubleArray(dack);
dack = da.toDoubleArray();
printArray(dack);
double d4[] = new double[4];
da.getDoubles(0, 4, d4, 0);
printArray(d4);
SafeArray da2 = new SafeArray(Variant.VariantDouble, 4);
da2.setDoubles(0, 4, d4, 0);
dack = da2.toDoubleArray();
printArray(dack);
// float
System.out.println("Float");
SafeArray fa = new SafeArray(Variant.VariantFloat, 4);
System.out.println("elem size:" + fa.getElemSize());
float fack[] = new float[] { 123.456F, 456.123F, 1234567.89F,
12.3456789F };
printArray(fack);
fa.fromFloatArray(fack);
fack = fa.toFloatArray();
printArray(fack);
float f4[] = new float[4];
fa.getFloats(0, 4, f4, 0);
printArray(f4);
SafeArray fa2 = new SafeArray(Variant.VariantFloat, 4);
fa2.setFloats(0, 4, f4, 0);
fack = fa2.toFloatArray();
printArray(fack);
// boolean
System.out.println("Boolean");
SafeArray ba = new SafeArray(Variant.VariantBoolean, 4);
System.out.println("elem size:" + ba.getElemSize());
boolean back[] = new boolean[] { true, false, true, false };
printArray(back);
ba.fromBooleanArray(back);
back = ba.toBooleanArray();
printArray(back);
boolean b4[] = new boolean[4];
ba.getBooleans(0, 4, b4, 0);
printArray(b4);
SafeArray ba2 = new SafeArray(Variant.VariantBoolean, 4);
ba2.setBooleans(0, 4, b4, 0);
back = ba2.toBooleanArray();
printArray(back);
// char
System.out.println("Char");
SafeArray ca = new SafeArray(Variant.VariantShort, 4);
System.out.println("elem size:" + ca.getElemSize());
char cack[] = new char[] { 'a', 'b', 'c', 'd' };
printArray(cack);
ca.fromCharArray(cack);
cack = ca.toCharArray();
printArray(cack);
char c4[] = new char[4];
ca.getChars(0, 4, c4, 0);
printArray(c4);
SafeArray ca2 = new SafeArray(Variant.VariantShort, 4);
ca2.setChars(0, 4, c4, 0);
cack = ca2.toCharArray();
printArray(cack);
// short
System.out.println("Short");
SafeArray sha = new SafeArray(Variant.VariantShort, 4);
System.out.println("elem size:" + sha.getElemSize());
short shack[] = new short[] { 1000, 2000, 3000, 4000 };
printArray(shack);
sha.fromShortArray(shack);
shack = sha.toShortArray();
printArray(shack);
short sh4[] = new short[4];
sha.getShorts(0, 4, sh4, 0);
printArray(sh4);
SafeArray sha2 = new SafeArray(Variant.VariantShort, 4);
sha2.setShorts(0, 4, sh4, 0);
shack = sha2.toShortArray();
printArray(shack);
// string
System.out.println("String");
SafeArray sa = new SafeArray(Variant.VariantString, 4);
System.out.println("elem size:" + sa.getElemSize());
String sack[] = new String[] { "aa", "bb", "cc", "dd" };
printArray(sack);
sa.fromStringArray(sack);
sack = sa.toStringArray();
printArray(sack);
String s4[] = new String[4];
sa.getStrings(0, 4, s4, 0);
printArray(s4);
SafeArray sa2 = new SafeArray(Variant.VariantString, 4);
sa2.setStrings(0, 4, s4, 0);
sack = sa2.toStringArray();
printArray(sack);
// variant
System.out.println("Variant");
SafeArray va = new SafeArray(Variant.VariantVariant, 4);
System.out.println("elem size:" + va.getElemSize());
Variant vack[] = new Variant[] { new Variant(1), new Variant(2.3),
new Variant(true), new Variant("four"), };
printArray(vack);
va.fromVariantArray(vack);
vack = va.toVariantArray();
printArray(vack);
Variant v4[] = new Variant[4];
va.getVariants(0, 4, v4, 0);
printArray(v4);
SafeArray va2 = new SafeArray(Variant.VariantVariant, 4);
va2.setVariants(0, 4, v4, 0);
vack = va2.toVariantArray();
printArray(vack);
// byte
System.out.println("Byte");
SafeArray bba = new SafeArray(Variant.VariantByte, 4);
System.out.println("elem size:" + bba.getElemSize());
byte bback[] = new byte[] { 0x1, 0x2, 0x3, 0x4 };
printArray(bback);
bba.fromByteArray(bback);
bback = bba.toByteArray();
printArray(bback);
byte bb4[] = new byte[4];
bba.getBytes(0, 4, bb4, 0);
printArray(bb4);
SafeArray bba2 = new SafeArray(Variant.VariantByte, 4);
bba2.setBytes(0, 4, bb4, 0);
bback = bba2.toByteArray();
printArray(bback);
try {
// this should throw ComException
bba2.fromCharArray(new char[] { 'a' });
fail("Failed to catch expected exception");
} catch (ComFailException cfe) {
// do nothing
// cfe.printStackTrace();
}
}
}

View File

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

View File

@@ -1,177 +0,0 @@
package com.jacob.test.safearray;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
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:
* <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
*/
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: " + 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"));
xl.setProperty("Visible", new Variant(false));
workbooks = xl.getProperty("Workbooks").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();
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++) {
colLgn[1] = i;
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");
// 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;
}
}
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;
}
}
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();
}
}
}
}

View File

@@ -1,89 +0,0 @@
package com.jacob.test.safearray;
import com.jacob.com.ComThread;
import com.jacob.com.SafeArray;
import com.jacob.com.Variant;
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| +------------+ +---------+
*
* <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;
/**
* 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,24 +0,0 @@
package com.jacob.test.safearray;
import com.jacob.com.SafeArray;
import com.jacob.test.BaseTestCase;
/**
* Test case provided #41 Fix for SafeArray(String) constructor
*
* In the current release of Jacob, SafeArray.java contains a constructor which
* takes a string as a single argument. The documentation claims that this
* method converts a string to a VT_UI1 array. Using this method as written
* always causes a ComFailException, because it attempts to create a SafeArray
* from Java chars, which are 16-bit unsigned integers (which would be VT_UI2).
*/
public class SafeArrayStringConstructorTest extends BaseTestCase {
public void testStringConstructor() {
// The line below will throw ComFailException using jacob 1.17-M2
// without the patch.
SafeArray safeArrayFromString = new SafeArray("This is a string.");
String convertBack = safeArrayFromString.asString();
assertEquals("This is a string.", convertBack);
}
}

View File

@@ -1,75 +0,0 @@
package com.jacob.test.safearray;
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;
/**
* 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.
* <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() {
ActiveXComponent xl = new ActiveXComponent("Excel.Application");
try {
Dispatch cell;
SafeArray sAProdText;
Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
System.out.println("have workbooks");
Dispatch workbook = Dispatch.call(
workbooks,
"Open",
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,
new Object[] { "A1:D1000" }, new int[1]).toDispatch();
System.out.println("have cell:" + cell);
sAProdText = Dispatch.get(cell, "Value").toSafeArray();
System.out.println("sa: dim=" + sAProdText.getNumDim());
System.out.println("sa: start row=" + sAProdText.getLBound(1));
System.out.println("sa: start col=" + sAProdText.getLBound(2));
System.out.println("sa: end row=" + sAProdText.getUBound(1));
System.out.println("sa: end col=" + sAProdText.getUBound(2));
int i;
int lineNumber = 1;
int n = 0;
for (lineNumber = 1; lineNumber < 1000; lineNumber++) {
for (i = 1; i < 4; i++) {
System.out.println((n++) + " " + lineNumber + " " + i + " "
+ sAProdText.getString(lineNumber, i));
/*
* if (sAProdText.getString(lineNumber,i).compareTo("aaaa") !=
* 0 ) { System.out.println("Invalid String in line " +
* lineNumber + " Cell " + i + " Value = " +
* sAProdText.getString(lineNumber,i)); stringFound = false; } }
* if (stringFound) { System.out.println("Valid Strings in
* line " + lineNumber); lineNumber++; }
*/
}
}
Dispatch.call(workbook, "Close");
System.out.println("Closed File\n");
} catch (Exception e) {
e.printStackTrace();
fail("Caught Exception " + e);
} finally {
xl.invoke("Quit", new Variant[] {});
}
}
}

View File

@@ -1,67 +0,0 @@
package com.jacob.test.vbscript;
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;
/**
* 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 ScriptTest extends BaseTestCase {
public void testStupidSpeedTest() {
String lang = "VBScript";
ActiveXComponent sC = new ActiveXComponent("ScriptControl");
Dispatch sControl = sC.getObject();
Dispatch.put(sControl, "Language", lang);
for (int i = 0; i < 10000; i++) {
Dispatch.call(sControl, "Eval", "1+1");
}
}
public void testCreatingDispatchEvents() {
ComThread.InitSTA(true);
DispatchEvents de = null;
Dispatch sControl = null;
try {
String scriptCommand = getSampleVPScriptForEval();
String lang = "VBScript";
ActiveXComponent sC = new ActiveXComponent("ScriptControl");
sControl = sC.getObject();
Dispatch.put(sControl, "Language", lang);
ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sControl, te);
if (de == null) {
System.out
.println("Received null when trying to create new DispatchEvents");
}
Variant result = Dispatch.call(sControl, "Eval", scriptCommand);
// call it twice to see the objects reused
result = Dispatch.call(sControl, "Eval", scriptCommand);
// call it 3 times to see the objects reused
result = Dispatch.call(sControl, "Eval", scriptCommand);
System.out.println("eval(" + scriptCommand + ") = " + result);
} catch (ComException e) {
e.printStackTrace();
fail("Caught Exception " + e);
} finally {
Integer I = null;
for (int i = 1; i < 1000000; i++) {
I = new Integer(i);
}
System.out.println(I);
ComThread.Release();
ComThread.quitMainSTA();
}
}
}

View File

@@ -1,105 +0,0 @@
package com.jacob.test.vbscript;
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;
/**
* This example demonstrates how to make calls between two different STA's.
* First, to create an STA, you need to extend the STA class and override its
* OnInit() method. This method will be called in the STA's thread so you can
* use it to create your COM components that will run in that STA. If you then
* try to call methods on those components from other threads (STA or MTA) -
* this will fail. You cannot create a component in an STA and call its methods
* from another thread. You can use the DispatchProxy to get a proxy to any
* Dispatch that lives in another STA. This object has to be created in the STA
* that houses the Dispatch (in this case it's created in the OnInit method).
* Then, another thread can call the toDispatch() method of DispatchProxy to get
* a local proxy. At most ONE (!) thread can call toDispatch(), and the call can
* be made only once. This is because a IStream object is used to pass the
* proxy, and it is only written once and closed when you read it. If you need
* 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.
*/
public class ScriptTest2 extends BaseTestCase {
public void testScript2() {
try {
ComThread.InitSTA();
ScriptTestSTA script = new ScriptTestSTA();
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
// should we get this?
}
String scriptCommand = getSampleVPScriptForEval();
// get a thread-local Dispatch from sCon
Dispatch sc = script.sCon.toDispatch();
// call a method on the thread-local Dispatch obtained
// from the DispatchProxy. If you try to make the same
// method call on the sControl object - you will get a
// ComException.
Variant result = Dispatch.call(sc, "Eval", scriptCommand);
System.out.println("eval(" + scriptCommand + ") = " + result);
script.quit();
System.out.println("called quit");
} catch (ComException e) {
e.printStackTrace();
fail("caught exception" + e);
} finally {
Integer I = null;
for (int i = 1; i < 1000000; i++) {
I = new Integer(i);
}
System.out.println(I);
ComThread.Release();
}
}
public class ScriptTestSTA extends STA {
public DispatchEvents de = null;
public Dispatch sControl = null;
public DispatchProxy sCon = null;
public boolean OnInit() {
try {
System.out.println("OnInit");
System.out.println(Thread.currentThread());
String lang = "VBScript";
sControl = new ActiveXComponent("ScriptControl");
// sCon can be called from another thread
sCon = new DispatchProxy(sControl);
Dispatch.put(sControl, "Language", lang);
ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sControl, te);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void OnQuit() {
System.out.println("OnQuit");
}
}
}

View File

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

View File

@@ -1,81 +0,0 @@
package com.jacob.test.vbscript;
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;
/**
* Here we create the ScriptControl component in a separate MTA thread and then
* call the Eval method from the main thread. The main thread must also be an
* 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.
*/
public class ScriptTest3 extends BaseTestCase {
public static ActiveXComponent sC;
public static DispatchEvents de = null;
public static Dispatch sControl = null;
public static boolean quit = false;
public void testScript() {
try {
ComThread.InitMTA();
ScriptTest3Inner script = new ScriptTest3Inner();
script.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
// should we get this?
}
Variant result = Dispatch.call(sControl, "Eval",
getSampleVPScriptForEval());
System.out.println("eval(" + getSampleVPScriptForEval() + ") = "
+ result);
System.out.println("setting quit");
ScriptTest3.quit = true;
} catch (ComException e) {
e.printStackTrace();
fail("Caught excpetion running script with MTA");
} finally {
System.out.println("main done");
ComThread.Release();
}
}
class ScriptTest3Inner extends Thread {
public void run() {
try {
ComThread.InitMTA();
System.out.println("OnInit");
String lang = "VBScript";
sC = new ActiveXComponent("ScriptControl");
sControl = sC.getObject();
Dispatch.put(sControl, "Language", lang);
ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sControl, te);
System.out.println("sControl=" + sControl);
while (!quit) {
sleep(100);
}
ComThread.Release();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("worker thread exits");
}
}
}
}

View File

@@ -1,75 +0,0 @@
package com.jacob.test.vbscript;
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;
/**
* Here we create the ScriptControl component in a separate MTA thread and then
* call the Eval method from the main thread. The main thread must also be an
* 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.
*/
public class ScriptTest3ActiveX extends BaseTestCase {
public static ActiveXComponent sC;
public static DispatchEvents de = null;
public static boolean quit = false;
public void testYetAnotherScriptTest() {
try {
ComThread.InitMTA();
ScriptTest3ActiveXInner script = new ScriptTest3ActiveXInner();
script.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
// should we get this?
}
Variant result = sC.invoke("Eval", getSampleVPScriptForEval());
System.out.println("eval(" + getSampleVPScriptForEval() + ") = "
+ result);
System.out.println("setting quit");
ScriptTest3ActiveX.quit = true;
} catch (ComException e) {
e.printStackTrace();
fail("Caught ComException " + e);
} finally {
System.out.println("main done");
ComThread.Release();
}
}
public class ScriptTest3ActiveXInner extends Thread {
public void run() {
try {
ComThread.InitMTA();
System.out.println("OnInit");
String lang = "VBScript";
sC = new ActiveXComponent("ScriptControl");
sC.setProperty("Language", lang);
ScriptTestErrEvents te = new ScriptTestErrEvents();
de = new DispatchEvents(sC, te);
System.out.println("sControl=" + sC);
while (!quit) {
sleep(100);
}
ComThread.Release();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("worker thread exits");
}
}
}
}

View File

@@ -1,53 +0,0 @@
package com.jacob.test.vbscript;
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;
/**
* 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() {
ComThread.InitSTA(true);
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);
ComThread.Release();
ComThread.quitMainSTA();
}
}
}

View File

@@ -1,19 +0,0 @@
package com.jacob.test.vbscript;
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
*/
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!");
}
}

View File

@@ -1,69 +0,0 @@
package com.jacob.test.windowsmedia;
/**
* partial test program from the sourceforge bug report 1453161
* that says you get a random "can't map name to dispid" when
* getting the URL from the player
* <p>
* this doesn't actually play for some reason. It always says the length is 0.
* <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>
*/
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jacob.test.BaseTestCase;
public class WMPlayer extends BaseTestCase {
/**
* This should demo the media player but it doesn't
*/
public void testOpenWMPlayer() {
// this file exists in windows 7 installations
File file = new File(
"C:/Windows/winsxs/x86_microsoft-windows-videosamples_31bf3856ad364e35_6.1.7600.16385_none_f583837f77a63ec7");
String filePath = file.getAbsolutePath();
String microsoftTestURL = filePath;
// use these instead if not on windows 7
// "http://support.microsoft.com/support/mediaplayer/wmptest/samples/new/mediaexample.wma";
// "http://support.microsoft.com/support/mediaplayer/wmptest/samples/new/mediaexample.wmv";
ActiveXComponent wmp = null;
// could use WMPlayer.OCX alias also
wmp = new ActiveXComponent(
"CLSID:{6BF52A52-394A-11D3-B153-00C04F79FAA6}");// ("WMPlayer.OCX");
wmp.setProperty("URL", microsoftTestURL);
assertEquals(wmp.getProperty("URL").toString(), microsoftTestURL);
// alternative way to get the controls
Dispatch controls = Dispatch.get(wmp, "controls").toDispatch();
Dispatch.call(controls, "Play");
// the sourceforge posting didn't post all the code so this is all we
// have we need some other information on how to set the document
// so that we have a url to open
// pause to let it play a second or two
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
for (int i = 0; i < 1000; i++) {
// Get media object
Dispatch vMedObj = wmp.getProperty("currentMedia").toDispatch();
// Get duration of media object
Variant vdur = Dispatch.call(vMedObj, "duration");
// why is this always 0?
// System.out.println(microsoftTestURL + " length is "
// + vdur.getDouble());
// System.out.println("the wmp url is "
// + wmp.getProperty("URL").toString());
}
}
}