Replace tabs with spaces

This commit is contained in:
2015-09-01 13:12:04 +01:00
parent e51103215c
commit 0bab3d8ace
111 changed files with 22231 additions and 22231 deletions

View File

@@ -279,7 +279,7 @@ JNIEXPORT jintArray JNICALL Java_com_jacob_com_Dispatch_getIDsOfNames
{ {
USES_CONVERSION; USES_CONVERSION;
jstring s = (jstring)env->GetObjectArrayElement(names, i); jstring s = (jstring)env->GetObjectArrayElement(names, i);
// if we used env->GetStringChars() would that let us drop the conversion? // if we used env->GetStringChars() would that let us drop the conversion?
const char *nm = env->GetStringUTFChars(s, NULL); const char *nm = env->GetStringUTFChars(s, NULL);
LPOLESTR nmos = A2W(nm); LPOLESTR nmos = A2W(nm);
env->ReleaseStringUTFChars(s, nm); env->ReleaseStringUTFChars(s, nm);
@@ -319,8 +319,8 @@ static char* BasicToCharString(const BSTR inBasicString)
if (charStrSize > 1) if (charStrSize > 1)
{ {
charString = new char[charStrSize]; charString = new char[charStrSize];
size_t convertedSize; size_t convertedSize;
::wcstombs_s(&convertedSize, charString, charStrSize, inBasicString, charStrSize); ::wcstombs_s(&convertedSize, charString, charStrSize, inBasicString, charStrSize);
} }
else else
{ {
@@ -394,14 +394,14 @@ static wchar_t* CreateErrorMsgFromInfo(HRESULT inResult, EXCEPINFO* ioInfo,
const size_t MSG_LEN = ::wcslen(methNameW) + ::wcslen(msg2) + 256; const size_t MSG_LEN = ::wcslen(methNameW) + ::wcslen(msg2) + 256;
msg = new wchar_t[MSG_LEN]; msg = new wchar_t[MSG_LEN];
::wcsncpy_s(msg, MSG_LEN, ::wcsncpy_s(msg, MSG_LEN,
L"A COM exception has been encountered:\nAt Invoke of: ", L"A COM exception has been encountered:\nAt Invoke of: ",
wcslen(L"A COM exception has been encountered:\nAt Invoke of: ")); wcslen(L"A COM exception has been encountered:\nAt Invoke of: "));
::wcsncat_s(msg, MSG_LEN, methNameW, wcslen(methNameW)); ::wcsncat_s(msg, MSG_LEN, methNameW, wcslen(methNameW));
::wcsncat_s(msg, MSG_LEN, L"\nDescription: ", wcslen(L"\nDescription: ")); ::wcsncat_s(msg, MSG_LEN, L"\nDescription: ", wcslen(L"\nDescription: "));
::wcsncat_s(msg, MSG_LEN, msg2, wcslen(msg2)); ::wcsncat_s(msg, MSG_LEN, msg2, wcslen(msg2));
// jacob-msg 1075 - SF 1053872 : Documentation says "use LocalFree"!! // jacob-msg 1075 - SF 1053872 : Documentation says "use LocalFree"!!
//delete msg2; //delete msg2;
LocalFree(msg2); LocalFree(msg2);
} }
delete methNameW; delete methNameW;
return msg; return msg;
@@ -494,15 +494,15 @@ JNIEXPORT jobject JNICALL Java_com_jacob_com_Dispatch_invokev
jint count = env->GetArrayLength(uArgErr); jint count = env->GetArrayLength(uArgErr);
if ( count != 0 ) if ( count != 0 )
{ {
jint *uAE = env->GetIntArrayElements(uArgErr, NULL); jint *uAE = env->GetIntArrayElements(uArgErr, NULL);
hr = pIDispatch->Invoke(dispID,IID_NULL, hr = pIDispatch->Invoke(dispID,IID_NULL,
lcid,(WORD)wFlags,&dispparams,v,&excepInfo,(unsigned int *)uAE); // SF 1689061 lcid,(WORD)wFlags,&dispparams,v,&excepInfo,(unsigned int *)uAE); // SF 1689061
env->ReleaseIntArrayElements(uArgErr, uAE, 0); env->ReleaseIntArrayElements(uArgErr, uAE, 0);
} }
else else
{ {
hr = pIDispatch->Invoke(dispID,IID_NULL, hr = pIDispatch->Invoke(dispID,IID_NULL,
lcid,(WORD)wFlags,&dispparams,v,&excepInfo, NULL); // SF 1689061 lcid,(WORD)wFlags,&dispparams,v,&excepInfo, NULL); // SF 1689061
} }
if (num_args) if (num_args)
{ {
@@ -531,30 +531,30 @@ JNIEXPORT jobject JNICALL Java_com_jacob_com_Dispatch_invokev
// this method can get called with a name or a dispatch id // this method can get called with a name or a dispatch id
// we need to handle both SF 1114159 // we need to handle both SF 1114159
if (name != NULL){ if (name != NULL){
const char *nm = env->GetStringUTFChars(name, NULL); const char *nm = env->GetStringUTFChars(name, NULL);
buf = CreateErrorMsgFromInfo(hr, &excepInfo, nm); buf = CreateErrorMsgFromInfo(hr, &excepInfo, nm);
env->ReleaseStringUTFChars(name, nm); env->ReleaseStringUTFChars(name, nm);
} else { } else {
dispIdAsName = new char[256]; dispIdAsName = new char[256];
// get the id string // get the id string
_itoa_s (dispID, dispIdAsName, 256,10); _itoa_s (dispID, dispIdAsName, 256,10);
//continue on mostly as before //continue on mostly as before
buf = CreateErrorMsgFromInfo(hr,&excepInfo,dispIdAsName); buf = CreateErrorMsgFromInfo(hr,&excepInfo,dispIdAsName);
} }
// jacob-msg 3696 - SF 1053866 // jacob-msg 3696 - SF 1053866
if(hr == DISP_E_EXCEPTION) if(hr == DISP_E_EXCEPTION)
{ {
if(excepInfo.scode != 0) if(excepInfo.scode != 0)
{ {
hr = excepInfo.scode; hr = excepInfo.scode;
} }
else else
{ {
hr = _com_error::WCodeToHRESULT(excepInfo.wCode); hr = _com_error::WCodeToHRESULT(excepInfo.wCode);
} }
} }
ThrowComFailUnicode(env, buf, hr); ThrowComFailUnicode(env, buf, hr);
if (buf) delete buf; if (buf) delete buf;
if (dispIdAsName) delete dispIdAsName; if (dispIdAsName) delete dispIdAsName;
@@ -568,20 +568,20 @@ JNIEXPORT jobject JNICALL Java_com_jacob_com_Dispatch_invokev
* Wait method added so folks could wait until a com server terminated * Wait method added so folks could wait until a com server terminated
*/ */
JNIEXPORT jint JNICALL Java_com_jacob_com_Dispatch_hasExited JNIEXPORT jint JNICALL Java_com_jacob_com_Dispatch_hasExited
(JNIEnv *env,jclass clazz, jobject disp, jint dispid, jint lcid) { (JNIEnv *env,jclass clazz, jobject disp, jint dispid, jint lcid) {
IDispatch *pIDispatch = extractDispatch(env, disp); IDispatch *pIDispatch = extractDispatch(env, disp);
if (!pIDispatch) { if (!pIDispatch) {
// should we return 0? // should we return 0?
return NULL; return NULL;
} }
ITypeInfo *v; ITypeInfo *v;
HRESULT hr = pIDispatch->GetTypeInfo(dispid, lcid, &v); HRESULT hr = pIDispatch->GetTypeInfo(dispid, lcid, &v);
if (hr == RPC_E_SERVERCALL_RETRYLATER || hr == RPC_E_CALL_REJECTED || hr if (hr == RPC_E_SERVERCALL_RETRYLATER || hr == RPC_E_CALL_REJECTED || hr
== 0) { == 0) {
return 0; return 0;
} else { } else {
return 1; return 1;
} }
} }
} }

View File

@@ -74,32 +74,32 @@ JNIEXPORT void JNICALL Java_com_jacob_com_DispatchEvents_init3
jstring _progid, jstring _progid,
jstring _typelib) jstring _typelib)
{ {
USES_CONVERSION; USES_CONVERSION;
if (_typelib != NULL && _progid == NULL){ if (_typelib != NULL && _progid == NULL){
// both are required if typelib exists // both are required if typelib exists
ThrowComFail(env,"TypeLib was specified but no program id was",-1); ThrowComFail(env,"TypeLib was specified but no program id was",-1);
return; return;
} }
BSTR typeLib = NULL; BSTR typeLib = NULL;
if (_typelib != NULL){ if (_typelib != NULL){
// why is this UTF instead of unicode? Then we could probably drop the A2W // why is this UTF instead of unicode? Then we could probably drop the A2W
const char *typelib = env->GetStringUTFChars(_typelib, NULL); const char *typelib = env->GetStringUTFChars(_typelib, NULL);
typeLib = A2W(typelib); typeLib = A2W(typelib);
// should we call env->ReleaseStringUTFChars(,) to free the memory like we do everywhere lese? // should we call env->ReleaseStringUTFChars(,) to free the memory like we do everywhere lese?
//printf("we have a type lib %ls\n",typeLib); //printf("we have a type lib %ls\n",typeLib);
} }
// find progid if any // find progid if any
LPOLESTR bsProgId = NULL; LPOLESTR bsProgId = NULL;
if (_progid!=NULL) { if (_progid!=NULL) {
// why is this UTF instead of unicode? Then we could probably drop the A2W // why is this UTF instead of unicode? Then we could probably drop the A2W
const char *progid = env->GetStringUTFChars(_progid, NULL); const char *progid = env->GetStringUTFChars(_progid, NULL);
bsProgId = A2W(progid); bsProgId = A2W(progid);
// should we call env->ReleaseStringUTFChars(,) to free the memory like we do everywhere lese? // should we call env->ReleaseStringUTFChars(,) to free the memory like we do everywhere lese?
//printf("we have an applicaton %ls\n",bsProgId); //printf("we have an applicaton %ls\n",bsProgId);
} }
// get the IDispatch for the source object // get the IDispatch for the source object
@@ -119,15 +119,15 @@ JNIEXPORT void JNICALL Java_com_jacob_com_DispatchEvents_init3
DISPID *mIDs; DISPID *mIDs;
int n_EventMethods; int n_EventMethods;
if (_typelib == NULL){ if (_typelib == NULL){
if (!GetEventIID(pUnk, &eventIID, &mNames, &mIDs, &n_EventMethods,bsProgId)) { if (!GetEventIID(pUnk, &eventIID, &mNames, &mIDs, &n_EventMethods,bsProgId)) {
ThrowComFail(env, "Can't find event iid", -1); ThrowComFail(env, "Can't find event iid", -1);
return; return;
} }
} else { } else {
if (!GetEventIIDForTypeLib(typeLib, &eventIID, &mNames, &mIDs, &n_EventMethods,bsProgId)) { if (!GetEventIIDForTypeLib(typeLib, &eventIID, &mNames, &mIDs, &n_EventMethods,bsProgId)) {
ThrowComFail(env, "Can't find event iid for type lib", -1); ThrowComFail(env, "Can't find event iid for type lib", -1);
return; return;
} }
} }
// hook up to the default source iid // hook up to the default source iid
@@ -153,10 +153,10 @@ JNIEXPORT void JNICALL Java_com_jacob_com_DispatchEvents_release
{ {
EventProxy *ep = extractProxy(env, _this); EventProxy *ep = extractProxy(env, _this);
if (ep) { if (ep) {
// Disconnect must be called to reduce the ref count to the EventProxy otherwise // Disconnect must be called to reduce the ref count to the EventProxy otherwise
// the destructor will never be called (to actually do the disconnect) // the destructor will never be called (to actually do the disconnect)
ep->Disconnect(); // SF 3412922 ep->Disconnect(); // SF 3412922
// this is the line that blows up in IETest // this is the line that blows up in IETest
ep->Release(); ep->Release();
putProxy(env, _this, NULL); putProxy(env, _this, NULL);
} }
@@ -219,15 +219,15 @@ BOOL GetEventIID(IUnknown *m_pObject, IID* piid,
{ {
//printf("got IProvideClassInfo\n"); //printf("got IProvideClassInfo\n");
ATLASSERT(pPCI != NULL); ATLASSERT(pPCI != NULL);
HRESULT hr = pPCI->GetClassInfo(&pClassInfo); HRESULT hr = pPCI->GetClassInfo(&pClassInfo);
pPCI->Release(); pPCI->Release();
if (!SUCCEEDED(hr)) return false; if (!SUCCEEDED(hr)) return false;
} }
else if (getClassInfoFromProgId(bsProgId,&pClassInfo)) { else if (getClassInfoFromProgId(bsProgId,&pClassInfo)) {
} }
else { else {
printf("GetEventIID: couldn't get IProvideClassInfo\n"); printf("GetEventIID: couldn't get IProvideClassInfo\n");
return false; return false;
} }
return MapEventIIDs(piid, mNames, mIDs, nmeth, bsProgId, pClassInfo); return MapEventIIDs(piid, mNames, mIDs, nmeth, bsProgId, pClassInfo);
@@ -249,7 +249,7 @@ BOOL MapEventIIDs(IID* piid,
int nFlags; int nFlags;
HREFTYPE hRefType; HREFTYPE hRefType;
//printf("MapEventIIDs: looking at %d class attribute impl types \n"); //printf("MapEventIIDs: looking at %d class attribute impl types \n");
for (unsigned int i = 0; i < pClassAttr->cImplTypes; i++) for (unsigned int i = 0; i < pClassAttr->cImplTypes; i++)
{ {
if (SUCCEEDED(pClassInfo->GetImplTypeFlags(i, &nFlags)) && if (SUCCEEDED(pClassInfo->GetImplTypeFlags(i, &nFlags)) &&
@@ -300,25 +300,25 @@ BOOL getClassInfoFromProgId(LPOLESTR bsProgId,LPTYPEINFO *pClassInfo)
LONG lVal; LONG lVal;
lVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("SOFTWARE"),0,KEY_READ,&keySoftware); lVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("SOFTWARE"),0,KEY_READ,&keySoftware);
if (lVal==ERROR_SUCCESS) { if (lVal==ERROR_SUCCESS) {
lVal = RegOpenKeyEx(keySoftware,_T("Classes"),0,KEY_READ,&keyClasses); lVal = RegOpenKeyEx(keySoftware,_T("Classes"),0,KEY_READ,&keyClasses);
if (lVal==ERROR_SUCCESS) { if (lVal==ERROR_SUCCESS) {
lVal = RegOpenKeyEx(keyClasses,_T("CLSID"),0,KEY_READ,&keyCLSID); lVal = RegOpenKeyEx(keyClasses,_T("CLSID"),0,KEY_READ,&keyCLSID);
if (lVal==ERROR_SUCCESS) { if (lVal==ERROR_SUCCESS) {
_TCHAR *tsProgId = W2T(bsProgId); _TCHAR *tsProgId = W2T(bsProgId);
lVal = RegOpenKeyEx(keyCLSID,tsProgId,0,KEY_READ,&keyXXXX); lVal = RegOpenKeyEx(keyCLSID,tsProgId,0,KEY_READ,&keyXXXX);
if (lVal==ERROR_SUCCESS) { if (lVal==ERROR_SUCCESS) {
lVal = RegOpenKeyEx(keyXXXX,_T("TypeLib"),0,KEY_READ,&keyTypeLib); lVal = RegOpenKeyEx(keyXXXX,_T("TypeLib"),0,KEY_READ,&keyTypeLib);
if (lVal==ERROR_SUCCESS) { if (lVal==ERROR_SUCCESS) {
lVal = RegQueryValueExA(keyTypeLib,NULL,NULL,&dwType,abData,&dwCountData); lVal = RegQueryValueExA(keyTypeLib,NULL,NULL,&dwType,abData,&dwCountData);
RegCloseKey(keyTypeLib); RegCloseKey(keyTypeLib);
} }
RegCloseKey(keyXXXX); RegCloseKey(keyXXXX);
} }
RegCloseKey(keyCLSID); RegCloseKey(keyCLSID);
} }
RegCloseKey(keyClasses); RegCloseKey(keyClasses);
} }
RegCloseKey(keySoftware); RegCloseKey(keySoftware);
} }
if (lVal!=ERROR_SUCCESS) return false; if (lVal!=ERROR_SUCCESS) return false;
BSTR bsLibId = A2BSTR((char*)abData); BSTR bsLibId = A2BSTR((char*)abData);
@@ -344,7 +344,7 @@ BOOL getClassInfoFromProgIdTypeLib(BSTR typeLib, LPOLESTR bsProgId, LPTYPEINFO *
if (FAILED(StringFromCLSID(clsid,&bsProgId))) return false; if (FAILED(StringFromCLSID(clsid,&bsProgId))) return false;
ITypeLib* pITypeLib; ITypeLib* pITypeLib;
if (FAILED(LoadTypeLib(typeLib, &pITypeLib))) return false; if (FAILED(LoadTypeLib(typeLib, &pITypeLib))) return false;
//Find ITypeInfo for coclass. //Find ITypeInfo for coclass.
pITypeLib->GetTypeInfoOfGuid(clsid, pClassInfo); pITypeLib->GetTypeInfoOfGuid(clsid, pClassInfo);
@@ -358,9 +358,9 @@ BOOL GetEventIIDForTypeLib(BSTR typeLib, IID* piid,
LPTYPEINFO pClassInfo = NULL; LPTYPEINFO pClassInfo = NULL;
if(getClassInfoFromProgIdTypeLib(typeLib, bsProgId,&pClassInfo)) if(getClassInfoFromProgIdTypeLib(typeLib, bsProgId,&pClassInfo))
{ {
if (pClassInfo == NULL){ if (pClassInfo == NULL){
printf("we had a successful return but pClassInfo is null\n"); printf("we had a successful return but pClassInfo is null\n");
} }
return MapEventIIDs(piid, mNames, mIDs, nmeth, bsProgId, pClassInfo); return MapEventIIDs(piid, mNames, mIDs, nmeth, bsProgId, pClassInfo);
} }
else else

View File

@@ -97,7 +97,7 @@ JNIEXPORT void JNICALL Java_com_jacob_com_DispatchProxy_release
IStream *ps = extractStream(env, _this); IStream *ps = extractStream(env, _this);
if (ps) { if (ps) {
ps->Release(); ps->Release();
jclass argClass = env->GetObjectClass(_this); jclass argClass = env->GetObjectClass(_this);
jfieldID ajf = env->GetFieldID( argClass, "m_pStream", "J"); jfieldID ajf = env->GetFieldID( argClass, "m_pStream", "J");
env->SetLongField(_this, ajf, 0ll); env->SetLongField(_this, ajf, 0ll);
} }

View File

@@ -48,7 +48,7 @@ JNIEXPORT jint JNICALL
Java_com_jacob_com_EnumVariant_Next(JNIEnv* env, jobject _this, jobjectArray vars) Java_com_jacob_com_EnumVariant_Next(JNIEnv* env, jobject _this, jobjectArray vars)
{ {
IEnumVARIANT* self = extractEnumVariant(env, _this); IEnumVARIANT* self = extractEnumVariant(env, _this);
//printf("self=%x\n", self); //printf("self=%x\n", self);
if(self == NULL) if(self == NULL)
return 0; return 0;

File diff suppressed because it is too large Load Diff

View File

@@ -1877,7 +1877,7 @@ JNIEXPORT void JNICALL Java_com_jacob_com_SafeArray_setString__ILjava_lang_Strin
env->ReleaseStringChars(s, str); env->ReleaseStringChars(s, str);
VariantClear(&v); VariantClear(&v);
} else if (vt == VT_BSTR) { } else if (vt == VT_BSTR) {
// SF 2847577 support unicode move from GetStringUTFChars() to GetStringChars() // SF 2847577 support unicode move from GetStringUTFChars() to GetStringChars()
const jchar *str = env->GetStringChars(s, NULL); const jchar *str = env->GetStringChars(s, NULL);
CComBSTR bs((LPCOLESTR)str); CComBSTR bs((LPCOLESTR)str);
SafeArrayPutElement(sa,&idx,bs.Detach()); SafeArrayPutElement(sa,&idx,bs.Detach());
@@ -2623,12 +2623,12 @@ JNIEXPORT void JNICALL Java_com_jacob_com_SafeArray_setVariants
} }
/* PLEASE NOTE THE LINE: /* PLEASE NOTE THE LINE:
jint *jIndices = env->GetIntArrayElements(indices, NULL); jint *jIndices = env->GetIntArrayElements(indices, NULL);
which I added to replace "long idx[2] = {i,j};" from the 2D case. which I added to replace "long idx[2] = {i,j};" from the 2D case.
Not sure if this is correct. Also, check that I am doing the null test and Not sure if this is correct. Also, check that I am doing the null test and
dimension test correctly. dimension test correctly.
Would really like to call env->ReleaseIntArrayElements(indices, jIndices, NULL); Would really like to call env->ReleaseIntArrayElements(indices, jIndices, NULL);
in here but I can't get it to work in here but I can't get it to work
*/ */
#define GETNDCODE(varType, varAccess, jtyp) \ #define GETNDCODE(varType, varAccess, jtyp) \
@@ -2669,12 +2669,12 @@ JNIEXPORT void JNICALL Java_com_jacob_com_SafeArray_setVariants
//--------------------------------- //---------------------------------
/* PLEASE NOTE THE LINE: /* PLEASE NOTE THE LINE:
jint *jIndices = env->GetIntArrayElements(indices, NULL); jint *jIndices = env->GetIntArrayElements(indices, NULL);
which I added to replace "long idx[2] = {i,j};" from the 2D case. which I added to replace "long idx[2] = {i,j};" from the 2D case.
Not sure if this is correct. Also, check that I am doing the null test and Not sure if this is correct. Also, check that I am doing the null test and
dimension test correctly. dimension test correctly.
Would really like to call env->ReleaseIntArrayElements(indices, jIndices, NULL); Would really like to call env->ReleaseIntArrayElements(indices, jIndices, NULL);
in here but I can't get it to work in here but I can't get it to work
*/ */
#define SETNDCODE(varType, varAccess) \ #define SETNDCODE(varType, varAccess) \

View File

@@ -116,26 +116,26 @@ void zeroVariant(JNIEnv *env, jobject _this)
JNIEXPORT jbyteArray JNICALL Java_com_jacob_com_Variant_SerializationWriteToBytes JNIEXPORT jbyteArray JNICALL Java_com_jacob_com_Variant_SerializationWriteToBytes
(JNIEnv *env, jobject _this){ (JNIEnv *env, jobject _this){
VARIANT *v = extractVariant(env, _this); VARIANT *v = extractVariant(env, _this);
if (v) if (v)
{ {
DWORD flags = MSHCTX_LOCAL; DWORD flags = MSHCTX_LOCAL;
jint size = VARIANT_UserSize(&flags, 0L, v); jint size = VARIANT_UserSize(&flags, 0L, v);
// allocate a byte array of the right length // allocate a byte array of the right length
jbyte* pBuf = new jbyte[size]; jbyte* pBuf = new jbyte[size];
// clear it out // clear it out
ZeroMemory(pBuf, size); ZeroMemory(pBuf, size);
// marshall the Variant into the buffer // marshall the Variant into the buffer
VARIANT_UserMarshal(&flags, (unsigned char *)pBuf, v); VARIANT_UserMarshal(&flags, (unsigned char *)pBuf, v);
// need to convert the buffer to a java byte ba[] // need to convert the buffer to a java byte ba[]
jbyteArray ba = env->NewByteArray(size); jbyteArray ba = env->NewByteArray(size);
env->SetByteArrayRegion(ba, 0, size, pBuf); env->SetByteArrayRegion(ba, 0, size, pBuf);
// and delete the original memory // and delete the original memory
delete [] pBuf; delete [] pBuf;
return ba; return ba;
} else { } else {
jbyteArray ba = env->NewByteArray(0); jbyteArray ba = env->NewByteArray(0);
return ba; return ba;
} }
} }
/** /**
@@ -148,17 +148,17 @@ JNIEXPORT void JNICALL Java_com_jacob_com_Variant_SerializationReadFromBytes
(JNIEnv *env, jobject _this, jbyteArray ba){ (JNIEnv *env, jobject _this, jbyteArray ba){
VARIANT *v = extractVariant(env, _this); VARIANT *v = extractVariant(env, _this);
if (v){ if (v){
// get a buffer from it // get a buffer from it
jbyte *pBuf = env->GetByteArrayElements(ba, 0); jbyte *pBuf = env->GetByteArrayElements(ba, 0);
// unmarshall the Variant from the buffer // unmarshall the Variant from the buffer
DWORD flags = MSHCTX_LOCAL; DWORD flags = MSHCTX_LOCAL;
printf("about to unmarshall array elements\n"); printf("about to unmarshall array elements\n");
VARIANT_UserUnmarshal(&flags, (unsigned char *)pBuf, v); VARIANT_UserUnmarshal(&flags, (unsigned char *)pBuf, v);
// release the byte array // release the byte array
printf("about to release array elements\n"); printf("about to release array elements\n");
env->ReleaseByteArrayElements(ba, pBuf, 0); env->ReleaseByteArrayElements(ba, pBuf, 0);
} }
} }
/** /**
@@ -272,13 +272,13 @@ JNIEXPORT void JNICALL Java_com_jacob_com_Variant_putVariantStringRef
if (v) { if (v) {
VariantClear(v); // whatever was there before VariantClear(v); // whatever was there before
const jchar *cStr = env->GetStringChars(s,NULL); const jchar *cStr = env->GetStringChars(s,NULL);
// SF 1314116 // SF 1314116
// DBeck: 2005-09-23: changed CComBSTR c-tor to accept // DBeck: 2005-09-23: changed CComBSTR c-tor to accept
// Unicode string (no terminating NULL) provided by GetStringChars // Unicode string (no terminating NULL) provided by GetStringChars
const jsize numChars = env->GetStringLength(s); const jsize numChars = env->GetStringLength(s);
//CComBSTR bs(cStr); //CComBSTR bs(cStr);
CComBSTR bs( numChars, (LPCOLESTR)cStr ); // SR cast SF 1689061 CComBSTR bs( numChars, (LPCOLESTR)cStr ); // SR cast SF 1689061
BSTR *pbs = (BSTR *)CoTaskMemAlloc(sizeof(BSTR)); BSTR *pbs = (BSTR *)CoTaskMemAlloc(sizeof(BSTR));
bs.CopyTo(pbs); bs.CopyTo(pbs);
@@ -802,11 +802,11 @@ JNIEXPORT void JNICALL Java_com_jacob_com_Variant_putVariantString
const jchar *cStr = env->GetStringChars(s,NULL); const jchar *cStr = env->GetStringChars(s,NULL);
// SF 1314116 // SF 1314116
// DBeck: 2005-09-23: changed CComBSTR c-tor to accept // DBeck: 2005-09-23: changed CComBSTR c-tor to accept
// Unicode string (no terminating NULL) provided by GetStringChars // Unicode string (no terminating NULL) provided by GetStringChars
const jsize numChars = env->GetStringLength(s); const jsize numChars = env->GetStringLength(s);
//CComBSTR bs(cStr); //CComBSTR bs(cStr);
CComBSTR bs( numChars, (LPCOLESTR)cStr ); // SR cast SF 1689061 CComBSTR bs( numChars, (LPCOLESTR)cStr ); // SR cast SF 1689061
V_VT(v) = VT_BSTR; V_VT(v) = VT_BSTR;
V_BSTR(v) = bs.Copy(); V_BSTR(v) = bs.Copy();
@@ -975,7 +975,7 @@ JNIEXPORT void JNICALL Java_com_jacob_com_Variant_putVariantNoParam
{ {
VARIANT *v = extractVariant(env, _this); VARIANT *v = extractVariant(env, _this);
if (v) { if (v) {
// SF 3377279 clear variable to fix leak // SF 3377279 clear variable to fix leak
VariantClear(v); VariantClear(v);
V_VT(v) = VT_ERROR; V_VT(v) = VT_ERROR;
V_ERROR(v) = DISP_E_PARAMNOTFOUND; V_ERROR(v) = DISP_E_PARAMNOTFOUND;
@@ -1041,7 +1041,7 @@ JNIEXPORT jshort JNICALL Java_com_jacob_com_Variant_getVariantType
/** /**
* this is a big cover method that returns TRUE if * this is a big cover method that returns TRUE if
* the variant type is * the variant type is
* VT_EMPTY, VT_NULL, VT_ERROR or VT_DISPATCH with no dispatch object * VT_EMPTY, VT_NULL, VT_ERROR or VT_DISPATCH with no dispatch object
* */ * */
JNIEXPORT jboolean JNICALL Java_com_jacob_com_Variant_isVariantConsideredNull JNIEXPORT jboolean JNICALL Java_com_jacob_com_Variant_isVariantConsideredNull
(JNIEnv *env, jobject _this) (JNIEnv *env, jobject _this)
@@ -1110,14 +1110,14 @@ JNIEXPORT jlong JNICALL Java_com_jacob_com_Variant_getVariantVariant
return NULL; return NULL;
} }
VARIANT *refVar = V_VARIANTREF(v); VARIANT *refVar = V_VARIANTREF(v);
// we could have made a copy of refV here but we aren't every going to free // we could have made a copy of refV here but we aren't every going to free
// it outside of the scope of the enclosing context so we will just used the // it outside of the scope of the enclosing context so we will just used the
// enclosed. This relies on the java layer to zero out its ref to this // enclosed. This relies on the java layer to zero out its ref to this
// enclosed variant before the gc can come along and free the memory out from // enclosed variant before the gc can come along and free the memory out from
// under this enclosing variant. // under this enclosing variant.
return (jlong)refVar; return (jlong)refVar;
} }
return NULL; return NULL;
@@ -1136,9 +1136,9 @@ JNIEXPORT jlong JNICALL Java_com_jacob_com_Variant_getVariantVariant
DECIMAL *pd = (DECIMAL *)CoTaskMemAlloc(sizeof(DECIMAL)); DECIMAL *pd = (DECIMAL *)CoTaskMemAlloc(sizeof(DECIMAL));
pd->scale = scale; pd->scale = scale;
if (signum == 1 || signum == 0){ if (signum == 1 || signum == 0){
pd->sign = 0; pd->sign = 0;
} else { } else {
pd->sign = 0x80; pd->sign = 0x80;
} }
pd->Hi32 = hi; pd->Hi32 = hi;
pd->Mid32 = mid; pd->Mid32 = mid;
@@ -1163,9 +1163,9 @@ JNIEXPORT jlong JNICALL Java_com_jacob_com_Variant_getVariantVariant
d = (DECIMAL*)v; d = (DECIMAL*)v;
d->scale = scale; d->scale = scale;
if (signum == 1 || signum == 0){ if (signum == 1 || signum == 0){
d->sign = 0; d->sign = 0;
} else { } else {
d->sign = 0x80; d->sign = 0x80;
} }
d->Hi32 = hi; d->Hi32 = hi;
d->Mid32 = mid; d->Mid32 = mid;

View File

@@ -37,7 +37,7 @@ void ThrowComFail(JNIEnv *env, const char* desc, jint hr)
jmethodID failCons = jmethodID failCons =
env->GetMethodID(failClass, "<init>", "(ILjava/lang/String;)V"); env->GetMethodID(failClass, "<init>", "(ILjava/lang/String;)V");
if (!desc) { if (!desc) {
desc = "Java/COM Error"; desc = "Java/COM Error";
} }
jstring js = env->NewStringUTF(desc); jstring js = env->NewStringUTF(desc);
jthrowable fail = (jthrowable)env->NewObject(failClass, failCons, hr, js); jthrowable fail = (jthrowable)env->NewObject(failClass, failCons, hr, js);
@@ -47,7 +47,7 @@ void ThrowComFail(JNIEnv *env, const char* desc, jint hr)
void ThrowComFailUnicode(JNIEnv *env, const wchar_t* desc, jint hr) void ThrowComFailUnicode(JNIEnv *env, const wchar_t* desc, jint hr)
{ {
if (!desc) { if (!desc) {
ThrowComFail(env, "Java/COM Error", hr); ThrowComFail(env, "Java/COM Error", hr);
} }
jclass failClass = env->FindClass("com/jacob/com/ComFailException"); jclass failClass = env->FindClass("com/jacob/com/ComFailException");
// call the constructor that takes hr and message // call the constructor that takes hr and message
@@ -67,9 +67,9 @@ int CheckEnv(JNIEnv *env1, JNIEnv *env2)
jmethodID failCons = jmethodID failCons =
env1->GetMethodID(failClass, "<init>", "()V"); env1->GetMethodID(failClass, "<init>", "()V");
env1->ThrowNew(failClass, "Wrong Thread"); env1->ThrowNew(failClass, "Wrong Thread");
return 0; return 0;
} }
return 1; return 1;
} }
} }

View File

@@ -87,7 +87,7 @@ JNIEXPORT jobject JNICALL Java_com_jacob_com_Dispatch_invokev
* Signature: (Ljava/lang/Object;I;)I * Signature: (Ljava/lang/Object;I;)I
*/ */
JNIEXPORT jint JNICALL Java_com_jacob_com_Dispatch_hasExited JNIEXPORT jint JNICALL Java_com_jacob_com_Dispatch_hasExited
(JNIEnv *, jclass, jobject, jint, jint); (JNIEnv *, jclass, jobject, jint, jint);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@@ -37,13 +37,13 @@ class EventProxy : public IDispatch
{ {
private: private:
int connected; int connected;
LONG m_cRef; // a reference counter LONG m_cRef; // a reference counter
CComPtr<IConnectionPoint> pCP; // the connection point CComPtr<IConnectionPoint> pCP; // the connection point
DWORD dwEventCookie; // connection point cookie DWORD dwEventCookie; // connection point cookie
jobject javaSinkObj; // the java object to delegate calls jobject javaSinkObj; // the java object to delegate calls
IID eventIID; // the interface iid passed in IID eventIID; // the interface iid passed in
int MethNum; // number of methods in the callback interface int MethNum; // number of methods in the callback interface
CComBSTR *MethName; // Array of method names CComBSTR *MethName; // Array of method names
DISPID *MethID; // Array of method ids, used to match invokations to method names DISPID *MethID; // Array of method ids, used to match invokations to method names
JavaVM *jvm; // The java vm we are running JavaVM *jvm; // The java vm we are running
@@ -53,7 +53,7 @@ public:
// constuct with a global JNI ref to a sink object // constuct with a global JNI ref to a sink object
// to which we will delegate event callbacks // to which we will delegate event callbacks
EventProxy(JNIEnv *jenv, EventProxy(JNIEnv *jenv,
jobject aSinkObj, jobject aSinkObj,
CComPtr<IConnectionPoint> pConn, CComPtr<IConnectionPoint> pConn,
IID eventIID, IID eventIID,
CComBSTR *mName, CComBSTR *mName,
@@ -72,7 +72,7 @@ public:
{ {
LONG res = InterlockedDecrement(&m_cRef); LONG res = InterlockedDecrement(&m_cRef);
if (res == 0) { if (res == 0) {
delete this; delete this;
} }
return res; return res;

File diff suppressed because it is too large Load Diff

View File

@@ -29,23 +29,23 @@ namespace ATL
inline errno_t AtlCrtErrorCheck(_In_ errno_t nError) inline errno_t AtlCrtErrorCheck(_In_ errno_t nError)
{ {
switch(nError) switch(nError)
{ {
case ENOMEM: case ENOMEM:
AtlThrow(E_OUTOFMEMORY); AtlThrow(E_OUTOFMEMORY);
break; break;
case EINVAL: case EINVAL:
case ERANGE: case ERANGE:
AtlThrow(E_INVALIDARG); AtlThrow(E_INVALIDARG);
break; break;
case 0: case 0:
case STRUNCATE: case STRUNCATE:
break; break;
default: default:
AtlThrow(E_FAIL); AtlThrow(E_FAIL);
break; break;
} }
return nError; return nError;
} }
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
@@ -61,331 +61,331 @@ namespace Checked
#endif #endif
inline void __cdecl memcpy_s( inline void __cdecl memcpy_s(
_Out_bytecap_post_bytecount_(_S1max,_N) void *_S1, _Out_bytecap_post_bytecount_(_S1max,_N) void *_S1,
_In_ size_t _S1max, _In_ size_t _S1max,
_In_bytecount_(_N) const void *_S2, _In_bytecount_(_N) const void *_S2,
_In_ size_t _N) _In_ size_t _N)
{ {
ATLMFC_CRT_ERRORCHECK(::memcpy_s(_S1, _S1max, _S2, _N)); ATLMFC_CRT_ERRORCHECK(::memcpy_s(_S1, _S1max, _S2, _N));
} }
inline void __cdecl wmemcpy_s( inline void __cdecl wmemcpy_s(
_Out_cap_post_count_(_N1,_N) wchar_t *_S1, _Out_cap_post_count_(_N1,_N) wchar_t *_S1,
_In_ size_t _N1, _In_ size_t _N1,
_In_count_(_N) const wchar_t *_S2, _In_count_(_N) const wchar_t *_S2,
_In_ size_t _N) _In_ size_t _N)
{ {
ATLMFC_CRT_ERRORCHECK(::wmemcpy_s(_S1, _N1, _S2, _N)); ATLMFC_CRT_ERRORCHECK(::wmemcpy_s(_S1, _N1, _S2, _N));
} }
inline void __cdecl memmove_s( inline void __cdecl memmove_s(
_Out_bytecap_post_bytecount_(_S1max,_N) void *_S1, _Out_bytecap_post_bytecount_(_S1max,_N) void *_S1,
_In_ size_t _S1max, _In_ size_t _S1max,
_In_bytecount_(_N) const void *_S2, _In_bytecount_(_N) const void *_S2,
_In_ size_t _N) _In_ size_t _N)
{ {
ATLMFC_CRT_ERRORCHECK(::memmove_s(_S1, _S1max, _S2, _N)); ATLMFC_CRT_ERRORCHECK(::memmove_s(_S1, _S1max, _S2, _N));
} }
inline void __cdecl strcpy_s( inline void __cdecl strcpy_s(
_Out_z_cap_(_S1max) char *_S1, _Out_z_cap_(_S1max) char *_S1,
_In_ size_t _S1max, _In_ size_t _S1max,
_In_z_ const char *_S2) _In_z_ const char *_S2)
{ {
ATLMFC_CRT_ERRORCHECK(::strcpy_s(_S1, _S1max, _S2)); ATLMFC_CRT_ERRORCHECK(::strcpy_s(_S1, _S1max, _S2));
} }
inline void __cdecl wcscpy_s( inline void __cdecl wcscpy_s(
_Out_z_cap_(_S1max) wchar_t *_S1, _Out_z_cap_(_S1max) wchar_t *_S1,
_In_ size_t _S1max, _In_ size_t _S1max,
_In_z_ const wchar_t *_S2) _In_z_ const wchar_t *_S2)
{ {
ATLMFC_CRT_ERRORCHECK(::wcscpy_s(_S1, _S1max, _S2)); ATLMFC_CRT_ERRORCHECK(::wcscpy_s(_S1, _S1max, _S2));
} }
inline void __cdecl tcscpy_s( inline void __cdecl tcscpy_s(
_Out_z_cap_(_SizeInChars) TCHAR * _Dst, _Out_z_cap_(_SizeInChars) TCHAR * _Dst,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_z_ const TCHAR * _Src) _In_z_ const TCHAR * _Src)
{ {
ATLMFC_CRT_ERRORCHECK(::_tcscpy_s(_Dst, _SizeInChars, _Src)); ATLMFC_CRT_ERRORCHECK(::_tcscpy_s(_Dst, _SizeInChars, _Src));
} }
inline errno_t __cdecl strncpy_s( inline errno_t __cdecl strncpy_s(
_Out_z_cap_(_SizeInChars) char *_Dest, _Out_z_cap_(_SizeInChars) char *_Dest,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_z_ const char *_Source, _In_z_ const char *_Source,
_In_ size_t _Count) _In_ size_t _Count)
{ {
return ATLMFC_CRT_ERRORCHECK(::strncpy_s(_Dest, _SizeInChars, _Source,_Count)); return ATLMFC_CRT_ERRORCHECK(::strncpy_s(_Dest, _SizeInChars, _Source,_Count));
} }
inline errno_t __cdecl wcsncpy_s( inline errno_t __cdecl wcsncpy_s(
_Out_z_cap_(_SizeInChars) wchar_t *_Dest, _Out_z_cap_(_SizeInChars) wchar_t *_Dest,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_z_ const wchar_t *_Source, _In_z_ const wchar_t *_Source,
_In_ size_t _Count) _In_ size_t _Count)
{ {
return ATLMFC_CRT_ERRORCHECK(::wcsncpy_s(_Dest, _SizeInChars, _Source,_Count)); return ATLMFC_CRT_ERRORCHECK(::wcsncpy_s(_Dest, _SizeInChars, _Source,_Count));
} }
inline errno_t __cdecl tcsncpy_s( inline errno_t __cdecl tcsncpy_s(
_Out_z_cap_(_SizeInChars) TCHAR *_Dest, _Out_z_cap_(_SizeInChars) TCHAR *_Dest,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_z_ const TCHAR *_Source, _In_z_ const TCHAR *_Source,
_In_ size_t _Count) _In_ size_t _Count)
{ {
return ATLMFC_CRT_ERRORCHECK(::_tcsncpy_s(_Dest, _SizeInChars, _Source,_Count)); return ATLMFC_CRT_ERRORCHECK(::_tcsncpy_s(_Dest, _SizeInChars, _Source,_Count));
} }
inline void __cdecl strcat_s( inline void __cdecl strcat_s(
_Inout_z_cap_(_SizeInChars) char * _Dst, _Inout_z_cap_(_SizeInChars) char * _Dst,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_z_ const char * _Src) _In_z_ const char * _Src)
{ {
ATLMFC_CRT_ERRORCHECK(::strcat_s(_Dst, _SizeInChars, _Src)); ATLMFC_CRT_ERRORCHECK(::strcat_s(_Dst, _SizeInChars, _Src));
} }
inline void __cdecl wcscat_s( inline void __cdecl wcscat_s(
_Inout_z_cap_(_SizeInChars) wchar_t * _Dst, _Inout_z_cap_(_SizeInChars) wchar_t * _Dst,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_z_ const wchar_t * _Src) _In_z_ const wchar_t * _Src)
{ {
ATLMFC_CRT_ERRORCHECK(::wcscat_s(_Dst, _SizeInChars, _Src)); ATLMFC_CRT_ERRORCHECK(::wcscat_s(_Dst, _SizeInChars, _Src));
} }
inline void __cdecl tcscat_s( inline void __cdecl tcscat_s(
_Inout_z_cap_(_SizeInChars) TCHAR * _Dst, _Inout_z_cap_(_SizeInChars) TCHAR * _Dst,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_z_ const TCHAR * _Src) _In_z_ const TCHAR * _Src)
{ {
ATLMFC_CRT_ERRORCHECK(::_tcscat_s(_Dst, _SizeInChars, _Src)); ATLMFC_CRT_ERRORCHECK(::_tcscat_s(_Dst, _SizeInChars, _Src));
} }
inline void __cdecl strlwr_s( inline void __cdecl strlwr_s(
_Inout_z_cap_(_SizeInChars) char * _Str, _Inout_z_cap_(_SizeInChars) char * _Str,
_In_ size_t _SizeInChars) _In_ size_t _SizeInChars)
{ {
ATLMFC_CRT_ERRORCHECK(::_strlwr_s(_Str, _SizeInChars)); ATLMFC_CRT_ERRORCHECK(::_strlwr_s(_Str, _SizeInChars));
} }
inline void __cdecl wcslwr_s( inline void __cdecl wcslwr_s(
_Inout_z_cap_(_SizeInChars) wchar_t * _Str, _Inout_z_cap_(_SizeInChars) wchar_t * _Str,
_In_ size_t _SizeInChars) _In_ size_t _SizeInChars)
{ {
ATLMFC_CRT_ERRORCHECK(::_wcslwr_s(_Str, _SizeInChars)); ATLMFC_CRT_ERRORCHECK(::_wcslwr_s(_Str, _SizeInChars));
} }
inline void __cdecl mbslwr_s( inline void __cdecl mbslwr_s(
_Inout_z_bytecap_(_SizeInChars) unsigned char * _Str, _Inout_z_bytecap_(_SizeInChars) unsigned char * _Str,
_In_ size_t _SizeInChars) _In_ size_t _SizeInChars)
{ {
ATLMFC_CRT_ERRORCHECK(::_mbslwr_s(_Str, _SizeInChars)); ATLMFC_CRT_ERRORCHECK(::_mbslwr_s(_Str, _SizeInChars));
} }
inline void __cdecl tcslwr_s( inline void __cdecl tcslwr_s(
_Inout_z_cap_(_SizeInChars) TCHAR * _Str, _Inout_z_cap_(_SizeInChars) TCHAR * _Str,
_In_ size_t _SizeInChars) _In_ size_t _SizeInChars)
{ {
ATLMFC_CRT_ERRORCHECK(::_tcslwr_s(_Str, _SizeInChars)); ATLMFC_CRT_ERRORCHECK(::_tcslwr_s(_Str, _SizeInChars));
} }
inline void __cdecl strupr_s( inline void __cdecl strupr_s(
_Inout_z_cap_(_SizeInChars) char * _Str, _Inout_z_cap_(_SizeInChars) char * _Str,
_In_ size_t _SizeInChars) _In_ size_t _SizeInChars)
{ {
ATLMFC_CRT_ERRORCHECK(::_strupr_s(_Str, _SizeInChars)); ATLMFC_CRT_ERRORCHECK(::_strupr_s(_Str, _SizeInChars));
} }
inline void __cdecl wcsupr_s( inline void __cdecl wcsupr_s(
_Inout_z_cap_(_SizeInChars) wchar_t * _Str, _Inout_z_cap_(_SizeInChars) wchar_t * _Str,
_In_ size_t _SizeInChars) _In_ size_t _SizeInChars)
{ {
ATLMFC_CRT_ERRORCHECK(::_wcsupr_s(_Str, _SizeInChars)); ATLMFC_CRT_ERRORCHECK(::_wcsupr_s(_Str, _SizeInChars));
} }
inline void __cdecl mbsupr_s( inline void __cdecl mbsupr_s(
_Inout_z_bytecap_(_SizeInChars) unsigned char * _Str, _Inout_z_bytecap_(_SizeInChars) unsigned char * _Str,
_In_ size_t _SizeInChars) _In_ size_t _SizeInChars)
{ {
ATLMFC_CRT_ERRORCHECK(::_mbsupr_s(_Str, _SizeInChars)); ATLMFC_CRT_ERRORCHECK(::_mbsupr_s(_Str, _SizeInChars));
} }
inline void __cdecl tcsupr_s( inline void __cdecl tcsupr_s(
_Inout_z_cap_(_SizeInChars) TCHAR * _Str, _Inout_z_cap_(_SizeInChars) TCHAR * _Str,
_In_ size_t _SizeInChars) _In_ size_t _SizeInChars)
{ {
ATLMFC_CRT_ERRORCHECK(::_tcsupr_s(_Str, _SizeInChars)); ATLMFC_CRT_ERRORCHECK(::_tcsupr_s(_Str, _SizeInChars));
} }
inline void __cdecl itoa_s( inline void __cdecl itoa_s(
_In_ int _Val, _In_ int _Val,
_Out_z_cap_(_SizeInChars) char *_Buf, _Out_z_cap_(_SizeInChars) char *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_itoa_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_itoa_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl itot_s( inline void __cdecl itot_s(
_In_ int _Val, _In_ int _Val,
_Out_z_cap_(_SizeInChars) TCHAR *_Buf, _Out_z_cap_(_SizeInChars) TCHAR *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_itot_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_itot_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl ltoa_s( inline void __cdecl ltoa_s(
_In_ long _Val, _In_ long _Val,
_Out_z_cap_(_SizeInChars) char *_Buf, _Out_z_cap_(_SizeInChars) char *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_ltoa_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_ltoa_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl ltot_s( inline void __cdecl ltot_s(
_In_ long _Val, _In_ long _Val,
_Out_z_cap_(_SizeInChars) TCHAR *_Buf, _Out_z_cap_(_SizeInChars) TCHAR *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_ltot_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_ltot_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl ultoa_s( inline void __cdecl ultoa_s(
_In_ unsigned long _Val, _In_ unsigned long _Val,
_Out_z_cap_(_SizeInChars) char *_Buf, _Out_z_cap_(_SizeInChars) char *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_ultoa_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_ultoa_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl ultow_s( inline void __cdecl ultow_s(
_In_ unsigned long _Val, _In_ unsigned long _Val,
_Out_z_cap_(_SizeInChars) wchar_t *_Buf, _Out_z_cap_(_SizeInChars) wchar_t *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_ultow_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_ultow_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl ultot_s( inline void __cdecl ultot_s(
_In_ unsigned long _Val, _In_ unsigned long _Val,
_Out_z_cap_(_SizeInChars) TCHAR *_Buf, _Out_z_cap_(_SizeInChars) TCHAR *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_ultot_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_ultot_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl i64toa_s( inline void __cdecl i64toa_s(
_In_ __int64 _Val, _In_ __int64 _Val,
_Out_z_cap_(_SizeInChars) char *_Buf, _Out_z_cap_(_SizeInChars) char *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_i64toa_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_i64toa_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl i64tow_s( inline void __cdecl i64tow_s(
_In_ __int64 _Val, _In_ __int64 _Val,
_Out_z_cap_(_SizeInChars) wchar_t *_Buf, _Out_z_cap_(_SizeInChars) wchar_t *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_i64tow_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_i64tow_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl ui64toa_s( inline void __cdecl ui64toa_s(
_In_ unsigned __int64 _Val, _In_ unsigned __int64 _Val,
_Out_z_cap_(_SizeInChars) char *_Buf, _Out_z_cap_(_SizeInChars) char *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_ui64toa_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_ui64toa_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl ui64tow_s( inline void __cdecl ui64tow_s(
_In_ unsigned __int64 _Val, _In_ unsigned __int64 _Val,
_Out_z_cap_(_SizeInChars) wchar_t *_Buf, _Out_z_cap_(_SizeInChars) wchar_t *_Buf,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ int _Radix) _In_ int _Radix)
{ {
ATLMFC_CRT_ERRORCHECK(::_ui64tow_s(_Val, _Buf, _SizeInChars, _Radix)); ATLMFC_CRT_ERRORCHECK(::_ui64tow_s(_Val, _Buf, _SizeInChars, _Radix));
} }
inline void __cdecl gcvt_s( inline void __cdecl gcvt_s(
_Out_z_cap_(_SizeInChars) char *_Buffer, _Out_z_cap_(_SizeInChars) char *_Buffer,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_ double _Value, _In_ double _Value,
_In_ int _Ndec) _In_ int _Ndec)
{ {
ATLMFC_CRT_ERRORCHECK(::_gcvt_s(_Buffer, _SizeInChars, _Value, _Ndec)); ATLMFC_CRT_ERRORCHECK(::_gcvt_s(_Buffer, _SizeInChars, _Value, _Ndec));
} }
inline void __cdecl tsplitpath_s( inline void __cdecl tsplitpath_s(
_In_z_ const TCHAR *_Path, _In_z_ const TCHAR *_Path,
_Out_opt_z_cap_(_Drive_len) TCHAR *_Drive, _Out_opt_z_cap_(_Drive_len) TCHAR *_Drive,
_In_ size_t _Drive_len, _In_ size_t _Drive_len,
_Out_opt_z_cap_(_Dir_len) TCHAR *_Dir, _Out_opt_z_cap_(_Dir_len) TCHAR *_Dir,
_In_ size_t _Dir_len, _In_ size_t _Dir_len,
_Out_opt_z_cap_(_Fname_len) TCHAR *_Fname, _Out_opt_z_cap_(_Fname_len) TCHAR *_Fname,
_In_ size_t _Fname_len, _In_ size_t _Fname_len,
_Out_opt_z_cap_(_Ext_len) TCHAR *_Ext, _Out_opt_z_cap_(_Ext_len) TCHAR *_Ext,
_In_ size_t _Ext_len) _In_ size_t _Ext_len)
{ {
ATLMFC_CRT_ERRORCHECK(::_tsplitpath_s(_Path, _Drive, _Drive_len, _Dir, _Dir_len, _Fname, _Fname_len, _Ext, _Ext_len)); ATLMFC_CRT_ERRORCHECK(::_tsplitpath_s(_Path, _Drive, _Drive_len, _Dir, _Dir_len, _Fname, _Fname_len, _Ext, _Ext_len));
} }
inline void __cdecl tmakepath_s( inline void __cdecl tmakepath_s(
_Out_z_cap_(_SizeInChars) TCHAR *_Path, _Out_z_cap_(_SizeInChars) TCHAR *_Path,
_In_ size_t _SizeInChars, _In_ size_t _SizeInChars,
_In_z_ const TCHAR *_Drive, _In_z_ const TCHAR *_Drive,
_In_z_ const TCHAR *_Dir, _In_z_ const TCHAR *_Dir,
_In_z_ const TCHAR *_Fname, _In_z_ const TCHAR *_Fname,
_In_z_ const TCHAR *_Ext) _In_z_ const TCHAR *_Ext)
{ {
ATLMFC_CRT_ERRORCHECK(::_tmakepath_s(_Path, _SizeInChars, _Drive, _Dir, _Fname, _Ext)); ATLMFC_CRT_ERRORCHECK(::_tmakepath_s(_Path, _SizeInChars, _Drive, _Dir, _Fname, _Ext));
} }
inline size_t __cdecl strnlen( inline size_t __cdecl strnlen(
_In_z_count_(_Maxsize) const char *_Str, _In_z_count_(_Maxsize) const char *_Str,
_In_ size_t _Maxsize) _In_ size_t _Maxsize)
{ {
return ::strnlen(_Str, _Maxsize); return ::strnlen(_Str, _Maxsize);
} }
inline size_t __cdecl wcsnlen( inline size_t __cdecl wcsnlen(
_In_z_count_(_Maxsize) const wchar_t *_Wcs, _In_z_count_(_Maxsize) const wchar_t *_Wcs,
_In_ size_t _Maxsize) _In_ size_t _Maxsize)
{ {
return ::wcsnlen(_Wcs, _Maxsize); return ::wcsnlen(_Wcs, _Maxsize);
} }
inline size_t __cdecl tcsnlen( inline size_t __cdecl tcsnlen(
_In_z_count_(_Maxsize) const TCHAR *_Str, _In_z_count_(_Maxsize) const TCHAR *_Str,
_In_ size_t _Maxsize) _In_ size_t _Maxsize)
{ {
return ::_tcsnlen(_Str, _Maxsize); return ::_tcsnlen(_Str, _Maxsize);
} }
inline int get_errno() throw() inline int get_errno() throw()
{ {
int nErrNo=0; int nErrNo=0;
errno_t nErrCall=::_get_errno(&nErrNo); errno_t nErrCall=::_get_errno(&nErrNo);
if(nErrCall) if(nErrCall)
{ {
return nErrCall; return nErrCall;
} }
return nErrNo; return nErrNo;
} }
inline void set_errno(_In_ int _Value) inline void set_errno(_In_ int _Value)
{ {
ATLMFC_CRT_ERRORCHECK(::_set_errno(_Value)); ATLMFC_CRT_ERRORCHECK(::_set_errno(_Value));
} }
} // namespace Checked } // namespace Checked

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -41,41 +41,41 @@ namespace ATL
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Verify that a null-terminated string points to valid memory // Verify that a null-terminated string points to valid memory
inline BOOL AtlIsValidString( inline BOOL AtlIsValidString(
_In_z_count_(nMaxLength) LPCWSTR psz, _In_z_count_(nMaxLength) LPCWSTR psz,
_In_ size_t nMaxLength = INT_MAX) _In_ size_t nMaxLength = INT_MAX)
{ {
(nMaxLength); (nMaxLength);
return (psz != NULL); return (psz != NULL);
} }
// Verify that a null-terminated string points to valid memory // Verify that a null-terminated string points to valid memory
inline BOOL AtlIsValidString( inline BOOL AtlIsValidString(
_In_z_count_(nMaxLength) LPCSTR psz, _In_z_count_(nMaxLength) LPCSTR psz,
_In_ size_t nMaxLength = UINT_MAX) _In_ size_t nMaxLength = UINT_MAX)
{ {
(nMaxLength); (nMaxLength);
return (psz != NULL); return (psz != NULL);
} }
// Verify that a pointer points to valid memory // Verify that a pointer points to valid memory
inline BOOL AtlIsValidAddress( inline BOOL AtlIsValidAddress(
_In_opt_bytecount_(nBytes) const void* p, _In_opt_bytecount_(nBytes) const void* p,
_In_ size_t nBytes, _In_ size_t nBytes,
_In_ BOOL bReadWrite = TRUE) _In_ BOOL bReadWrite = TRUE)
{ {
(bReadWrite); (bReadWrite);
(nBytes); (nBytes);
return (p != NULL); return (p != NULL);
} }
template<typename T> template<typename T>
inline void AtlAssertValidObject( inline void AtlAssertValidObject(
_In_opt_ _Prepost_opt_bytecount_x_(sizeof(T)) const T *pOb) _In_opt_ _Prepost_opt_bytecount_x_(sizeof(T)) const T *pOb)
{ {
ATLASSERT(pOb); ATLASSERT(pOb);
ATLASSERT(AtlIsValidAddress(pOb, sizeof(T))); ATLASSERT(AtlIsValidAddress(pOb, sizeof(T)));
if(pOb) if(pOb)
pOb->AssertValid(); pOb->AssertValid();
} }
#ifdef _DEBUG #ifdef _DEBUG
#define ATLASSERT_VALID(x) ATL::AtlAssertValidObject(x) #define ATLASSERT_VALID(x) ATL::AtlAssertValidObject(x)
@@ -87,143 +87,143 @@ inline void AtlAssertValidObject(
class CComCriticalSection class CComCriticalSection
{ {
public: public:
CComCriticalSection() throw() CComCriticalSection() throw()
{ {
memset(&m_sec, 0, sizeof(CRITICAL_SECTION)); memset(&m_sec, 0, sizeof(CRITICAL_SECTION));
} }
~CComCriticalSection() ~CComCriticalSection()
{ {
} }
HRESULT Lock() throw() HRESULT Lock() throw()
{ {
EnterCriticalSection(&m_sec); EnterCriticalSection(&m_sec);
return S_OK; return S_OK;
} }
HRESULT Unlock() throw() HRESULT Unlock() throw()
{ {
LeaveCriticalSection(&m_sec); LeaveCriticalSection(&m_sec);
return S_OK; return S_OK;
} }
HRESULT Init() throw() HRESULT Init() throw()
{ {
HRESULT hRes = S_OK; HRESULT hRes = S_OK;
if (!InitializeCriticalSectionAndSpinCount(&m_sec, 0)) if (!InitializeCriticalSectionAndSpinCount(&m_sec, 0))
{ {
hRes = HRESULT_FROM_WIN32(GetLastError()); hRes = HRESULT_FROM_WIN32(GetLastError());
} }
return hRes; return hRes;
} }
HRESULT Term() throw() HRESULT Term() throw()
{ {
DeleteCriticalSection(&m_sec); DeleteCriticalSection(&m_sec);
return S_OK; return S_OK;
} }
CRITICAL_SECTION m_sec; CRITICAL_SECTION m_sec;
}; };
class CComAutoCriticalSection : class CComAutoCriticalSection :
public CComCriticalSection public CComCriticalSection
{ {
public: public:
CComAutoCriticalSection() CComAutoCriticalSection()
{ {
HRESULT hr = CComCriticalSection::Init(); HRESULT hr = CComCriticalSection::Init();
if (FAILED(hr)) if (FAILED(hr))
AtlThrow(hr); AtlThrow(hr);
} }
~CComAutoCriticalSection() throw() ~CComAutoCriticalSection() throw()
{ {
CComCriticalSection::Term(); CComCriticalSection::Term();
} }
private : private :
HRESULT Init(); // Not implemented. CComAutoCriticalSection::Init should never be called HRESULT Init(); // Not implemented. CComAutoCriticalSection::Init should never be called
HRESULT Term(); // Not implemented. CComAutoCriticalSection::Term should never be called HRESULT Term(); // Not implemented. CComAutoCriticalSection::Term should never be called
}; };
class CComSafeDeleteCriticalSection : class CComSafeDeleteCriticalSection :
public CComCriticalSection public CComCriticalSection
{ {
public: public:
CComSafeDeleteCriticalSection(): m_bInitialized(false) CComSafeDeleteCriticalSection(): m_bInitialized(false)
{ {
} }
~CComSafeDeleteCriticalSection() throw() ~CComSafeDeleteCriticalSection() throw()
{ {
if (!m_bInitialized) if (!m_bInitialized)
{ {
return; return;
} }
m_bInitialized = false; m_bInitialized = false;
CComCriticalSection::Term(); CComCriticalSection::Term();
} }
HRESULT Init() throw() HRESULT Init() throw()
{ {
ATLASSERT( !m_bInitialized ); ATLASSERT( !m_bInitialized );
HRESULT hr = CComCriticalSection::Init(); HRESULT hr = CComCriticalSection::Init();
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
m_bInitialized = true; m_bInitialized = true;
} }
return hr; return hr;
} }
HRESULT Term() throw() HRESULT Term() throw()
{ {
if (!m_bInitialized) if (!m_bInitialized)
{ {
return S_OK; return S_OK;
} }
m_bInitialized = false; m_bInitialized = false;
return CComCriticalSection::Term(); return CComCriticalSection::Term();
} }
HRESULT Lock() HRESULT Lock()
{ {
// CComSafeDeleteCriticalSection::Init or CComAutoDeleteCriticalSection::Init // CComSafeDeleteCriticalSection::Init or CComAutoDeleteCriticalSection::Init
// not called or failed. // not called or failed.
// m_critsec member of CComObjectRootEx is now of type // m_critsec member of CComObjectRootEx is now of type
// CComAutoDeleteCriticalSection. It has to be initialized // CComAutoDeleteCriticalSection. It has to be initialized
// by calling CComObjectRootEx::_AtlInitialConstruct // by calling CComObjectRootEx::_AtlInitialConstruct
ATLASSUME(m_bInitialized); ATLASSUME(m_bInitialized);
return CComCriticalSection::Lock(); return CComCriticalSection::Lock();
} }
private: private:
bool m_bInitialized; bool m_bInitialized;
}; };
class CComAutoDeleteCriticalSection : class CComAutoDeleteCriticalSection :
public CComSafeDeleteCriticalSection public CComSafeDeleteCriticalSection
{ {
private: private:
// CComAutoDeleteCriticalSection::Term should never be called // CComAutoDeleteCriticalSection::Term should never be called
HRESULT Term() throw(); HRESULT Term() throw();
}; };
class CComFakeCriticalSection class CComFakeCriticalSection
{ {
public: public:
HRESULT Lock() throw() HRESULT Lock() throw()
{ {
return S_OK; return S_OK;
} }
HRESULT Unlock() throw() HRESULT Unlock() throw()
{ {
return S_OK; return S_OK;
} }
HRESULT Init() throw() HRESULT Init() throw()
{ {
return S_OK; return S_OK;
} }
HRESULT Term() throw() HRESULT Term() throw()
{ {
return S_OK; return S_OK;
} }
}; };
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
@@ -232,40 +232,40 @@ public:
// Used by any project that uses ATL // Used by any project that uses ATL
struct _ATL_BASE_MODULE70 struct _ATL_BASE_MODULE70
{ {
UINT cbSize; UINT cbSize;
HINSTANCE m_hInst; HINSTANCE m_hInst;
HINSTANCE m_hInstResource; HINSTANCE m_hInstResource;
DWORD dwAtlBuildVer; DWORD dwAtlBuildVer;
const GUID* pguidVer; const GUID* pguidVer;
CComCriticalSection m_csResource; CComCriticalSection m_csResource;
CSimpleArray<HINSTANCE> m_rgResourceInstance; CSimpleArray<HINSTANCE> m_rgResourceInstance;
}; };
typedef _ATL_BASE_MODULE70 _ATL_BASE_MODULE; typedef _ATL_BASE_MODULE70 _ATL_BASE_MODULE;
class CAtlBaseModule : class CAtlBaseModule :
public _ATL_BASE_MODULE public _ATL_BASE_MODULE
{ {
public : public :
static bool m_bInitFailed; static bool m_bInitFailed;
CAtlBaseModule() throw(); CAtlBaseModule() throw();
~CAtlBaseModule() throw (); ~CAtlBaseModule() throw ();
HINSTANCE GetModuleInstance() throw() HINSTANCE GetModuleInstance() throw()
{ {
return m_hInst; return m_hInst;
} }
HINSTANCE GetResourceInstance() throw() HINSTANCE GetResourceInstance() throw()
{ {
return m_hInstResource; return m_hInstResource;
} }
HINSTANCE SetResourceInstance(_In_ HINSTANCE hInst) throw() HINSTANCE SetResourceInstance(_In_ HINSTANCE hInst) throw()
{ {
return static_cast< HINSTANCE >(InterlockedExchangePointer((void**)&m_hInstResource, hInst)); return static_cast< HINSTANCE >(InterlockedExchangePointer((void**)&m_hInstResource, hInst));
} }
bool AddResourceInstance(_In_ HINSTANCE hInst) throw(); bool AddResourceInstance(_In_ HINSTANCE hInst) throw();
bool RemoveResourceInstance(_In_ HINSTANCE hInst) throw(); bool RemoveResourceInstance(_In_ HINSTANCE hInst) throw();
HINSTANCE GetHInstanceAt(_In_ int i) throw(); HINSTANCE GetHInstanceAt(_In_ int i) throw();
}; };
__declspec(selectany) bool CAtlBaseModule::m_bInitFailed = false; __declspec(selectany) bool CAtlBaseModule::m_bInitFailed = false;
@@ -276,199 +276,199 @@ extern CAtlBaseModule _AtlBaseModule;
#pragma warning(push) #pragma warning(push)
#pragma warning(disable: 4200) #pragma warning(disable: 4200)
struct ATLSTRINGRESOURCEIMAGE struct ATLSTRINGRESOURCEIMAGE
{ {
WORD nLength; WORD nLength;
WCHAR achString[]; WCHAR achString[];
}; };
#pragma warning(pop) // C4200 #pragma warning(pop) // C4200
inline const ATLSTRINGRESOURCEIMAGE* _AtlGetStringResourceImage( inline const ATLSTRINGRESOURCEIMAGE* _AtlGetStringResourceImage(
_In_ HINSTANCE hInstance, _In_ HINSTANCE hInstance,
_In_ HRSRC hResource, _In_ HRSRC hResource,
_In_ UINT id) throw() _In_ UINT id) throw()
{ {
const ATLSTRINGRESOURCEIMAGE* pImage; const ATLSTRINGRESOURCEIMAGE* pImage;
const ATLSTRINGRESOURCEIMAGE* pImageEnd; const ATLSTRINGRESOURCEIMAGE* pImageEnd;
ULONG nResourceSize; ULONG nResourceSize;
HGLOBAL hGlobal; HGLOBAL hGlobal;
UINT iIndex; UINT iIndex;
hGlobal = ::LoadResource( hInstance, hResource ); hGlobal = ::LoadResource( hInstance, hResource );
if( hGlobal == NULL ) if( hGlobal == NULL )
{ {
return( NULL ); return( NULL );
} }
pImage = (const ATLSTRINGRESOURCEIMAGE*)::LockResource( hGlobal ); pImage = (const ATLSTRINGRESOURCEIMAGE*)::LockResource( hGlobal );
if( pImage == NULL ) if( pImage == NULL )
{ {
return( NULL ); return( NULL );
} }
nResourceSize = ::SizeofResource( hInstance, hResource ); nResourceSize = ::SizeofResource( hInstance, hResource );
pImageEnd = (const ATLSTRINGRESOURCEIMAGE*)(LPBYTE( pImage )+nResourceSize); pImageEnd = (const ATLSTRINGRESOURCEIMAGE*)(LPBYTE( pImage )+nResourceSize);
iIndex = id&0x000f; iIndex = id&0x000f;
while( (iIndex > 0) && (pImage < pImageEnd) ) while( (iIndex > 0) && (pImage < pImageEnd) )
{ {
pImage = (const ATLSTRINGRESOURCEIMAGE*)(LPBYTE( pImage )+(sizeof( ATLSTRINGRESOURCEIMAGE )+(pImage->nLength*sizeof( WCHAR )))); pImage = (const ATLSTRINGRESOURCEIMAGE*)(LPBYTE( pImage )+(sizeof( ATLSTRINGRESOURCEIMAGE )+(pImage->nLength*sizeof( WCHAR ))));
iIndex--; iIndex--;
} }
if( pImage >= pImageEnd ) if( pImage >= pImageEnd )
{ {
return( NULL ); return( NULL );
} }
if( pImage->nLength == 0 ) if( pImage->nLength == 0 )
{ {
return( NULL ); return( NULL );
} }
return( pImage ); return( pImage );
} }
inline const ATLSTRINGRESOURCEIMAGE* AtlGetStringResourceImage( inline const ATLSTRINGRESOURCEIMAGE* AtlGetStringResourceImage(
_In_ HINSTANCE hInstance, _In_ HINSTANCE hInstance,
_In_ UINT id) throw() _In_ UINT id) throw()
{ {
HRSRC hResource; HRSRC hResource;
/* /*
The and operation (& static_cast<WORD>(~0)) protects the expression from being greater The and operation (& static_cast<WORD>(~0)) protects the expression from being greater
than WORD - this would cause a runtime error when the application is compiled with /RTCc flag. than WORD - this would cause a runtime error when the application is compiled with /RTCc flag.
*/ */
hResource = ::FindResourceW(hInstance, MAKEINTRESOURCEW( (((id>>4)+1) & static_cast<WORD>(~0)) ), (LPWSTR) RT_STRING); hResource = ::FindResourceW(hInstance, MAKEINTRESOURCEW( (((id>>4)+1) & static_cast<WORD>(~0)) ), (LPWSTR) RT_STRING);
if( hResource == NULL ) if( hResource == NULL )
{ {
return( NULL ); return( NULL );
} }
return _AtlGetStringResourceImage( hInstance, hResource, id ); return _AtlGetStringResourceImage( hInstance, hResource, id );
} }
inline const ATLSTRINGRESOURCEIMAGE* AtlGetStringResourceImage( inline const ATLSTRINGRESOURCEIMAGE* AtlGetStringResourceImage(
_In_ HINSTANCE hInstance, _In_ HINSTANCE hInstance,
_In_ UINT id, _In_ UINT id,
_In_ WORD wLanguage) throw() _In_ WORD wLanguage) throw()
{ {
HRSRC hResource; HRSRC hResource;
/* /*
The and operation (& static_cast<WORD>(~0)) protects the expression from being greater The and operation (& static_cast<WORD>(~0)) protects the expression from being greater
than WORD - this would cause a runtime error when the application is compiled with /RTCc flag. than WORD - this would cause a runtime error when the application is compiled with /RTCc flag.
*/ */
hResource = ::FindResourceExW(hInstance, (LPWSTR) RT_STRING, MAKEINTRESOURCEW( (((id>>4)+1) & static_cast<WORD>(~0)) ), wLanguage); hResource = ::FindResourceExW(hInstance, (LPWSTR) RT_STRING, MAKEINTRESOURCEW( (((id>>4)+1) & static_cast<WORD>(~0)) ), wLanguage);
if( hResource == NULL ) if( hResource == NULL )
{ {
return( NULL ); return( NULL );
} }
return _AtlGetStringResourceImage( hInstance, hResource, id ); return _AtlGetStringResourceImage( hInstance, hResource, id );
} }
inline const ATLSTRINGRESOURCEIMAGE* AtlGetStringResourceImage(_In_ UINT id) throw() inline const ATLSTRINGRESOURCEIMAGE* AtlGetStringResourceImage(_In_ UINT id) throw()
{ {
const ATLSTRINGRESOURCEIMAGE* p = NULL; const ATLSTRINGRESOURCEIMAGE* p = NULL;
HINSTANCE hInst = _AtlBaseModule.GetHInstanceAt(0); HINSTANCE hInst = _AtlBaseModule.GetHInstanceAt(0);
for (int i = 1; hInst != NULL && p == NULL; hInst = _AtlBaseModule.GetHInstanceAt(i++)) for (int i = 1; hInst != NULL && p == NULL; hInst = _AtlBaseModule.GetHInstanceAt(i++))
{ {
p = AtlGetStringResourceImage(hInst, id); p = AtlGetStringResourceImage(hInst, id);
} }
return p; return p;
} }
inline const ATLSTRINGRESOURCEIMAGE* AtlGetStringResourceImage( inline const ATLSTRINGRESOURCEIMAGE* AtlGetStringResourceImage(
_In_ UINT id, _In_ UINT id,
_In_ WORD wLanguage) throw() _In_ WORD wLanguage) throw()
{ {
const ATLSTRINGRESOURCEIMAGE* p = NULL; const ATLSTRINGRESOURCEIMAGE* p = NULL;
HINSTANCE hInst = _AtlBaseModule.GetHInstanceAt(0); HINSTANCE hInst = _AtlBaseModule.GetHInstanceAt(0);
for (int i = 1; hInst != NULL && p == NULL; hInst = _AtlBaseModule.GetHInstanceAt(i++)) for (int i = 1; hInst != NULL && p == NULL; hInst = _AtlBaseModule.GetHInstanceAt(i++))
{ {
p = AtlGetStringResourceImage(hInst, id, wLanguage); p = AtlGetStringResourceImage(hInst, id, wLanguage);
} }
return p; return p;
} }
inline int AtlLoadString( inline int AtlLoadString(
_In_ UINT nID, _In_ UINT nID,
_Out_z_cap_post_count_(nBufferMax, return + 1) LPTSTR lpBuffer, _Out_z_cap_post_count_(nBufferMax, return + 1) LPTSTR lpBuffer,
_In_ int nBufferMax) throw() _In_ int nBufferMax) throw()
{ {
HINSTANCE hInst = _AtlBaseModule.GetHInstanceAt(0); HINSTANCE hInst = _AtlBaseModule.GetHInstanceAt(0);
int nRet = 0; int nRet = 0;
for (int i = 1; hInst != NULL && nRet == 0; hInst = _AtlBaseModule.GetHInstanceAt(i++)) for (int i = 1; hInst != NULL && nRet == 0; hInst = _AtlBaseModule.GetHInstanceAt(i++))
{ {
nRet = LoadString(hInst, nID, lpBuffer, nBufferMax); nRet = LoadString(hInst, nID, lpBuffer, nBufferMax);
} }
return nRet; return nRet;
} }
inline HINSTANCE AtlFindResourceInstance( inline HINSTANCE AtlFindResourceInstance(
_In_z_ LPCTSTR lpName, _In_z_ LPCTSTR lpName,
_In_z_ LPCTSTR lpType, _In_z_ LPCTSTR lpType,
_In_ WORD wLanguage = 0) throw() _In_ WORD wLanguage = 0) throw()
{ {
ATLASSERT(lpType != RT_STRING); // Call AtlFindStringResourceInstance to find the string ATLASSERT(lpType != RT_STRING); // Call AtlFindStringResourceInstance to find the string
if (lpType == RT_STRING) if (lpType == RT_STRING)
return NULL; return NULL;
if (ATL_IS_INTRESOURCE(lpType)) if (ATL_IS_INTRESOURCE(lpType))
{ {
/* Prefast false warnings caused by bad-shaped definition of MAKEINTRESOURCE macro from PSDK */ /* Prefast false warnings caused by bad-shaped definition of MAKEINTRESOURCE macro from PSDK */
if (lpType == ATL_RT_ICON) if (lpType == ATL_RT_ICON)
{ {
lpType = ATL_RT_GROUP_ICON; lpType = ATL_RT_GROUP_ICON;
} }
else if (lpType == ATL_RT_CURSOR) else if (lpType == ATL_RT_CURSOR)
{ {
lpType = ATL_RT_GROUP_CURSOR; lpType = ATL_RT_GROUP_CURSOR;
} }
} }
HINSTANCE hInst = _AtlBaseModule.GetHInstanceAt(0); HINSTANCE hInst = _AtlBaseModule.GetHInstanceAt(0);
HRSRC hResource = NULL; HRSRC hResource = NULL;
for (int i = 1; hInst != NULL; hInst = _AtlBaseModule.GetHInstanceAt(i++)) for (int i = 1; hInst != NULL; hInst = _AtlBaseModule.GetHInstanceAt(i++))
{ {
hResource = ::FindResourceEx(hInst, lpType, lpName, wLanguage); hResource = ::FindResourceEx(hInst, lpType, lpName, wLanguage);
if (hResource != NULL) if (hResource != NULL)
{ {
return hInst; return hInst;
} }
} }
return NULL; return NULL;
} }
inline HINSTANCE AtlFindResourceInstance( inline HINSTANCE AtlFindResourceInstance(
_In_ UINT nID, _In_ UINT nID,
_In_z_ LPCTSTR lpType, _In_z_ LPCTSTR lpType,
_In_ WORD wLanguage = 0) throw() _In_ WORD wLanguage = 0) throw()
{ {
/* /*
The and operation (& static_cast<WORD>(~0)) protects the expression from being greater The and operation (& static_cast<WORD>(~0)) protects the expression from being greater
than WORD - this would cause a runtime error when the application is compiled with /RTCc flag. than WORD - this would cause a runtime error when the application is compiled with /RTCc flag.
*/ */
return AtlFindResourceInstance(MAKEINTRESOURCE(nID & static_cast<WORD>(~0)), lpType, wLanguage); return AtlFindResourceInstance(MAKEINTRESOURCE(nID & static_cast<WORD>(~0)), lpType, wLanguage);
} }
inline HINSTANCE AtlFindStringResourceInstance( inline HINSTANCE AtlFindStringResourceInstance(
_In_ UINT nID, _In_ UINT nID,
_In_ WORD wLanguage = 0) throw() _In_ WORD wLanguage = 0) throw()
{ {
const ATLSTRINGRESOURCEIMAGE* p = NULL; const ATLSTRINGRESOURCEIMAGE* p = NULL;
HINSTANCE hInst = _AtlBaseModule.GetHInstanceAt(0); HINSTANCE hInst = _AtlBaseModule.GetHInstanceAt(0);
for (int i = 1; hInst != NULL && p == NULL; hInst = _AtlBaseModule.GetHInstanceAt(i++)) for (int i = 1; hInst != NULL && p == NULL; hInst = _AtlBaseModule.GetHInstanceAt(i++))
{ {
p = AtlGetStringResourceImage(hInst, nID, wLanguage); p = AtlGetStringResourceImage(hInst, nID, wLanguage);
if (p != NULL) if (p != NULL)
return hInst; return hInst;
} }
return NULL; return NULL;
} }
/* /*
@@ -505,39 +505,39 @@ inline HRESULT AtlSafeArrayGetActualVartype(
template <typename _CharType> template <typename _CharType>
inline _CharType* AtlCharNext(_In_ const _CharType* p) throw() inline _CharType* AtlCharNext(_In_ const _CharType* p) throw()
{ {
ATLASSUME(p != NULL); // Too expensive to check separately here ATLASSUME(p != NULL); // Too expensive to check separately here
if (*p == '\0') // ::CharNextA won't increment if we're at a \0 already if (*p == '\0') // ::CharNextA won't increment if we're at a \0 already
return const_cast<_CharType*>(p+1); return const_cast<_CharType*>(p+1);
else else
return ::CharNextA(p); return ::CharNextA(p);
} }
template <> template <>
inline wchar_t* AtlCharNext<wchar_t>(_In_ const wchar_t* p) throw() inline wchar_t* AtlCharNext<wchar_t>(_In_ const wchar_t* p) throw()
{ {
return const_cast< wchar_t* >( p+1 ); return const_cast< wchar_t* >( p+1 );
} }
template<typename CharType> template<typename CharType>
inline const CharType* AtlstrchrT( inline const CharType* AtlstrchrT(
_In_z_ const CharType* p, _In_z_ const CharType* p,
_In_ CharType ch) throw() _In_ CharType ch) throw()
{ {
ATLASSERT(p != NULL); ATLASSERT(p != NULL);
if(p==NULL) if(p==NULL)
{ {
return NULL; return NULL;
} }
while( *p != 0 ) while( *p != 0 )
{ {
if (*p == ch) if (*p == ch)
{ {
return p; return p;
} }
p = AtlCharNext(p); p = AtlCharNext(p);
} }
//strchr for '\0' should succeed - the while loop terminates //strchr for '\0' should succeed - the while loop terminates
//*p == 0, but ch also == 0, so NULL terminator address is returned //*p == 0, but ch also == 0, so NULL terminator address is returned
return (*p == ch) ? p : NULL; return (*p == ch) ? p : NULL;
} }
//Ansi and Unicode versions of printf, used with templated CharType trait classes. //Ansi and Unicode versions of printf, used with templated CharType trait classes.
#pragma warning(push) #pragma warning(push)
@@ -545,12 +545,12 @@ inline const CharType* AtlstrchrT(
template<typename CharType> template<typename CharType>
inline int AtlprintfT(_In_z_ _Printf_format_string_ const CharType* pszFormat,...) throw() inline int AtlprintfT(_In_z_ _Printf_format_string_ const CharType* pszFormat,...) throw()
{ {
int retval=0; int retval=0;
va_list argList; va_list argList;
va_start( argList, pszFormat ); va_start( argList, pszFormat );
retval=vprintf(pszFormat,argList); retval=vprintf(pszFormat,argList);
va_end( argList ); va_end( argList );
return retval; return retval;
} }
#pragma warning(pop) #pragma warning(pop)
@@ -559,43 +559,43 @@ inline int AtlprintfT(_In_z_ _Printf_format_string_ const CharType* pszFormat,..
template<> template<>
inline int AtlprintfT(_In_z_ _Printf_format_string_ const wchar_t* pszFormat,... ) throw() inline int AtlprintfT(_In_z_ _Printf_format_string_ const wchar_t* pszFormat,... ) throw()
{ {
int retval=0; int retval=0;
va_list argList; va_list argList;
va_start( argList, pszFormat ); va_start( argList, pszFormat );
retval=vwprintf(pszFormat, argList); retval=vwprintf(pszFormat, argList);
va_end( argList ); va_end( argList );
return retval; return retval;
} }
#pragma warning(pop) #pragma warning(pop)
inline BOOL AtlConvertSystemTimeToVariantTime( inline BOOL AtlConvertSystemTimeToVariantTime(
_In_ const SYSTEMTIME& systimeSrc, _In_ const SYSTEMTIME& systimeSrc,
_Out_ double* pVarDtTm) _Out_ double* pVarDtTm)
{ {
ATLENSURE(pVarDtTm!=NULL); ATLENSURE(pVarDtTm!=NULL);
//Convert using ::SystemTimeToVariantTime and store the result in pVarDtTm then //Convert using ::SystemTimeToVariantTime and store the result in pVarDtTm then
//convert variant time back to system time and compare to original system time. //convert variant time back to system time and compare to original system time.
BOOL ok = ::SystemTimeToVariantTime(const_cast<SYSTEMTIME*>(&systimeSrc), pVarDtTm); BOOL ok = ::SystemTimeToVariantTime(const_cast<SYSTEMTIME*>(&systimeSrc), pVarDtTm);
SYSTEMTIME sysTime; SYSTEMTIME sysTime;
::ZeroMemory(&sysTime, sizeof(SYSTEMTIME)); ::ZeroMemory(&sysTime, sizeof(SYSTEMTIME));
ok = ok && ::VariantTimeToSystemTime(*pVarDtTm, &sysTime); ok = ok && ::VariantTimeToSystemTime(*pVarDtTm, &sysTime);
ok = ok && (systimeSrc.wYear == sysTime.wYear && ok = ok && (systimeSrc.wYear == sysTime.wYear &&
systimeSrc.wMonth == sysTime.wMonth && systimeSrc.wMonth == sysTime.wMonth &&
systimeSrc.wDay == sysTime.wDay && systimeSrc.wDay == sysTime.wDay &&
systimeSrc.wHour == sysTime.wHour && systimeSrc.wHour == sysTime.wHour &&
systimeSrc.wMinute == sysTime.wMinute && systimeSrc.wMinute == sysTime.wMinute &&
systimeSrc.wSecond == sysTime.wSecond); systimeSrc.wSecond == sysTime.wSecond);
return ok; return ok;
} }
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
} // namespace ATL } // namespace ATL
#pragma pack(pop) #pragma pack(pop)
#ifdef _ATL_ALL_WARNINGS #ifdef _ATL_ALL_WARNINGS
#pragma warning( pop ) #pragma warning( pop )
#endif #endif
#endif // __ATLCORE_H__ #endif // __ATLCORE_H__

View File

@@ -13,7 +13,7 @@
#pragma once #pragma once
#pragma warning(disable : 4619) // there is no warning number #pragma warning(disable : 4619) // there is no warning number
#include <atlrc.h> #include <atlrc.h>
#include <errno.h> #include <errno.h>
@@ -33,11 +33,11 @@
#ifndef RC_INVOKED #ifndef RC_INVOKED
#ifndef __cplusplus #ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix) #error ATL requires C++ compilation (use a .cpp suffix)
#endif #endif
#ifdef UNDER_CE #ifdef UNDER_CE
#error This version of ATL is not currently supported for CE. Look for the CE specific version. #error This version of ATL is not currently supported for CE. Look for the CE specific version.
#endif #endif
// If you are mixing compilation units that are built as // If you are mixing compilation units that are built as
@@ -47,7 +47,7 @@
#if !defined(_ATL_MIXED) #if !defined(_ATL_MIXED)
namespace Inconsistent_definition_of_symbol__ATL_MIXED namespace Inconsistent_definition_of_symbol__ATL_MIXED
{ {
struct _Please_define_it_the_same_throughout_your_project { }; struct _Please_define_it_the_same_throughout_your_project { };
} }
#else #else
namespace Inconsistent_definition_of_symbol__ATL_MIXED namespace Inconsistent_definition_of_symbol__ATL_MIXED
@@ -57,28 +57,28 @@ namespace Inconsistent_definition_of_symbol__ATL_MIXED
#else #else
#pragma comment(linker, "/include:??3@YAXPEAX@Z") #pragma comment(linker, "/include:??3@YAXPEAX@Z")
#endif #endif
struct _Please_define_it_the_same_throughout_your_project { virtual void one(){} }; struct _Please_define_it_the_same_throughout_your_project { virtual void one(){} };
} }
#endif #endif
namespace Inconsistent_definition_of_symbol__ATL_MIXED namespace Inconsistent_definition_of_symbol__ATL_MIXED
{ {
__declspec(selectany) _Please_define_it_the_same_throughout_your_project clash = _Please_define_it_the_same_throughout_your_project (); __declspec(selectany) _Please_define_it_the_same_throughout_your_project clash = _Please_define_it_the_same_throughout_your_project ();
} }
#if !defined(_ATL_MIXED) #if !defined(_ATL_MIXED)
namespace Define_the_symbol__ATL_MIXED namespace Define_the_symbol__ATL_MIXED
{ {
#if defined(_M_CEE) #if defined(_M_CEE)
struct Thank_you { }; struct Thank_you { };
#else #else
#ifdef _M_IX86 #ifdef _M_IX86
#pragma comment(linker, "/include:??3@YAXPAX@Z") #pragma comment(linker, "/include:??3@YAXPAX@Z")
#else #else
#pragma comment(linker, "/include:??3@YAXPEAX@Z") #pragma comment(linker, "/include:??3@YAXPEAX@Z")
#endif #endif
struct Thank_you { virtual void one(){} }; struct Thank_you { virtual void one(){} };
#endif #endif
__declspec(selectany) Thank_you clash = Thank_you(); __declspec(selectany) Thank_you clash = Thank_you();
} }
#endif #endif
@@ -113,7 +113,7 @@ namespace Define_the_symbol__ATL_MIXED
#if defined(_PREFAST_) && (_MSC_VER < 1600) #if defined(_PREFAST_) && (_MSC_VER < 1600)
#define ATLSTATIC_ASSERT(expr, comment) #define ATLSTATIC_ASSERT(expr, comment)
#else #else
#define ATLSTATIC_ASSERT(expr, comment) static_assert(expr, comment) #define ATLSTATIC_ASSERT(expr, comment) static_assert(expr, comment)
#endif #endif
#ifdef _WIN64 #ifdef _WIN64
@@ -184,19 +184,19 @@ Sometimes we have code like
HRESULT ComMethod(void) HRESULT ComMethod(void)
{ {
ATLASSUME(m_pFoo); ATLASSUME(m_pFoo);
return m_pFoo->Method(); return m_pFoo->Method();
} }
We could add We could add
if(!m_pFoo) return E_POINTER; if(!m_pFoo) return E_POINTER;
But this is very unlikely to help, since it removes the ability of the developer to debug this problem if it's seen in a retail But this is very unlikely to help, since it removes the ability of the developer to debug this problem if it's seen in a retail
build of the application. build of the application.
We could try something more severe We could try something more severe
if(!m_pFoo) terminate(); // or your favourite shutdown function if(!m_pFoo) terminate(); // or your favourite shutdown function
This would ensure good reporting (because VC8 terminate generates a Windows Error Report and crash dump), but hardly seems a big win This would ensure good reporting (because VC8 terminate generates a Windows Error Report and crash dump), but hardly seems a big win
over the previous crash. over the previous crash.
@@ -233,9 +233,9 @@ So we've done a broad replace of all the member-related ATLASSERT to ATLASSUME.
#ifndef ATLENSURE_THROW #ifndef ATLENSURE_THROW
#define ATLENSURE_THROW(expr, hr) \ #define ATLENSURE_THROW(expr, hr) \
do { \ do { \
int __atl_condVal=!!(expr); \ int __atl_condVal=!!(expr); \
ATLASSUME(__atl_condVal); \ ATLASSUME(__atl_condVal); \
if(!(__atl_condVal)) AtlThrow(hr); \ if(!(__atl_condVal)) AtlThrow(hr); \
} while (0) } while (0)
#endif // ATLENSURE_THROW #endif // ATLENSURE_THROW
@@ -251,9 +251,9 @@ do { \
#ifndef ATLENSURE_RETURN_VAL #ifndef ATLENSURE_RETURN_VAL
#define ATLENSURE_RETURN_VAL(expr, val) \ #define ATLENSURE_RETURN_VAL(expr, val) \
do { \ do { \
int __atl_condVal=!!(expr); \ int __atl_condVal=!!(expr); \
ATLASSERT(__atl_condVal); \ ATLASSERT(__atl_condVal); \
if(!(__atl_condVal)) return val; \ if(!(__atl_condVal)) return val; \
} while (0) } while (0)
#endif // ATLENSURE_RETURN_VAL #endif // ATLENSURE_RETURN_VAL
@@ -278,17 +278,17 @@ ATLENSURE_RETURN_HR is HRESULT-specific, though currently the same as _VAL
#ifndef ATL_CRT_ERRORCHECK_SPRINTF #ifndef ATL_CRT_ERRORCHECK_SPRINTF
#define ATL_CRT_ERRORCHECK_SPRINTF(expr) \ #define ATL_CRT_ERRORCHECK_SPRINTF(expr) \
do { \ do { \
errno_t _saveErrno = errno; \ errno_t _saveErrno = errno; \
errno = 0; \ errno = 0; \
(expr); \ (expr); \
if(0 != errno) \ if(0 != errno) \
{ \ { \
AtlCrtErrorCheck(errno); \ AtlCrtErrorCheck(errno); \
} \ } \
else \ else \
{ \ { \
errno = _saveErrno; \ errno = _saveErrno; \
} \ } \
} while (0) } while (0)
#endif // ATL_CRT_ERRORCHECK_SPRINTF #endif // ATL_CRT_ERRORCHECK_SPRINTF
@@ -383,33 +383,33 @@ do { \
#endif #endif
#if defined(_ATL_DLL) #if defined(_ATL_DLL)
#define ATLAPI extern "C" HRESULT __declspec(dllimport) __stdcall #define ATLAPI extern "C" HRESULT __declspec(dllimport) __stdcall
#define ATLAPI_(x) extern "C" __declspec(dllimport) x __stdcall #define ATLAPI_(x) extern "C" __declspec(dllimport) x __stdcall
#define ATLINLINE #define ATLINLINE
#define ATLAPIINL extern "C" inline HRESULT __stdcall #define ATLAPIINL extern "C" inline HRESULT __stdcall
#define ATLAPIINL_(x) extern "C" inline x __stdcall #define ATLAPIINL_(x) extern "C" inline x __stdcall
#elif defined(_ATL_DLL_IMPL) #elif defined(_ATL_DLL_IMPL)
#define ATLAPI extern "C" inline HRESULT __stdcall #define ATLAPI extern "C" inline HRESULT __stdcall
#define ATLAPI_(x) extern "C" inline x __stdcall #define ATLAPI_(x) extern "C" inline x __stdcall
#define ATLAPIINL ATLAPI #define ATLAPIINL ATLAPI
#define ATLAPIINL_(x) ATLAPI_(x) #define ATLAPIINL_(x) ATLAPI_(x)
#define ATLINLINE #define ATLINLINE
#else #else
#define ATLAPI __declspec(nothrow) HRESULT __stdcall #define ATLAPI __declspec(nothrow) HRESULT __stdcall
#define ATLAPI_(x) __declspec(nothrow) x __stdcall #define ATLAPI_(x) __declspec(nothrow) x __stdcall
#define ATLAPIINL ATLAPI #define ATLAPIINL ATLAPI
#define ATLAPIINL_(x) ATLAPI_(x) #define ATLAPIINL_(x) ATLAPI_(x)
#define ATLINLINE inline #define ATLINLINE inline
#endif #endif
#ifdef _ATL_NO_EXCEPTIONS #ifdef _ATL_NO_EXCEPTIONS
#ifdef _AFX #ifdef _AFX
// #error MFC projects cannot define _ATL_NO_EXCEPTIONS // #error MFC projects cannot define _ATL_NO_EXCEPTIONS
#endif #endif
#else #else
#ifndef _CPPUNWIND #ifndef _CPPUNWIND
#define _ATL_NO_EXCEPTIONS #define _ATL_NO_EXCEPTIONS
#endif #endif
#endif #endif
#ifdef _CPPUNWIND #ifdef _CPPUNWIND
@@ -421,9 +421,9 @@ do { \
#else #else
/* prefast noise VSW 489981 */ /* prefast noise VSW 489981 */
#define ATLTRYALLOC(x) __pragma(warning(push)) __pragma(warning(disable: 4571)) try{x;} catch(...) {} __pragma(warning(pop)) #define ATLTRYALLOC(x) __pragma(warning(push)) __pragma(warning(disable: 4571)) try{x;} catch(...) {} __pragma(warning(pop))
#endif //__AFX #endif //__AFX
#endif //ATLTRYALLOC #endif //ATLTRYALLOC
// If you define _ATLTRY before including this file, then // If you define _ATLTRY before including this file, then
// you should define _ATLCATCH and _ATLRETHROW as well. // you should define _ATLCATCH and _ATLRETHROW as well.
@@ -444,7 +444,7 @@ do { \
#endif #endif
#define _ATLRETHROW throw #define _ATLRETHROW throw
#endif // _ATLTRY #endif // _ATLTRY
/* /*
COM functions should not throw. Which means we should protect their callers from C++ exceptions leaking out. These macros COM functions should not throw. Which means we should protect their callers from C++ exceptions leaking out. These macros
@@ -454,38 +454,38 @@ this end
#ifndef _ATL_COM_BEGIN #ifndef _ATL_COM_BEGIN
#define _ATL_COM_BEGIN \ #define _ATL_COM_BEGIN \
HRESULT __hrAtlComMethod=S_OK; \ HRESULT __hrAtlComMethod=S_OK; \
try \ try \
{ {
#endif #endif
#ifdef _AFX #ifdef _AFX
/* Nice to do something more complex here in future to translate an MFC exception to a better HR */ /* Nice to do something more complex here in future to translate an MFC exception to a better HR */
#define _AFX_COM_END_PART \ #define _AFX_COM_END_PART \
catch(CException *e) \ catch(CException *e) \
{ \ { \
if(e) \ if(e) \
{ \ { \
e->Delete(); \ e->Delete(); \
} \ } \
__hrAtlComMethod=E_FAIL; \ __hrAtlComMethod=E_FAIL; \
} }
#else #else
#define _AFX_COM_END_PART \ #define _AFX_COM_END_PART \
catch(CAtlException e) \ catch(CAtlException e) \
{ \ { \
__hrAtlComMethod=e.m_hr; \ __hrAtlComMethod=e.m_hr; \
} }
#endif #endif
#ifndef _ATL_COM_END #ifndef _ATL_COM_END
#define _ATL_COM_END \ #define _ATL_COM_END \
_AFX_COM_END_PART \ _AFX_COM_END_PART \
catch(...) \ catch(...) \
{ \ { \
__hrAtlComMethod=E_FAIL; \ __hrAtlComMethod=E_FAIL; \
} \ } \
return hr; return hr;
#endif #endif
@@ -494,7 +494,7 @@ this end
#ifndef ATLTRYALLOC #ifndef ATLTRYALLOC
#define ATLTRYALLOC(x) x; #define ATLTRYALLOC(x) x;
#endif //ATLTRYALLOC #endif //ATLTRYALLOC
// if _ATLTRY is defined before including this file then // if _ATLTRY is defined before including this file then
// _ATLCATCH and _ATLRETHROW should be defined as well. // _ATLCATCH and _ATLRETHROW should be defined as well.
@@ -504,13 +504,13 @@ this end
#define _ATLCATCHALL() __pragma(warning(push)) __pragma(warning(disable: 4127)) if( false ) __pragma(warning(pop)) #define _ATLCATCHALL() __pragma(warning(push)) __pragma(warning(disable: 4127)) if( false ) __pragma(warning(pop))
#define _ATLDELETEEXCEPTION(e) #define _ATLDELETEEXCEPTION(e)
#define _ATLRETHROW #define _ATLRETHROW
#endif // _ATLTRY #endif // _ATLTRY
#endif //_CPPUNWIND #endif //_CPPUNWIND
#ifndef ATLTRY #ifndef ATLTRY
#define ATLTRY(x) ATLTRYALLOC(x) #define ATLTRY(x) ATLTRYALLOC(x)
#endif //ATLTRY #endif //ATLTRY
#define offsetofclass(base, derived) ((DWORD_PTR)(static_cast<base*>((derived*)_ATL_PACKING))-_ATL_PACKING) #define offsetofclass(base, derived) ((DWORD_PTR)(static_cast<base*>((derived*)_ATL_PACKING))-_ATL_PACKING)
@@ -558,19 +558,19 @@ this end
#ifndef NOMCX #ifndef NOMCX
#define NOMCX #define NOMCX
#endif #endif
#endif // ATL_NO_LEAN_AND_MEAN #endif // ATL_NO_LEAN_AND_MEAN
#ifdef NOSERVICE #ifdef NOSERVICE
#ifndef _ATL_NO_SERVICE #ifndef _ATL_NO_SERVICE
#define _ATL_NO_SERVICE #define _ATL_NO_SERVICE
#endif // _ATL_NO_SERVICE #endif // _ATL_NO_SERVICE
#else #else
#ifdef _ATL_NO_SERVICE #ifdef _ATL_NO_SERVICE
#ifndef NOSERVICE #ifndef NOSERVICE
#define NOSERVICE #define NOSERVICE
#endif // NOSERVICE #endif // NOSERVICE
#endif // _ATL_NO_SERVICE #endif // _ATL_NO_SERVICE
#endif // NOSERVICE #endif // NOSERVICE
#include <malloc.h> #include <malloc.h>
#ifdef _DEBUG #ifdef _DEBUG
@@ -580,15 +580,15 @@ this end
// Warning: if you define the above symbol, you will have // Warning: if you define the above symbol, you will have
// to provide your own definition of the ATLASSERT(x) macro // to provide your own definition of the ATLASSERT(x) macro
// in order to compile ATL // in order to compile ATL
#include <crtdbg.h> #include <crtdbg.h>
#endif #endif
#endif // RC_INVOKED #endif // RC_INVOKED
// Note : we can not use macros to generate the window class names because it // Note : we can not use macros to generate the window class names because it
// will require nested macros. rc.exe does not handle nested macros. // will require nested macros. rc.exe does not handle nested macros.
// #define ATLAXWIN_CLASS _ATL_STRINGIZE(_ATL_APPEND(AtlAxWin, _ATL_FILENAME_VER_NUM)) // #define ATLAXWIN_CLASS _ATL_STRINGIZE(_ATL_APPEND(AtlAxWin, _ATL_FILENAME_VER_NUM))
// #define ATLAXWINLIC_CLASS _ATL_STRINGIZE(_ATL_APPEND(AtlAxWinLic, _ATL_FILENAME_VER_NUM)) // #define ATLAXWINLIC_CLASS _ATL_STRINGIZE(_ATL_APPEND(AtlAxWinLic, _ATL_FILENAME_VER_NUM))
#define ATLAXWIN_CLASS "AtlAxWin100" #define ATLAXWIN_CLASS "AtlAxWin100"
#define ATLAXWINLIC_CLASS "AtlAxWinLic100" #define ATLAXWINLIC_CLASS "AtlAxWinLic100"
@@ -622,10 +622,10 @@ that we consider it dangerous to even throw an exception
#else #else
#if !defined(__MINGW32__) #if !defined(__MINGW32__)
#define PTM_WARNING_DISABLE \ #define PTM_WARNING_DISABLE \
__pragma(warning( push )) \ __pragma(warning( push )) \
__pragma(warning( disable : 4867 )) __pragma(warning( disable : 4867 ))
#define PTM_WARNING_RESTORE \ #define PTM_WARNING_RESTORE \
__pragma(warning( pop )) __pragma(warning( pop ))
#else #else
#define PTM_WARNING_DISABLE #define PTM_WARNING_DISABLE
#define PTM_WARNING_RESTORE #define PTM_WARNING_RESTORE
@@ -695,13 +695,13 @@ that we consider it dangerous to even throw an exception
#define ATLPREFAST_SUPPRESS(x) #define ATLPREFAST_SUPPRESS(x)
#define ATLPREFAST_UNSUPPRESS() #define ATLPREFAST_UNSUPPRESS()
#endif #endif
#ifndef _FormatMessage_format_string_ #ifndef _FormatMessage_format_string_
#define _FormatMessage_format_string_ #define _FormatMessage_format_string_
#endif #endif
/* /*
Helper functions for SAL annotation Helper functions for SAL annotation
*/ */
namespace ATL { namespace ATL {

View File

@@ -27,32 +27,32 @@ namespace ATL
// Exception raise (for functions that cannot return an error code) // Exception raise (for functions that cannot return an error code)
inline void __declspec(noreturn) _AtlRaiseException( inline void __declspec(noreturn) _AtlRaiseException(
_In_ DWORD dwExceptionCode, _In_ DWORD dwExceptionCode,
_In_ DWORD dwExceptionFlags = EXCEPTION_NONCONTINUABLE) _In_ DWORD dwExceptionFlags = EXCEPTION_NONCONTINUABLE)
{ {
RaiseException( dwExceptionCode, dwExceptionFlags, 0, NULL ); RaiseException( dwExceptionCode, dwExceptionFlags, 0, NULL );
} }
class CAtlException class CAtlException
{ {
public: public:
CAtlException() throw() : CAtlException() throw() :
m_hr( E_FAIL ) m_hr( E_FAIL )
{ {
} }
CAtlException(_In_ HRESULT hr) throw() : CAtlException(_In_ HRESULT hr) throw() :
m_hr( hr ) m_hr( hr )
{ {
} }
operator HRESULT() const throw() operator HRESULT() const throw()
{ {
return( m_hr ); return( m_hr );
} }
public: public:
HRESULT m_hr; HRESULT m_hr;
}; };
#ifndef ATL_NOINLINE #ifndef ATL_NOINLINE
@@ -73,15 +73,15 @@ public:
#else #else
ATL_NOINLINE __declspec(noreturn) inline void WINAPI AtlThrowImpl(_In_ HRESULT hr) ATL_NOINLINE __declspec(noreturn) inline void WINAPI AtlThrowImpl(_In_ HRESULT hr)
{ {
throw CAtlException( hr ); throw CAtlException( hr );
} }
#endif #endif
// Throw a CAtlException corresponding to the result of ::GetLastError // Throw a CAtlException corresponding to the result of ::GetLastError
ATL_NOINLINE __declspec(noreturn) inline void WINAPI AtlThrowLastWin32() ATL_NOINLINE __declspec(noreturn) inline void WINAPI AtlThrowLastWin32()
{ {
DWORD dwError = ::GetLastError(); DWORD dwError = ::GetLastError();
AtlThrowImpl( HRESULT_FROM_WIN32( dwError ) ); AtlThrowImpl( HRESULT_FROM_WIN32( dwError ) );
} }
#else // no exception handling #else // no exception handling
@@ -91,25 +91,25 @@ ATL_NOINLINE __declspec(noreturn) inline void WINAPI AtlThrowLastWin32()
ATL_NOINLINE inline void WINAPI AtlThrowImpl(_In_ HRESULT hr) ATL_NOINLINE inline void WINAPI AtlThrowImpl(_In_ HRESULT hr)
{ {
ATLASSERT( false ); ATLASSERT( false );
DWORD dwExceptionCode; DWORD dwExceptionCode;
switch(hr) switch(hr)
{ {
case E_OUTOFMEMORY: case E_OUTOFMEMORY:
dwExceptionCode = STATUS_NO_MEMORY; dwExceptionCode = STATUS_NO_MEMORY;
break; break;
default: default:
dwExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION; dwExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
} }
_AtlRaiseException((DWORD)dwExceptionCode); _AtlRaiseException((DWORD)dwExceptionCode);
} }
#endif #endif
// Throw a CAtlException corresponding to the result of ::GetLastError // Throw a CAtlException corresponding to the result of ::GetLastError
ATL_NOINLINE inline void WINAPI AtlThrowLastWin32() ATL_NOINLINE inline void WINAPI AtlThrowLastWin32()
{ {
DWORD dwError = ::GetLastError(); DWORD dwError = ::GetLastError();
AtlThrowImpl( HRESULT_FROM_WIN32( dwError ) ); AtlThrowImpl( HRESULT_FROM_WIN32( dwError ) );
} }
#endif // no exception handling #endif // no exception handling

File diff suppressed because it is too large Load Diff

View File

@@ -49,64 +49,64 @@ template <class T>
class CSimpleArrayEqualHelper class CSimpleArrayEqualHelper
{ {
public: public:
static bool IsEqual( static bool IsEqual(
_In_ const T& t1, _In_ const T& t1,
_In_ const T& t2) _In_ const T& t2)
{ {
return (t1 == t2); return (t1 == t2);
} }
}; };
template <class T> template <class T>
class CSimpleArrayEqualHelperFalse class CSimpleArrayEqualHelperFalse
{ {
public: public:
static bool IsEqual( static bool IsEqual(
_In_ const T&, _In_ const T&,
_In_ const T&) _In_ const T&)
{ {
ATLASSERT(false); ATLASSERT(false);
return false; return false;
} }
}; };
template <class TKey, class TVal> template <class TKey, class TVal>
class CSimpleMapEqualHelper class CSimpleMapEqualHelper
{ {
public: public:
static bool IsEqualKey( static bool IsEqualKey(
_In_ const TKey& k1, _In_ const TKey& k1,
_In_ const TKey& k2) _In_ const TKey& k2)
{ {
return CSimpleArrayEqualHelper<TKey>::IsEqual(k1, k2); return CSimpleArrayEqualHelper<TKey>::IsEqual(k1, k2);
} }
static bool IsEqualValue( static bool IsEqualValue(
_In_ const TVal& v1, _In_ const TVal& v1,
_In_ const TVal& v2) _In_ const TVal& v2)
{ {
return CSimpleArrayEqualHelper<TVal>::IsEqual(v1, v2); return CSimpleArrayEqualHelper<TVal>::IsEqual(v1, v2);
} }
}; };
template <class TKey, class TVal> template <class TKey, class TVal>
class CSimpleMapEqualHelperFalse class CSimpleMapEqualHelperFalse
{ {
public: public:
static bool IsEqualKey( static bool IsEqualKey(
_In_ const TKey& k1, _In_ const TKey& k1,
_In_ const TKey& k2) _In_ const TKey& k2)
{ {
return CSimpleArrayEqualHelper<TKey>::IsEqual(k1, k2); return CSimpleArrayEqualHelper<TKey>::IsEqual(k1, k2);
} }
static bool IsEqualValue( static bool IsEqualValue(
_In_ const TVal&, _In_ const TVal&,
_In_ const TVal&) _In_ const TVal&)
{ {
ATLASSERT(FALSE); ATLASSERT(FALSE);
return false; return false;
} }
}; };
template <class T, class TEqual = CSimpleArrayEqualHelper< T > > template <class T, class TEqual = CSimpleArrayEqualHelper< T > >
@@ -114,193 +114,193 @@ class CSimpleArray
{ {
public: public:
// Construction/destruction // Construction/destruction
CSimpleArray() : CSimpleArray() :
m_aT(NULL), m_nSize(0), m_nAllocSize(0) m_aT(NULL), m_nSize(0), m_nAllocSize(0)
{ {
} }
~CSimpleArray(); ~CSimpleArray();
CSimpleArray(_In_ const CSimpleArray< T, TEqual >& src) : CSimpleArray(_In_ const CSimpleArray< T, TEqual >& src) :
m_aT(NULL), m_nSize(0), m_nAllocSize(0) m_aT(NULL), m_nSize(0), m_nAllocSize(0)
{ {
if (src.GetSize()) if (src.GetSize())
{ {
m_aT = (T*)nb_calloc(src.GetSize(), sizeof(T)); m_aT = (T*)nb_calloc(src.GetSize(), sizeof(T));
if (m_aT != NULL) if (m_aT != NULL)
{ {
m_nAllocSize = src.GetSize(); m_nAllocSize = src.GetSize();
for (int i=0; i<src.GetSize(); i++) for (int i=0; i<src.GetSize(); i++)
Add(src[i]); Add(src[i]);
} }
} }
} }
CSimpleArray< T, TEqual >& operator=(_In_ const CSimpleArray< T, TEqual >& src) CSimpleArray< T, TEqual >& operator=(_In_ const CSimpleArray< T, TEqual >& src)
{ {
if (GetSize() != src.GetSize()) if (GetSize() != src.GetSize())
{ {
RemoveAll(); RemoveAll();
m_aT = (T*)nb_calloc(src.GetSize(), sizeof(T)); m_aT = (T*)nb_calloc(src.GetSize(), sizeof(T));
if (m_aT != NULL) if (m_aT != NULL)
m_nAllocSize = src.GetSize(); m_nAllocSize = src.GetSize();
} }
else else
{ {
for (int i = GetSize(); i > 0; i--) for (int i = GetSize(); i > 0; i--)
RemoveAt(i - 1); RemoveAt(i - 1);
} }
for (int i=0; i<src.GetSize(); i++) for (int i=0; i<src.GetSize(); i++)
Add(src[i]); Add(src[i]);
return *this; return *this;
} }
// Operations // Operations
int GetSize() const int GetSize() const
{ {
return m_nSize; return m_nSize;
}
BOOL Add(_In_ const T& t)
{
if(m_nSize == m_nAllocSize)
{
// Make sure newElement is not a reference to an element in the array.
// Or else, it will be invalidated by the reallocation.
ATLENSURE( (&t < m_aT) ||
(&t >= (m_aT + m_nAllocSize) ) );
T* aT;
int nNewAllocSize = (m_nAllocSize == 0) ? 1 : (m_nSize * 2);
if (nNewAllocSize<0||nNewAllocSize>INT_MAX/sizeof(T))
{
return FALSE;
}
aT = (T*)_recalloc(m_aT, nNewAllocSize, sizeof(T));
if(aT == NULL)
return FALSE;
m_nAllocSize = nNewAllocSize;
m_aT = aT;
}
InternalSetAtIndex(m_nSize, t);
m_nSize++;
return TRUE;
}
BOOL Remove(_In_ const T& t)
{
int nIndex = Find(t);
if(nIndex == -1)
return FALSE;
return RemoveAt(nIndex);
}
BOOL RemoveAt(_In_ int nIndex)
{
ATLASSERT(nIndex >= 0 && nIndex < m_nSize);
if (nIndex < 0 || nIndex >= m_nSize)
return FALSE;
m_aT[nIndex].~T();
if(nIndex != (m_nSize - 1))
Checked::memmove_s((void*)(m_aT + nIndex), (m_nSize - nIndex) * sizeof(T), (void*)(m_aT + nIndex + 1), (m_nSize - (nIndex + 1)) * sizeof(T));
m_nSize--;
return TRUE;
}
void RemoveAll()
{
if(m_aT != NULL)
{
for(int i = 0; i < m_nSize; i++)
m_aT[i].~T();
nb_free(m_aT);
m_aT = NULL;
}
m_nSize = 0;
m_nAllocSize = 0;
} }
const T& operator[] (_In_ int nIndex) const BOOL Add(_In_ const T& t)
{ {
ATLASSERT(nIndex >= 0 && nIndex < m_nSize); if(m_nSize == m_nAllocSize)
if(nIndex < 0 || nIndex >= m_nSize) {
{ // Make sure newElement is not a reference to an element in the array.
_AtlRaiseException((DWORD)EXCEPTION_ARRAY_BOUNDS_EXCEEDED); // Or else, it will be invalidated by the reallocation.
} ATLENSURE( (&t < m_aT) ||
return m_aT[nIndex]; (&t >= (m_aT + m_nAllocSize) ) );
}
T& operator[] (_In_ int nIndex)
{
ATLASSERT(nIndex >= 0 && nIndex < m_nSize);
if(nIndex < 0 || nIndex >= m_nSize)
{
_AtlRaiseException((DWORD)EXCEPTION_ARRAY_BOUNDS_EXCEEDED);
}
return m_aT[nIndex];
}
T* GetData() const
{
return m_aT;
}
int Find(_In_ const T& t) const T* aT;
{ int nNewAllocSize = (m_nAllocSize == 0) ? 1 : (m_nSize * 2);
for(int i = 0; i < m_nSize; i++)
{
if(TEqual::IsEqual(m_aT[i], t))
return i;
}
return -1; // not found
}
BOOL SetAtIndex( if (nNewAllocSize<0||nNewAllocSize>INT_MAX/sizeof(T))
_In_ int nIndex, {
_In_ const T& t) return FALSE;
{ }
if (nIndex < 0 || nIndex >= m_nSize)
return FALSE; aT = (T*)_recalloc(m_aT, nNewAllocSize, sizeof(T));
InternalSetAtIndex(nIndex, t); if(aT == NULL)
return TRUE; return FALSE;
} m_nAllocSize = nNewAllocSize;
m_aT = aT;
}
InternalSetAtIndex(m_nSize, t);
m_nSize++;
return TRUE;
}
BOOL Remove(_In_ const T& t)
{
int nIndex = Find(t);
if(nIndex == -1)
return FALSE;
return RemoveAt(nIndex);
}
BOOL RemoveAt(_In_ int nIndex)
{
ATLASSERT(nIndex >= 0 && nIndex < m_nSize);
if (nIndex < 0 || nIndex >= m_nSize)
return FALSE;
m_aT[nIndex].~T();
if(nIndex != (m_nSize - 1))
Checked::memmove_s((void*)(m_aT + nIndex), (m_nSize - nIndex) * sizeof(T), (void*)(m_aT + nIndex + 1), (m_nSize - (nIndex + 1)) * sizeof(T));
m_nSize--;
return TRUE;
}
void RemoveAll()
{
if(m_aT != NULL)
{
for(int i = 0; i < m_nSize; i++)
m_aT[i].~T();
nb_free(m_aT);
m_aT = NULL;
}
m_nSize = 0;
m_nAllocSize = 0;
}
const T& operator[] (_In_ int nIndex) const
{
ATLASSERT(nIndex >= 0 && nIndex < m_nSize);
if(nIndex < 0 || nIndex >= m_nSize)
{
_AtlRaiseException((DWORD)EXCEPTION_ARRAY_BOUNDS_EXCEEDED);
}
return m_aT[nIndex];
}
T& operator[] (_In_ int nIndex)
{
ATLASSERT(nIndex >= 0 && nIndex < m_nSize);
if(nIndex < 0 || nIndex >= m_nSize)
{
_AtlRaiseException((DWORD)EXCEPTION_ARRAY_BOUNDS_EXCEEDED);
}
return m_aT[nIndex];
}
T* GetData() const
{
return m_aT;
}
int Find(_In_ const T& t) const
{
for(int i = 0; i < m_nSize; i++)
{
if(TEqual::IsEqual(m_aT[i], t))
return i;
}
return -1; // not found
}
BOOL SetAtIndex(
_In_ int nIndex,
_In_ const T& t)
{
if (nIndex < 0 || nIndex >= m_nSize)
return FALSE;
InternalSetAtIndex(nIndex, t);
return TRUE;
}
// Implementation // Implementation
class Wrapper class Wrapper
{ {
public: public:
Wrapper(_In_ const T& _t) : t(_t) Wrapper(_In_ const T& _t) : t(_t)
{ {
} }
template <class _Ty> template <class _Ty>
void * __cdecl operator new( void * __cdecl operator new(
_In_ size_t, _In_ size_t,
_In_ _Ty* p) _In_ _Ty* p)
{ {
return p; return p;
} }
template <class _Ty> template <class _Ty>
void __cdecl operator delete( void __cdecl operator delete(
_In_ void* /* pv */, _In_ void* /* pv */,
_In_ _Ty* /* p */) _In_ _Ty* /* p */)
{ {
} }
T t; T t;
}; };
// Implementation // Implementation
void InternalSetAtIndex( void InternalSetAtIndex(
_In_ int nIndex, _In_ int nIndex,
_In_ const T& t) _In_ const T& t)
{ {
new(m_aT + nIndex) Wrapper(t); new(m_aT + nIndex) Wrapper(t);
} }
typedef T _ArrayElementType; typedef T _ArrayElementType;
T* m_aT; T* m_aT;
int m_nSize; int m_nSize;
int m_nAllocSize; int m_nAllocSize;
}; };
#define CSimpleValArray CSimpleArray #define CSimpleValArray CSimpleArray
template <class T, class TEqual> inline CSimpleArray<T, TEqual>::~CSimpleArray() template <class T, class TEqual> inline CSimpleArray<T, TEqual>::~CSimpleArray()
{ {
RemoveAll(); RemoveAll();
} }
// intended for small number of simple types or pointers // intended for small number of simple types or pointers
@@ -308,204 +308,204 @@ template <class TKey, class TVal, class TEqual = CSimpleMapEqualHelper< TKey, TV
class CSimpleMap class CSimpleMap
{ {
public: public:
TKey* m_aKey; TKey* m_aKey;
TVal* m_aVal; TVal* m_aVal;
int m_nSize; int m_nSize;
typedef TKey _ArrayKeyType; typedef TKey _ArrayKeyType;
typedef TVal _ArrayElementType; typedef TVal _ArrayElementType;
// Construction/destruction // Construction/destruction
CSimpleMap() : CSimpleMap() :
m_aKey(NULL), m_aVal(NULL), m_nSize(0) m_aKey(NULL), m_aVal(NULL), m_nSize(0)
{ {
} }
~CSimpleMap() ~CSimpleMap()
{ {
RemoveAll(); RemoveAll();
} }
// Operations // Operations
int GetSize() const int GetSize() const
{ {
return m_nSize; return m_nSize;
} }
BOOL Add( BOOL Add(
_In_ const TKey& key, _In_ const TKey& key,
_In_ const TVal& val) _In_ const TVal& val)
{ {
TKey* pKey; TKey* pKey;
pKey = (TKey*)_recalloc(m_aKey, (m_nSize + 1), sizeof(TKey)); pKey = (TKey*)_recalloc(m_aKey, (m_nSize + 1), sizeof(TKey));
if(pKey == NULL) if(pKey == NULL)
return FALSE; return FALSE;
m_aKey = pKey; m_aKey = pKey;
TVal* pVal; TVal* pVal;
pVal = (TVal*)_recalloc(m_aVal, (m_nSize + 1), sizeof(TVal)); pVal = (TVal*)_recalloc(m_aVal, (m_nSize + 1), sizeof(TVal));
if(pVal == NULL) if(pVal == NULL)
return FALSE; return FALSE;
m_aVal = pVal; m_aVal = pVal;
InternalSetAtIndex(m_nSize, key, val); InternalSetAtIndex(m_nSize, key, val);
m_nSize++; m_nSize++;
return TRUE; return TRUE;
} }
BOOL Remove(_In_ const TKey& key) BOOL Remove(_In_ const TKey& key)
{ {
int nIndex = FindKey(key); int nIndex = FindKey(key);
if(nIndex == -1) if(nIndex == -1)
return FALSE; return FALSE;
return RemoveAt(nIndex); return RemoveAt(nIndex);
} }
BOOL RemoveAt(_In_ int nIndex) BOOL RemoveAt(_In_ int nIndex)
{ {
ATLASSERT(nIndex >= 0 && nIndex < m_nSize); ATLASSERT(nIndex >= 0 && nIndex < m_nSize);
if (nIndex < 0 || nIndex >= m_nSize) if (nIndex < 0 || nIndex >= m_nSize)
return FALSE; return FALSE;
m_aKey[nIndex].~TKey(); m_aKey[nIndex].~TKey();
m_aVal[nIndex].~TVal(); m_aVal[nIndex].~TVal();
if(nIndex != (m_nSize - 1)) if(nIndex != (m_nSize - 1))
{ {
Checked::memmove_s((void*)(m_aKey + nIndex), (m_nSize - nIndex) * sizeof(TKey), (void*)(m_aKey + nIndex + 1), (m_nSize - (nIndex + 1)) * sizeof(TKey)); Checked::memmove_s((void*)(m_aKey + nIndex), (m_nSize - nIndex) * sizeof(TKey), (void*)(m_aKey + nIndex + 1), (m_nSize - (nIndex + 1)) * sizeof(TKey));
Checked::memmove_s((void*)(m_aVal + nIndex), (m_nSize - nIndex) * sizeof(TVal), (void*)(m_aVal + nIndex + 1), (m_nSize - (nIndex + 1)) * sizeof(TVal)); Checked::memmove_s((void*)(m_aVal + nIndex), (m_nSize - nIndex) * sizeof(TVal), (void*)(m_aVal + nIndex + 1), (m_nSize - (nIndex + 1)) * sizeof(TVal));
} }
TKey* pKey; TKey* pKey;
pKey = (TKey*)_recalloc(m_aKey, (m_nSize - 1), sizeof(TKey)); pKey = (TKey*)_recalloc(m_aKey, (m_nSize - 1), sizeof(TKey));
if(pKey != NULL || m_nSize == 1) if(pKey != NULL || m_nSize == 1)
m_aKey = pKey; m_aKey = pKey;
TVal* pVal; TVal* pVal;
pVal = (TVal*)_recalloc(m_aVal, (m_nSize - 1), sizeof(TVal)); pVal = (TVal*)_recalloc(m_aVal, (m_nSize - 1), sizeof(TVal));
if(pVal != NULL || m_nSize == 1) if(pVal != NULL || m_nSize == 1)
m_aVal = pVal; m_aVal = pVal;
m_nSize--; m_nSize--;
return TRUE; return TRUE;
} }
void RemoveAll() void RemoveAll()
{ {
if(m_aKey != NULL) if(m_aKey != NULL)
{ {
for(int i = 0; i < m_nSize; i++) for(int i = 0; i < m_nSize; i++)
{ {
m_aKey[i].~TKey(); m_aKey[i].~TKey();
m_aVal[i].~TVal(); m_aVal[i].~TVal();
} }
nb_free(m_aKey); nb_free(m_aKey);
m_aKey = NULL; m_aKey = NULL;
} }
if(m_aVal != NULL) if(m_aVal != NULL)
{ {
nb_free(m_aVal); nb_free(m_aVal);
m_aVal = NULL; m_aVal = NULL;
} }
m_nSize = 0; m_nSize = 0;
} }
BOOL SetAt( BOOL SetAt(
_In_ const TKey& key, _In_ const TKey& key,
_In_ const TVal& val) _In_ const TVal& val)
{ {
int nIndex = FindKey(key); int nIndex = FindKey(key);
if(nIndex == -1) if(nIndex == -1)
return FALSE; return FALSE;
ATLASSERT(nIndex >= 0 && nIndex < m_nSize); ATLASSERT(nIndex >= 0 && nIndex < m_nSize);
m_aKey[nIndex].~TKey(); m_aKey[nIndex].~TKey();
m_aVal[nIndex].~TVal(); m_aVal[nIndex].~TVal();
InternalSetAtIndex(nIndex, key, val); InternalSetAtIndex(nIndex, key, val);
return TRUE; return TRUE;
} }
TVal Lookup(_In_ const TKey& key) const TVal Lookup(_In_ const TKey& key) const
{ {
int nIndex = FindKey(key); int nIndex = FindKey(key);
if(nIndex == -1) if(nIndex == -1)
return NULL; // must be able to convert return NULL; // must be able to convert
return GetValueAt(nIndex); return GetValueAt(nIndex);
} }
TKey ReverseLookup(_In_ const TVal& val) const TKey ReverseLookup(_In_ const TVal& val) const
{ {
int nIndex = FindVal(val); int nIndex = FindVal(val);
if(nIndex == -1) if(nIndex == -1)
return NULL; // must be able to convert return NULL; // must be able to convert
return GetKeyAt(nIndex); return GetKeyAt(nIndex);
} }
TKey& GetKeyAt(_In_ int nIndex) const TKey& GetKeyAt(_In_ int nIndex) const
{ {
ATLASSERT(nIndex >= 0 && nIndex < m_nSize); ATLASSERT(nIndex >= 0 && nIndex < m_nSize);
if(nIndex < 0 || nIndex >= m_nSize) if(nIndex < 0 || nIndex >= m_nSize)
_AtlRaiseException((DWORD)EXCEPTION_ARRAY_BOUNDS_EXCEEDED); _AtlRaiseException((DWORD)EXCEPTION_ARRAY_BOUNDS_EXCEEDED);
return m_aKey[nIndex]; return m_aKey[nIndex];
} }
TVal& GetValueAt(_In_ int nIndex) const TVal& GetValueAt(_In_ int nIndex) const
{ {
ATLASSERT(nIndex >= 0 && nIndex < m_nSize); ATLASSERT(nIndex >= 0 && nIndex < m_nSize);
if(nIndex < 0 || nIndex >= m_nSize) if(nIndex < 0 || nIndex >= m_nSize)
_AtlRaiseException((DWORD)EXCEPTION_ARRAY_BOUNDS_EXCEEDED); _AtlRaiseException((DWORD)EXCEPTION_ARRAY_BOUNDS_EXCEEDED);
return m_aVal[nIndex]; return m_aVal[nIndex];
} }
int FindKey(_In_ const TKey& key) const int FindKey(_In_ const TKey& key) const
{ {
for(int i = 0; i < m_nSize; i++) for(int i = 0; i < m_nSize; i++)
{ {
if(TEqual::IsEqualKey(m_aKey[i], key)) if(TEqual::IsEqualKey(m_aKey[i], key))
return i; return i;
} }
return -1; // not found return -1; // not found
} }
int FindVal(_In_ const TVal& val) const int FindVal(_In_ const TVal& val) const
{ {
for(int i = 0; i < m_nSize; i++) for(int i = 0; i < m_nSize; i++)
{ {
if(TEqual::IsEqualValue(m_aVal[i], val)) if(TEqual::IsEqualValue(m_aVal[i], val))
return i; return i;
} }
return -1; // not found return -1; // not found
} }
BOOL SetAtIndex( BOOL SetAtIndex(
_In_ int nIndex, _In_ int nIndex,
_In_ const TKey& key, _In_ const TKey& key,
_In_ const TVal& val) _In_ const TVal& val)
{ {
if (nIndex < 0 || nIndex >= m_nSize) if (nIndex < 0 || nIndex >= m_nSize)
return FALSE; return FALSE;
InternalSetAtIndex(nIndex, key, val); InternalSetAtIndex(nIndex, key, val);
return TRUE; return TRUE;
} }
// Implementation // Implementation
template <typename T> template <typename T>
class Wrapper class Wrapper
{ {
public: public:
Wrapper(_In_ const T& _t) : t(_t) Wrapper(_In_ const T& _t) : t(_t)
{ {
} }
template <class _Ty> template <class _Ty>
void *operator new( void *operator new(
_In_ size_t, _In_ size_t,
_In_ _Ty* p) _In_ _Ty* p)
{ {
return p; return p;
} }
template <class _Ty> template <class _Ty>
void operator delete( void operator delete(
_In_ void* /* pv */, _In_ void* /* pv */,
_In_ _Ty* /* p */) _In_ _Ty* /* p */)
{ {
} }
T t; T t;
}; };
void InternalSetAtIndex( void InternalSetAtIndex(
_In_ int nIndex, _In_ int nIndex,
_In_ const TKey& key, _In_ const TKey& key,
_In_ const TVal& val) _In_ const TVal& val)
{ {
new(m_aKey + nIndex) Wrapper<TKey>(key); new(m_aKey + nIndex) Wrapper<TKey>(key);
new(m_aVal + nIndex) Wrapper<TVal>(val); new(m_aVal + nIndex) Wrapper<TVal>(val);
} }
}; };
#pragma pop_macro("new") #pragma pop_macro("new")

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.activeX; package com.jacob.activeX;
@@ -54,72 +54,72 @@ import com.jacob.com.InvocationProxy;
*/ */
public class ActiveXDispatchEvents extends DispatchEvents { public class ActiveXDispatchEvents extends DispatchEvents {
/** /**
* This is the most commonly used constructor. * This is the most commonly used constructor.
* <p> * <p>
* Creates the event callback linkage between the the MS program represented * Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the * by the Dispatch object and the Java object that will receive the
* callback. * callback.
* *
* @param sourceOfEvent * @param sourceOfEvent
* Dispatch object who's MS app will generate callbacks * Dispatch object who's MS app will generate callbacks
* @param eventSink * @param eventSink
* Java object that wants to receive the events * Java object that wants to receive the events
*/ */
public ActiveXDispatchEvents(Dispatch sourceOfEvent, Object eventSink) { public ActiveXDispatchEvents(Dispatch sourceOfEvent, Object eventSink) {
super(sourceOfEvent, eventSink, null); super(sourceOfEvent, eventSink, null);
} }
/** /**
* None of the samples use this constructor. * None of the samples use this constructor.
* <p> * <p>
* Creates the event callback linkage between the the MS program represented * Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the * by the Dispatch object and the Java object that will receive the
* callback. * callback.
* *
* @param sourceOfEvent * @param sourceOfEvent
* Dispatch object who's MS app will generate callbacks * Dispatch object who's MS app will generate callbacks
* @param eventSink * @param eventSink
* Java object that wants to receive the events * Java object that wants to receive the events
* @param progId * @param progId
* ??? * ???
*/ */
public ActiveXDispatchEvents(Dispatch sourceOfEvent, Object eventSink, public ActiveXDispatchEvents(Dispatch sourceOfEvent, Object eventSink,
String progId) { String progId) {
super(sourceOfEvent, eventSink, progId, null); super(sourceOfEvent, eventSink, progId, null);
} }
/** /**
* Creates the event callback linkage between the the MS program represented * Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the * by the Dispatch object and the Java object that will receive the
* callback. * callback.
* *
* <pre> * <pre>
* &gt;ActiveXDispatchEvents de = * &gt;ActiveXDispatchEvents de =
* new ActiveXDispatchEvents(someDispatch,someEventHAndler, * new ActiveXDispatchEvents(someDispatch,someEventHAndler,
* &quot;Excel.Application&quot;, * &quot;Excel.Application&quot;,
* &quot;C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE&quot;); * &quot;C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE&quot;);
* *
* @param sourceOfEvent Dispatch object who's MS app will generate callbacks * @param sourceOfEvent Dispatch object who's MS app will generate callbacks
* @param eventSink Java object that wants to receive the events * @param eventSink Java object that wants to receive the events
* @param progId , mandatory if the typelib is specified * @param progId , mandatory if the typelib is specified
* @param typeLib The location of the typelib to use * @param typeLib The location of the typelib to use
* *
*/ */
public ActiveXDispatchEvents(Dispatch sourceOfEvent, Object eventSink, public ActiveXDispatchEvents(Dispatch sourceOfEvent, Object eventSink,
String progId, String typeLib) { String progId, String typeLib) {
super(sourceOfEvent, eventSink, progId, typeLib); super(sourceOfEvent, eventSink, progId, typeLib);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see com.jacob.com.DispatchEvents#getInvocationProxy(java.lang.Object) * @see com.jacob.com.DispatchEvents#getInvocationProxy(java.lang.Object)
*/ */
protected InvocationProxy getInvocationProxy(Object pTargetObject) { protected InvocationProxy getInvocationProxy(Object pTargetObject) {
InvocationProxy newProxy = new ActiveXInvocationProxy(); InvocationProxy newProxy = new ActiveXInvocationProxy();
newProxy.setTarget(pTargetObject); newProxy.setTarget(pTargetObject);
return newProxy; return newProxy;
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.activeX; package com.jacob.activeX;
@@ -72,131 +72,131 @@ import com.jacob.com.Variant;
*/ */
public class ActiveXInvocationProxy extends InvocationProxy { public class ActiveXInvocationProxy extends InvocationProxy {
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see com.jacob.com.InvocationProxy#invoke(java.lang.String, * @see com.jacob.com.InvocationProxy#invoke(java.lang.String,
* com.jacob.com.Variant[]) * com.jacob.com.Variant[])
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Variant invoke(String methodName, Variant targetParameters[]) { public Variant invoke(String methodName, Variant targetParameters[]) {
Variant mVariantToBeReturned = null; Variant mVariantToBeReturned = null;
if (mTargetObject == null) { if (mTargetObject == null) {
// structured programming guidlines say this return should not be up // structured programming guidlines say this return should not be up
// here // here
return null; return null;
} }
Class targetClass = mTargetObject.getClass(); Class targetClass = mTargetObject.getClass();
if (methodName == null) { if (methodName == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"InvocationProxy: missing method name"); "InvocationProxy: missing method name");
} }
if (targetParameters == null) { if (targetParameters == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"InvocationProxy: missing Variant parameters"); "InvocationProxy: missing Variant parameters");
} }
try { try {
Method targetMethod; Method targetMethod;
Object parametersAsJavaObjects[] = getParametersAsJavaObjects(targetParameters); Object parametersAsJavaObjects[] = getParametersAsJavaObjects(targetParameters);
Class parametersAsJavaClasses[] = getParametersAsJavaClasses(parametersAsJavaObjects); Class parametersAsJavaClasses[] = getParametersAsJavaClasses(parametersAsJavaObjects);
targetMethod = targetClass.getMethod(methodName, targetMethod = targetClass.getMethod(methodName,
parametersAsJavaClasses); parametersAsJavaClasses);
if (targetMethod != null) { if (targetMethod != null) {
// protected classes can't be invoked against even if they // protected classes can't be invoked against even if they
// let you grab the method. you could do // let you grab the method. you could do
// targetMethod.setAccessible(true); // targetMethod.setAccessible(true);
// but that should be stopped by the security manager // but that should be stopped by the security manager
Object mReturnedByInvocation = null; Object mReturnedByInvocation = null;
mReturnedByInvocation = targetMethod.invoke(mTargetObject, mReturnedByInvocation = targetMethod.invoke(mTargetObject,
parametersAsJavaObjects); parametersAsJavaObjects);
if (mReturnedByInvocation == null) { if (mReturnedByInvocation == null) {
mVariantToBeReturned = null; mVariantToBeReturned = null;
} else if (!(mReturnedByInvocation instanceof Variant)) { } else if (!(mReturnedByInvocation instanceof Variant)) {
mVariantToBeReturned = new Variant(mReturnedByInvocation); mVariantToBeReturned = new Variant(mReturnedByInvocation);
} else { } else {
mVariantToBeReturned = (Variant) mReturnedByInvocation; mVariantToBeReturned = (Variant) mReturnedByInvocation;
} }
} }
} catch (SecurityException e) { } catch (SecurityException e) {
// what causes this exception? // what causes this exception?
e.printStackTrace(); e.printStackTrace();
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
// this happens whenever the listener doesn't implement all the // this happens whenever the listener doesn't implement all the
// methods // methods
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// we can throw these inside the catch block so need to re-throw it // we can throw these inside the catch block so need to re-throw it
Exception oneWeShouldToss = new IllegalArgumentException( Exception oneWeShouldToss = new IllegalArgumentException(
"Unable to map parameters for method " + methodName + ": " "Unable to map parameters for method " + methodName + ": "
+ e.toString()); + e.toString());
oneWeShouldToss.printStackTrace(); oneWeShouldToss.printStackTrace();
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
// can't access the method on the target instance for some reason // can't access the method on the target instance for some reason
e.printStackTrace(); e.printStackTrace();
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
// invocation of target method failed // invocation of target method failed
e.printStackTrace(); e.printStackTrace();
} }
return mVariantToBeReturned; return mVariantToBeReturned;
} }
/** /**
* creates a method signature compatible array of classes from an array of * creates a method signature compatible array of classes from an array of
* parameters * parameters
* *
* @param parametersAsJavaObjects * @param parametersAsJavaObjects
* @return * @return
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Class[] getParametersAsJavaClasses(Object[] parametersAsJavaObjects) { private Class[] getParametersAsJavaClasses(Object[] parametersAsJavaObjects) {
if (parametersAsJavaObjects == null) { if (parametersAsJavaObjects == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"This only works with an array of parameters"); "This only works with an array of parameters");
} }
int numParameters = parametersAsJavaObjects.length; int numParameters = parametersAsJavaObjects.length;
Class parametersAsJavaClasses[] = new Class[numParameters]; Class parametersAsJavaClasses[] = new Class[numParameters];
for (int parameterIndex = 0; parameterIndex < numParameters; parameterIndex++) { for (int parameterIndex = 0; parameterIndex < numParameters; parameterIndex++) {
Object oneParameterObject = parametersAsJavaObjects[parameterIndex]; Object oneParameterObject = parametersAsJavaObjects[parameterIndex];
if (oneParameterObject == null) { if (oneParameterObject == null) {
parametersAsJavaClasses[parameterIndex] = null; parametersAsJavaClasses[parameterIndex] = null;
} else { } else {
Class oneParameterClass = oneParameterObject.getClass(); Class oneParameterClass = oneParameterObject.getClass();
parametersAsJavaClasses[parameterIndex] = oneParameterClass; parametersAsJavaClasses[parameterIndex] = oneParameterClass;
} }
} }
return parametersAsJavaClasses; return parametersAsJavaClasses;
} }
/** /**
* converts an array of Variants to their associated Java types * converts an array of Variants to their associated Java types
* *
* @param targetParameters * @param targetParameters
* @return * @return
*/ */
private Object[] getParametersAsJavaObjects(Variant[] targetParameters) { private Object[] getParametersAsJavaObjects(Variant[] targetParameters) {
if (targetParameters == null) { if (targetParameters == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"This only works with an array of parameters"); "This only works with an array of parameters");
} }
int numParameters = targetParameters.length; int numParameters = targetParameters.length;
Object parametersAsJavaObjects[] = new Object[numParameters]; Object parametersAsJavaObjects[] = new Object[numParameters];
for (int parameterIndex = 0; parameterIndex < numParameters; parameterIndex++) { for (int parameterIndex = 0; parameterIndex < numParameters; parameterIndex++) {
Variant oneParameterObject = targetParameters[parameterIndex]; Variant oneParameterObject = targetParameters[parameterIndex];
if (oneParameterObject == null) { if (oneParameterObject == null) {
parametersAsJavaObjects[parameterIndex] = null; parametersAsJavaObjects[parameterIndex] = null;
} else { } else {
try { try {
parametersAsJavaObjects[parameterIndex] = oneParameterObject parametersAsJavaObjects[parameterIndex] = oneParameterObject
.toJavaObject(); .toJavaObject();
} catch (NotImplementedException nie) { } catch (NotImplementedException nie) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Can't convert parameter " + parameterIndex "Can't convert parameter " + parameterIndex
+ " type " + oneParameterObject.getvt() + " type " + oneParameterObject.getvt()
+ " to java object: " + nie.getMessage()); + " to java object: " + nie.getMessage());
} }
} }
} }
return parametersAsJavaObjects; return parametersAsJavaObjects;
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -43,118 +43,118 @@ package com.jacob.com;
*/ */
public abstract class ComException extends JacobException { public abstract class ComException extends JacobException {
/** /**
* COM code initializes this filed with an appropriate return code that was * COM code initializes this filed with an appropriate return code that was
* returned by the underlying com code * returned by the underlying com code
*/ */
protected int hr; protected int hr;
/** /**
* No documentation is available at this time. Someone should document this * No documentation is available at this time. Someone should document this
* field * field
*/ */
protected int m_helpContext; protected int m_helpContext;
/** /**
* No documentation is available at this time. Someone should document this * No documentation is available at this time. Someone should document this
* field * field
*/ */
protected String m_helpFile; protected String m_helpFile;
/** /**
* No documentation is available at this time. Someone should document this * No documentation is available at this time. Someone should document this
* field * field
*/ */
protected String m_source; protected String m_source;
/** /**
* constructor * constructor
* *
*/ */
public ComException() { public ComException() {
super(); super();
} }
/** /**
* constructor with error code? * constructor with error code?
* *
* @param newHr ?? * @param newHr ??
*/ */
public ComException(int newHr) { public ComException(int newHr) {
super(); super();
this.hr = newHr; this.hr = newHr;
} }
/** /**
* @param newHr * @param newHr
* @param description * @param description
*/ */
public ComException(int newHr, String description) { public ComException(int newHr, String description) {
super(description); super(description);
this.hr = newHr; this.hr = newHr;
} }
/** /**
* @param newHr * @param newHr
* @param source * @param source
* @param helpFile * @param helpFile
* @param helpContext * @param helpContext
*/ */
public ComException(int newHr, String source, String helpFile, public ComException(int newHr, String source, String helpFile,
int helpContext) { int helpContext) {
super(); super();
this.hr = newHr; this.hr = newHr;
m_source = source; m_source = source;
m_helpFile = helpFile; m_helpFile = helpFile;
m_helpContext = helpContext; m_helpContext = helpContext;
} }
/** /**
* @param newHr * @param newHr
* @param description * @param description
* @param source * @param source
* @param helpFile * @param helpFile
* @param helpContext * @param helpContext
*/ */
public ComException(int newHr, String description, String source, public ComException(int newHr, String description, String source,
String helpFile, int helpContext) { String helpFile, int helpContext) {
super(description); super(description);
this.hr = newHr; this.hr = newHr;
m_source = source; m_source = source;
m_helpFile = helpFile; m_helpFile = helpFile;
m_helpContext = helpContext; m_helpContext = helpContext;
} }
/** /**
* @param description * @param description
*/ */
public ComException(String description) { public ComException(String description) {
super(description); super(description);
} }
/** /**
* @return int representation of the help context * @return int representation of the help context
*/ */
// Methods // Methods
public int getHelpContext() { public int getHelpContext() {
return m_helpContext; return m_helpContext;
} }
/** /**
* @return String ??? help file * @return String ??? help file
*/ */
public String getHelpFile() { public String getHelpFile() {
return m_helpFile; return m_helpFile;
} }
/** /**
* @return int hr result ?? * @return int hr result ??
*/ */
public int getHResult() { public int getHResult() {
return hr; return hr;
} }
/** /**
* @return String source ?? * @return String source ??
*/ */
public String getSource() { public String getSource() {
return m_source; return m_source;
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -42,66 +42,66 @@ package com.jacob.com;
* COM Fail Exception class raised when there is a problem * COM Fail Exception class raised when there is a problem
*/ */
public class ComFailException extends ComException { public class ComFailException extends ComException {
/** /**
* eclipse generated to get rid of a wanring * eclipse generated to get rid of a wanring
*/ */
private static final long serialVersionUID = -266047261992987700L; private static final long serialVersionUID = -266047261992987700L;
/** /**
* Constructor * Constructor
* *
* @param hrNew * @param hrNew
*/ */
public ComFailException(int hrNew) { public ComFailException(int hrNew) {
super(hrNew); super(hrNew);
} }
/** /**
* Constructor * Constructor
* *
* @param hrNew * @param hrNew
* @param message * @param message
*/ */
public ComFailException(int hrNew, String message) { public ComFailException(int hrNew, String message) {
super(hrNew, message); super(hrNew, message);
} }
/** /**
* @param hrNew * @param hrNew
* @param source * @param source
* @param helpFile * @param helpFile
* @param helpContext * @param helpContext
*/ */
public ComFailException(int hrNew, String source, String helpFile, public ComFailException(int hrNew, String source, String helpFile,
int helpContext) { int helpContext) {
super(hrNew, source, helpFile, helpContext); super(hrNew, source, helpFile, helpContext);
} }
/** /**
* Constructor * Constructor
* *
* @param hrNew * @param hrNew
* @param description * @param description
* @param source * @param source
* @param helpFile * @param helpFile
* @param helpContext * @param helpContext
*/ */
public ComFailException(int hrNew, String description, String source, public ComFailException(int hrNew, String description, String source,
String helpFile, int helpContext) { String helpFile, int helpContext) {
super(hrNew, description, source, helpFile, helpContext); super(hrNew, description, source, helpFile, helpContext);
} }
/** /**
* No argument Constructor * No argument Constructor
*/ */
public ComFailException() { public ComFailException() {
super(); super();
} }
/** /**
* @param message * @param message
*/ */
public ComFailException(String message) { public ComFailException(String message) {
super(message); super(message);
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -43,146 +43,146 @@ package com.jacob.com;
* methods are static and no instances are ever created. * methods are static and no instances are ever created.
*/ */
public abstract class ComThread { public abstract class ComThread {
private static final int MTA = 0x0; private static final int MTA = 0x0;
private static final int STA = 0x2; private static final int STA = 0x2;
/** /**
* Comment for <code>haveSTA</code> * Comment for <code>haveSTA</code>
*/ */
public static boolean haveSTA = false; public static boolean haveSTA = false;
/** /**
* Comment for <code>mainSTA</code> * Comment for <code>mainSTA</code>
*/ */
public static MainSTA mainSTA = null; public static MainSTA mainSTA = null;
/** /**
* Initialize the current java thread to be part of the Multi-threaded COM * Initialize the current java thread to be part of the Multi-threaded COM
* Apartment * Apartment
*/ */
public static synchronized void InitMTA() { public static synchronized void InitMTA() {
InitMTA(false); InitMTA(false);
} }
/** /**
* Initialize the current java thread to be an STA * Initialize the current java thread to be an STA
*/ */
public static synchronized void InitSTA() { public static synchronized void InitSTA() {
InitSTA(false); InitSTA(false);
} }
/** /**
* Initialize the current java thread to be part of the Multi-threaded COM * Initialize the current java thread to be part of the Multi-threaded COM
* Apartment, if createMainSTA is true, create a separate MainSTA thread * Apartment, if createMainSTA is true, create a separate MainSTA thread
* that will house all Apartment Threaded components * that will house all Apartment Threaded components
* *
* @param createMainSTA * @param createMainSTA
*/ */
public static synchronized void InitMTA(boolean createMainSTA) { public static synchronized void InitMTA(boolean createMainSTA) {
Init(createMainSTA, MTA); Init(createMainSTA, MTA);
} }
/** /**
* Initialize the current java thread to be an STA COM Apartment, if * Initialize the current java thread to be an STA COM Apartment, if
* createMainSTA is true, create a separate MainSTA thread that will house * createMainSTA is true, create a separate MainSTA thread that will house
* all Apartment Threaded components * all Apartment Threaded components
* *
* @param createMainSTA * @param createMainSTA
*/ */
public static synchronized void InitSTA(boolean createMainSTA) { public static synchronized void InitSTA(boolean createMainSTA) {
Init(createMainSTA, STA); Init(createMainSTA, STA);
} }
/** /**
* *
*/ */
public static synchronized void startMainSTA() { public static synchronized void startMainSTA() {
mainSTA = new MainSTA(); mainSTA = new MainSTA();
haveSTA = true; haveSTA = true;
} }
/** /**
* *
*/ */
public static synchronized void quitMainSTA() { public static synchronized void quitMainSTA() {
if (mainSTA != null) if (mainSTA != null)
mainSTA.quit(); mainSTA.quit();
} }
/** /**
* Initialize the current java thread to be part of the MTA/STA COM * Initialize the current java thread to be part of the MTA/STA COM
* Apartment * Apartment
* *
* @param createMainSTA * @param createMainSTA
* @param mode * @param mode
*/ */
public static synchronized void Init(boolean createMainSTA, int mode) { public static synchronized void Init(boolean createMainSTA, int mode) {
if (createMainSTA && !haveSTA) { if (createMainSTA && !haveSTA) {
// if the current thread is going to be in the MTA and there // if the current thread is going to be in the MTA and there
// is no STA thread yet, then create a main STA thread // is no STA thread yet, then create a main STA thread
// to avoid COM creating its own // to avoid COM creating its own
startMainSTA(); startMainSTA();
} }
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: before Init: " + mode); JacobObject.debug("ComThread: before Init: " + mode);
} }
doCoInitialize(mode); doCoInitialize(mode);
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: after Init: " + mode); JacobObject.debug("ComThread: after Init: " + mode);
} }
ROT.addThread(); ROT.addThread();
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: after ROT.addThread: " + mode); JacobObject.debug("ComThread: after ROT.addThread: " + mode);
} }
} }
/** /**
* Call CoUninitialize to release this java thread from COM * Call CoUninitialize to release this java thread from COM
*/ */
public static synchronized void Release() { public static synchronized void Release() {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: before clearObjects"); JacobObject.debug("ComThread: before clearObjects");
} }
ROT.clearObjects(); ROT.clearObjects();
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: before UnInit"); JacobObject.debug("ComThread: before UnInit");
} }
doCoUninitialize(); doCoUninitialize();
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: after UnInit"); JacobObject.debug("ComThread: after UnInit");
} }
} }
/** /**
* @deprecated the java model leave the responsibility of clearing up * @deprecated the java model leave the responsibility of clearing up
* objects to the Garbage Collector. Our programming model * objects to the Garbage Collector. Our programming model
* should not require that the user specifically remove object * should not require that the user specifically remove object
* from the thread. * from the thread.
* *
* This will remove an object from the ROT * This will remove an object from the ROT
* @param o * @param o
*/ */
@Deprecated @Deprecated
public static synchronized void RemoveObject(JacobObject o) { public static synchronized void RemoveObject(JacobObject o) {
ROT.removeObject(o); ROT.removeObject(o);
} }
/** /**
* @param threadModel * @param threadModel
*/ */
public static native void doCoInitialize(int threadModel); public static native void doCoInitialize(int threadModel);
/** /**
* *
*/ */
public static native void doCoUninitialize(); public static native void doCoUninitialize();
/** /**
* load the Jacob DLL. We do this in case COMThread is called before any * load the Jacob DLL. We do this in case COMThread is called before any
* other reference to one of the JacboObject subclasses is made. * other reference to one of the JacboObject subclasses is made.
*/ */
static { static {
LibraryLoader.loadJacobLibrary(); LibraryLoader.loadJacobLibrary();
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -49,81 +49,81 @@ package com.jacob.com;
* In the future, this should convert to and from BigDecimal or Double * In the future, this should convert to and from BigDecimal or Double
*/ */
public class Currency { public class Currency {
Long embeddedValue = null; Long embeddedValue = null;
/** /**
* constructor that takes a long already in COM representation * constructor that takes a long already in COM representation
* *
* @param newValue * @param newValue
*/ */
public Currency(long newValue) { public Currency(long newValue) {
embeddedValue = new Long(newValue); embeddedValue = new Long(newValue);
} }
/** /**
* constructor that takes a String already in COM representation * constructor that takes a String already in COM representation
* *
* @param newValue * @param newValue
*/ */
public Currency(String newValue) { public Currency(String newValue) {
embeddedValue = new Long(newValue); embeddedValue = new Long(newValue);
} }
/** /**
* *
* @return the currency as a primitive long * @return the currency as a primitive long
*/ */
public long longValue() { public long longValue() {
return embeddedValue.longValue(); return embeddedValue.longValue();
} }
/** /**
* getter to the inner storage so that cmpareTo can work * getter to the inner storage so that cmpareTo can work
* *
* @return the embedded long value * @return the embedded long value
*/ */
protected Long getLongValue() { protected Long getLongValue() {
return embeddedValue; return embeddedValue;
} }
/** /**
* compares the values of two currencies * compares the values of two currencies
* *
* @param anotherCurrency * @param anotherCurrency
* @return the usual compareTo results * @return the usual compareTo results
*/ */
public int compareTo(Currency anotherCurrency) { public int compareTo(Currency anotherCurrency) {
return embeddedValue.compareTo(anotherCurrency.getLongValue()); return embeddedValue.compareTo(anotherCurrency.getLongValue());
} }
/** /**
* standard comparison * standard comparison
* *
* @param o * @param o
* must be Currency or Long * must be Currency or Long
* @return the usual compareTo results * @return the usual compareTo results
*/ */
public int compareTo(Object o) { public int compareTo(Object o) {
if (o instanceof Currency) { if (o instanceof Currency) {
return compareTo((Currency) o); return compareTo((Currency) o);
} else if (o instanceof Long) { } else if (o instanceof Long) {
return embeddedValue.compareTo((Long) o); return embeddedValue.compareTo((Long) o);
} else } else
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Can only compare to Long and Currency not " "Can only compare to Long and Currency not "
+ o.getClass().getName()); + o.getClass().getName());
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == null) { if (o == null) {
return false; return false;
} else if (compareTo(o) == 0) { } else if (compareTo(o) == 0) {
return true; return true;
} else { } else {
return false; return false;
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -49,76 +49,76 @@ import java.util.Date;
*/ */
public class DateUtilities { public class DateUtilities {
/** /**
* converts a windows time to a Java Date Object * converts a windows time to a Java Date Object
* *
* @param comTime * @param comTime
* @return Date object representing the windows time as specified in comTime * @return Date object representing the windows time as specified in comTime
*/ */
static public Date convertWindowsTimeToDate(double comTime) { static public Date convertWindowsTimeToDate(double comTime) {
return new Date(convertWindowsTimeToMilliseconds(comTime)); return new Date(convertWindowsTimeToMilliseconds(comTime));
} }
/** /**
* Convert a COM time from functions Date(), Time(), Now() to a Java time * Convert a COM time from functions Date(), Time(), Now() to a Java time
* (milliseconds). Visual Basic time values are based to 30.12.1899, Java * (milliseconds). Visual Basic time values are based to 30.12.1899, Java
* time values are based to 1.1.1970 (= 0 milliseconds). The difference is * time values are based to 1.1.1970 (= 0 milliseconds). The difference is
* added to the Visual Basic value to get the corresponding Java value. The * added to the Visual Basic value to get the corresponding Java value. The
* Visual Basic double value reads: <day count delta since 30.12.1899>.<1 * Visual Basic double value reads: <day count delta since 30.12.1899>.<1
* day percentage fraction>, e.g. "38100.6453" means: 38100 days since * day percentage fraction>, e.g. "38100.6453" means: 38100 days since
* 30.12.1899 plus (24 hours * 0.6453). Example usage: * 30.12.1899 plus (24 hours * 0.6453). Example usage:
* <code>Date javaDate = new Date(toMilliseconds (vbDate));</code>. * <code>Date javaDate = new Date(toMilliseconds (vbDate));</code>.
* *
* @param comTime * @param comTime
* COM time. * COM time.
* @return Java time. * @return Java time.
*/ */
static public long convertWindowsTimeToMilliseconds(double comTime) { static public long convertWindowsTimeToMilliseconds(double comTime) {
long result = 0; long result = 0;
// code from jacobgen: // code from jacobgen:
comTime = comTime - 25569D; comTime = comTime - 25569D;
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
result = Math.round(86400000L * comTime) result = Math.round(86400000L * comTime)
- cal.get(Calendar.ZONE_OFFSET); - cal.get(Calendar.ZONE_OFFSET);
cal.setTime(new Date(result)); cal.setTime(new Date(result));
result -= cal.get(Calendar.DST_OFFSET); result -= cal.get(Calendar.DST_OFFSET);
return result; return result;
}// convertWindowsTimeToMilliseconds() }// convertWindowsTimeToMilliseconds()
/** /**
* converts a java date to a windows time object (is this timezone safe?) * converts a java date to a windows time object (is this timezone safe?)
* *
* @param javaDate * @param javaDate
* the java date to be converted to windows time * the java date to be converted to windows time
* @return the double representing the date in a form windows understands * @return the double representing the date in a form windows understands
*/ */
static public double convertDateToWindowsTime(Date javaDate) { static public double convertDateToWindowsTime(Date javaDate) {
if (javaDate == null) { if (javaDate == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"cannot convert null to windows time"); "cannot convert null to windows time");
} }
return convertMillisecondsToWindowsTime(javaDate.getTime()); return convertMillisecondsToWindowsTime(javaDate.getTime());
} }
/** /**
* Convert a Java time to a COM time. * Convert a Java time to a COM time.
* *
* @param milliseconds * @param milliseconds
* Java time. * Java time.
* @return COM time. * @return COM time.
*/ */
static public double convertMillisecondsToWindowsTime(long milliseconds) { static public double convertMillisecondsToWindowsTime(long milliseconds) {
double result = 0.0; double result = 0.0;
// code from jacobgen: // code from jacobgen:
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(milliseconds); cal.setTimeInMillis(milliseconds);
milliseconds += (cal.get(Calendar.ZONE_OFFSET) + cal milliseconds += (cal.get(Calendar.ZONE_OFFSET) + cal
.get(Calendar.DST_OFFSET)); // add GMT offset .get(Calendar.DST_OFFSET)); // add GMT offset
result = (milliseconds / 86400000D) + 25569D; result = (milliseconds / 86400000D) + 25569D;
return result; return result;
}// convertMillisecondsToWindowsTime() }// convertMillisecondsToWindowsTime()
} }

File diff suppressed because it is too large Load Diff

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -59,180 +59,180 @@ package com.jacob.com;
*/ */
public class DispatchEvents extends JacobObject { public class DispatchEvents extends JacobObject {
/** /**
* pointer to an MS data struct. The COM layer knows the name of this * pointer to an MS data struct. The COM layer knows the name of this
* variable and puts the windows memory pointer here. * variable and puts the windows memory pointer here.
*/ */
int m_pConnPtProxy = 0; int m_pConnPtProxy = 0;
/** /**
* the wrapper for the event sink. This object is the one that will be sent * the wrapper for the event sink. This object is the one that will be sent
* a message when an event occurs in the MS layer. Normally, the * a message when an event occurs in the MS layer. Normally, the
* InvocationProxy will forward the messages to a wrapped object that it * InvocationProxy will forward the messages to a wrapped object that it
* contains. * contains.
*/ */
InvocationProxy mInvocationProxy = null; InvocationProxy mInvocationProxy = null;
/** /**
* This is the most commonly used constructor. * This is the most commonly used constructor.
* <p> * <p>
* Creates the event callback linkage between the the MS program represented * Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the * by the Dispatch object and the Java object that will receive the
* callback. * callback.
* <p> * <p>
* Can be used on any object that implements IProvideClassInfo. * Can be used on any object that implements IProvideClassInfo.
* *
* @param sourceOfEvent * @param sourceOfEvent
* Dispatch object who's MS app will generate callbacks * Dispatch object who's MS app will generate callbacks
* @param eventSink * @param eventSink
* Java object that wants to receive the events * Java object that wants to receive the events
*/ */
public DispatchEvents(Dispatch sourceOfEvent, Object eventSink) { public DispatchEvents(Dispatch sourceOfEvent, Object eventSink) {
this(sourceOfEvent, eventSink, null); this(sourceOfEvent, eventSink, null);
} }
/** /**
* None of the samples use this constructor. * None of the samples use this constructor.
* <p> * <p>
* Creates the event callback linkage between the the MS program represented * Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the * by the Dispatch object and the Java object that will receive the
* callback. * callback.
* <p> * <p>
* Used when the program doesn't implement IProvideClassInfo. It provides a * Used when the program doesn't implement IProvideClassInfo. It provides a
* way to find the TypeLib in the registry based on the programId. The * way to find the TypeLib in the registry based on the programId. The
* TypeLib is looked up in the registry on the path * TypeLib is looked up in the registry on the path
* HKEY_LOCAL_MACHINE/SOFTWARE/Classes/CLSID/(CLID drived from * HKEY_LOCAL_MACHINE/SOFTWARE/Classes/CLSID/(CLID drived from
* progid)/ProgID/Typelib * progid)/ProgID/Typelib
* *
* @param sourceOfEvent * @param sourceOfEvent
* Dispatch object who's MS app will generate callbacks * Dispatch object who's MS app will generate callbacks
* @param eventSink * @param eventSink
* Java object that wants to receive the events * Java object that wants to receive the events
* @param progId * @param progId
* program id in the registry that has a TypeLib subkey. The * program id in the registry that has a TypeLib subkey. The
* progrId is mapped to a CLSID that is they used to look up the * progrId is mapped to a CLSID that is they used to look up the
* key to the Typelib * key to the Typelib
*/ */
public DispatchEvents(Dispatch sourceOfEvent, Object eventSink, public DispatchEvents(Dispatch sourceOfEvent, Object eventSink,
String progId) { String progId) {
this(sourceOfEvent, eventSink, progId, null); this(sourceOfEvent, eventSink, progId, null);
} }
/** /**
* Creates the event callback linkage between the the MS program represented * Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the * by the Dispatch object and the Java object that will receive the
* callback. * callback.
* <p> * <p>
* This method was added because Excel doesn't implement IProvideClassInfo * This method was added because Excel doesn't implement IProvideClassInfo
* and the registry entry for Excel.Application doesn't include a typelib * and the registry entry for Excel.Application doesn't include a typelib
* key. * key.
* *
* <pre> * <pre>
* DispatchEvents de = new DispatchEvents(someDispatch, someEventHAndler, * DispatchEvents de = new DispatchEvents(someDispatch, someEventHAndler,
* &quot;Excel.Application&quot;, * &quot;Excel.Application&quot;,
* &quot;C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE&quot;); * &quot;C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE&quot;);
* </pre> * </pre>
* *
* @param sourceOfEvent * @param sourceOfEvent
* Dispatch object who's MS app will generate callbacks * Dispatch object who's MS app will generate callbacks
* @param eventSink * @param eventSink
* Java object that wants to receive the events * Java object that wants to receive the events
* @param progId , * @param progId ,
* mandatory if the typelib is specified * mandatory if the typelib is specified
* @param typeLib * @param typeLib
* The location of the typelib to use * The location of the typelib to use
*/ */
public DispatchEvents(Dispatch sourceOfEvent, Object eventSink, public DispatchEvents(Dispatch sourceOfEvent, Object eventSink,
String progId, String typeLib) { String progId, String typeLib) {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
System.out.println("DispatchEvents: Registering " + eventSink System.out.println("DispatchEvents: Registering " + eventSink
+ "for events "); + "for events ");
} }
if (eventSink instanceof InvocationProxy) { if (eventSink instanceof InvocationProxy) {
mInvocationProxy = (InvocationProxy) eventSink; mInvocationProxy = (InvocationProxy) eventSink;
} else { } else {
mInvocationProxy = getInvocationProxy(eventSink); mInvocationProxy = getInvocationProxy(eventSink);
} }
if (mInvocationProxy != null) { if (mInvocationProxy != null) {
init3(sourceOfEvent, mInvocationProxy, progId, typeLib); init3(sourceOfEvent, mInvocationProxy, progId, typeLib);
} else { } else {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("Cannot register null event sink for events"); JacobObject.debug("Cannot register null event sink for events");
} }
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Cannot register null event sink for events"); "Cannot register null event sink for events");
} }
} }
/** /**
* Returns an instance of the proxy configured with pTargetObject as its * Returns an instance of the proxy configured with pTargetObject as its
* target * target
* *
* @param pTargetObject * @param pTargetObject
* @return InvocationProxy an instance of the proxy this DispatchEvents will * @return InvocationProxy an instance of the proxy this DispatchEvents will
* send to the COM layer * send to the COM layer
*/ */
protected InvocationProxy getInvocationProxy(Object pTargetObject) { protected InvocationProxy getInvocationProxy(Object pTargetObject) {
InvocationProxy newProxy = new InvocationProxyAllVariants(); InvocationProxy newProxy = new InvocationProxyAllVariants();
newProxy.setTarget(pTargetObject); newProxy.setTarget(pTargetObject);
return newProxy; return newProxy;
} }
/** /**
* hooks up a connection point proxy by progId event methods on the sink * hooks up a connection point proxy by progId event methods on the sink
* object will be called by name with a signature of <name>(Variant[] args) * object will be called by name with a signature of <name>(Variant[] args)
* *
* You must specify the location of the typeLib. * You must specify the location of the typeLib.
* *
* @param src * @param src
* dispatch that is the source of the messages * dispatch that is the source of the messages
* @param sink * @param sink
* the object that will receive the messages * the object that will receive the messages
* @param progId * @param progId
* optional program id. most folks don't need this either * optional program id. most folks don't need this either
* @param typeLib * @param typeLib
* optional parameter for those programs that don't register * optional parameter for those programs that don't register
* their type libs (like Excel) * their type libs (like Excel)
*/ */
private native void init3(Dispatch src, Object sink, String progId, private native void init3(Dispatch src, Object sink, String progId,
String typeLib); String typeLib);
/** /**
* now private so only this object can asccess was: call this to explicitly * now private so only this object can asccess was: call this to explicitly
* release the com object before gc * release the com object before gc
* *
*/ */
private native void release(); private native void release();
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see java.lang.Object#finalize() * @see java.lang.Object#finalize()
*/ */
protected void finalize() { protected void finalize() {
safeRelease(); safeRelease();
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see com.jacob.com.JacobObject#safeRelease() * @see com.jacob.com.JacobObject#safeRelease()
*/ */
public void safeRelease() { public void safeRelease() {
if (mInvocationProxy != null) { if (mInvocationProxy != null) {
mInvocationProxy.setTarget(null); mInvocationProxy.setTarget(null);
} }
mInvocationProxy = null; mInvocationProxy = null;
super.safeRelease(); super.safeRelease();
if (m_pConnPtProxy != 0) { if (m_pConnPtProxy != 0) {
release(); release();
m_pConnPtProxy = 0; m_pConnPtProxy = 0;
} else { } else {
// looks like a double release // looks like a double release
if (isDebugEnabled()) { if (isDebugEnabled()) {
debug("DispatchEvents:" + this.hashCode() + " double release"); debug("DispatchEvents:" + this.hashCode() + " double release");
} }
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
/** /**
* *
@@ -47,74 +47,74 @@ package com.jacob.com;
*/ */
public class DispatchIdentifier { public class DispatchIdentifier {
private DispatchIdentifier() { private DispatchIdentifier() {
// This is utility class so there is no constructor. // This is utility class so there is no constructor.
} }
public static final int DISPID_UNKNOWN = -1; public static final int DISPID_UNKNOWN = -1;
public static final int DISPID_VALUE = 0; public static final int DISPID_VALUE = 0;
public static final int DISPID_PROPERTYPUT = -3; public static final int DISPID_PROPERTYPUT = -3;
public static final int DISPID_NEWENUM = -4; public static final int DISPID_NEWENUM = -4;
public static final int DISPID_EVALUATE = -5; public static final int DISPID_EVALUATE = -5;
public static final int DISPID_CONSTRUCTOR = -6; public static final int DISPID_CONSTRUCTOR = -6;
public static final int DISPID_DESTRUCTOR = -7; public static final int DISPID_DESTRUCTOR = -7;
public static final int DISPID_COLLECT = -8; public static final int DISPID_COLLECT = -8;
public static final int DISPID_AUTOSIZE = -500; public static final int DISPID_AUTOSIZE = -500;
public static final int DISPID_BACKCOLOR = -501; public static final int DISPID_BACKCOLOR = -501;
public static final int DISPID_BACKSTYLE = -502; public static final int DISPID_BACKSTYLE = -502;
public static final int DISPID_BORDERCOLOR = -503; public static final int DISPID_BORDERCOLOR = -503;
public static final int DISPID_BORDERSTYLE = -504; public static final int DISPID_BORDERSTYLE = -504;
public static final int DISPID_BORDERWIDTH = -505; public static final int DISPID_BORDERWIDTH = -505;
public static final int DISPID_DRAWMODE = -507; public static final int DISPID_DRAWMODE = -507;
public static final int DISPID_DRAWSTYLE = -508; public static final int DISPID_DRAWSTYLE = -508;
public static final int DISPID_DRAWWIDTH = -509; public static final int DISPID_DRAWWIDTH = -509;
public static final int DISPID_FILLCOLOR = -510; public static final int DISPID_FILLCOLOR = -510;
public static final int DISPID_FILLSTYLE = -511; public static final int DISPID_FILLSTYLE = -511;
public static final int DISPID_FONT = -512; public static final int DISPID_FONT = -512;
public static final int DISPID_FORECOLOR = -513; public static final int DISPID_FORECOLOR = -513;
public static final int DISPID_ENABLED = -514; public static final int DISPID_ENABLED = -514;
public static final int DISPID_HWND = -515; public static final int DISPID_HWND = -515;
public static final int DISPID_TABSTOP = -516; public static final int DISPID_TABSTOP = -516;
public static final int DISPID_TEXT = -517; public static final int DISPID_TEXT = -517;
public static final int DISPID_CAPTION = -518; public static final int DISPID_CAPTION = -518;
public static final int DISPID_BORDERVISIBLE = -519; public static final int DISPID_BORDERVISIBLE = -519;
public static final int DISPID_APPEARANCE = -520; public static final int DISPID_APPEARANCE = -520;
public static final int DISPID_MOUSEPOINTER = -521; public static final int DISPID_MOUSEPOINTER = -521;
public static final int DISPID_MOUSEICON = -522; public static final int DISPID_MOUSEICON = -522;
public static final int DISPID_PICTURE = -523; public static final int DISPID_PICTURE = -523;
public static final int DISPID_VALID = -524; public static final int DISPID_VALID = -524;
public static final int DISPID_READYSTATE = -525; public static final int DISPID_READYSTATE = -525;
public static final int DISPID_REFRESH = -550; public static final int DISPID_REFRESH = -550;
public static final int DISPID_DOCLICK = -551; public static final int DISPID_DOCLICK = -551;
public static final int DISPID_ABOUTBOX = -552; public static final int DISPID_ABOUTBOX = -552;
public static final int DISPID_CLICK = -600; public static final int DISPID_CLICK = -600;
public static final int DISPID_DBLCLICK = -601; public static final int DISPID_DBLCLICK = -601;
public static final int DISPID_KEYDOWN = -602; public static final int DISPID_KEYDOWN = -602;
public static final int DISPID_KEYPRESS = -603; public static final int DISPID_KEYPRESS = -603;
public static final int DISPID_KEYUP = -604; public static final int DISPID_KEYUP = -604;
public static final int DISPID_MOUSEDOWN = -605; public static final int DISPID_MOUSEDOWN = -605;
public static final int DISPID_MOUSEMOVE = -606; public static final int DISPID_MOUSEMOVE = -606;
public static final int DISPID_MOUSEUP = -607; public static final int DISPID_MOUSEUP = -607;
public static final int DISPID_ERROREVENT = -608; public static final int DISPID_ERROREVENT = -608;
public static final int DISPID_READYSTATECHANGE = -609; public static final int DISPID_READYSTATECHANGE = -609;
public static final int DISPID_AMBIENT_BACKCOLOR = -701; public static final int DISPID_AMBIENT_BACKCOLOR = -701;
public static final int DISPID_AMBIENT_DISPLAYNAME = -702; public static final int DISPID_AMBIENT_DISPLAYNAME = -702;
public static final int DISPID_AMBIENT_FONT = -703; public static final int DISPID_AMBIENT_FONT = -703;
public static final int DISPID_AMBIENT_FORECOLOR = -704; public static final int DISPID_AMBIENT_FORECOLOR = -704;
public static final int DISPID_AMBIENT_LOCALEID = -705; public static final int DISPID_AMBIENT_LOCALEID = -705;
public static final int DISPID_AMBIENT_MESSAGEREFLECT = -706; public static final int DISPID_AMBIENT_MESSAGEREFLECT = -706;
public static final int DISPID_AMBIENT_SCALEUNITS = -707; public static final int DISPID_AMBIENT_SCALEUNITS = -707;
public static final int DISPID_AMBIENT_TEXTALIGN = -708; public static final int DISPID_AMBIENT_TEXTALIGN = -708;
public static final int DISPID_AMBIENT_USERMODE = -709; public static final int DISPID_AMBIENT_USERMODE = -709;
public static final int DISPID_AMBIENT_UIDEAD = -710; public static final int DISPID_AMBIENT_UIDEAD = -710;
public static final int DISPID_AMBIENT_SHOWGRABHANDLES = -711; public static final int DISPID_AMBIENT_SHOWGRABHANDLES = -711;
public static final int DISPID_AMBIENT_SHOWHATCHING = -712; public static final int DISPID_AMBIENT_SHOWHATCHING = -712;
public static final int DISPID_AMBIENT_DISPLAYASDEFAULT = -713; public static final int DISPID_AMBIENT_DISPLAYASDEFAULT = -713;
public static final int DISPID_AMBIENT_SUPPORTSMNEMONICS = -714; public static final int DISPID_AMBIENT_SUPPORTSMNEMONICS = -714;
public static final int DISPID_AMBIENT_AUTOCLIP = -715; public static final int DISPID_AMBIENT_AUTOCLIP = -715;
public static final int DISPID_AMBIENT_APPEARANCE = -716; public static final int DISPID_AMBIENT_APPEARANCE = -716;
public static final int DISPID_AMBIENT_CODEPAGE = -725; public static final int DISPID_AMBIENT_CODEPAGE = -725;
public static final int DISPID_AMBIENT_PALETTE = -726; public static final int DISPID_AMBIENT_PALETTE = -726;
public static final int DISPID_AMBIENT_CHARSET = -727; public static final int DISPID_AMBIENT_CHARSET = -727;
public static final int DISPID_AMBIENT_TRANSFERPRIORITY = -728; public static final int DISPID_AMBIENT_TRANSFERPRIORITY = -728;
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -48,64 +48,64 @@ package com.jacob.com;
* construct a separate DispatchProxy instance for each such case! * construct a separate DispatchProxy instance for each such case!
*/ */
public class DispatchProxy extends JacobObject { public class DispatchProxy extends JacobObject {
/** /**
* Comment for <code>m_pStream</code> * Comment for <code>m_pStream</code>
*/ */
public int m_pStream; public int m_pStream;
/** /**
* Marshals the passed in dispatch into the stream * Marshals the passed in dispatch into the stream
* *
* @param localDispatch * @param localDispatch
*/ */
public DispatchProxy(Dispatch localDispatch) { public DispatchProxy(Dispatch localDispatch) {
MarshalIntoStream(localDispatch); MarshalIntoStream(localDispatch);
} }
/** /**
* *
* @return Dispatch the dispatch retrieved from the stream * @return Dispatch the dispatch retrieved from the stream
*/ */
public Dispatch toDispatch() { public Dispatch toDispatch() {
return MarshalFromStream(); return MarshalFromStream();
} }
private native void MarshalIntoStream(Dispatch d); private native void MarshalIntoStream(Dispatch d);
private native Dispatch MarshalFromStream(); private native Dispatch MarshalFromStream();
/** /**
* now private so only this object can access was: call this to explicitly * now private so only this object can access was: call this to explicitly
* release the com object before gc * release the com object before gc
* *
*/ */
private native void release(); private native void release();
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see java.lang.Object#finalize() * @see java.lang.Object#finalize()
*/ */
public void finalize() { public void finalize() {
safeRelease(); safeRelease();
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see com.jacob.com.JacobObject#safeRelease() * @see com.jacob.com.JacobObject#safeRelease()
*/ */
public void safeRelease() { public void safeRelease() {
super.safeRelease(); super.safeRelease();
if (m_pStream != 0) { if (m_pStream != 0) {
release(); release();
m_pStream = 0; m_pStream = 0;
} else { } else {
// looks like a double release // looks like a double release
if (isDebugEnabled()) { if (isDebugEnabled()) {
debug(this.getClass().getName() + ":" + this.hashCode() debug(this.getClass().getName() + ":" + this.hashCode()
+ " double release"); + " double release");
} }
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -43,133 +43,133 @@ package com.jacob.com;
* (mailto:Thomas.Hallgren@eoncompany.com) * (mailto:Thomas.Hallgren@eoncompany.com)
*/ */
public class EnumVariant extends JacobObject implements public class EnumVariant extends JacobObject implements
java.util.Enumeration<Variant> { java.util.Enumeration<Variant> {
private int m_pIEnumVARIANT; private int m_pIEnumVARIANT;
private final Variant[] m_recBuf = new Variant[1]; private final Variant[] m_recBuf = new Variant[1];
// this only gets called from JNI // this only gets called from JNI
// //
protected EnumVariant(int pIEnumVARIANT) { protected EnumVariant(int pIEnumVARIANT) {
m_pIEnumVARIANT = pIEnumVARIANT; m_pIEnumVARIANT = pIEnumVARIANT;
} }
/** /**
* @param disp * @param disp
*/ */
public EnumVariant(Dispatch disp) { public EnumVariant(Dispatch disp) {
int[] hres = new int[1]; int[] hres = new int[1];
Variant evv = Dispatch.invokev(disp, DispatchIdentifier.DISPID_NEWENUM, Variant evv = Dispatch.invokev(disp, DispatchIdentifier.DISPID_NEWENUM,
Dispatch.Get, new Variant[0], hres); Dispatch.Get, new Variant[0], hres);
if (evv.getvt() != Variant.VariantObject) if (evv.getvt() != Variant.VariantObject)
// //
// The DISPID_NEWENUM did not result in a valid object // The DISPID_NEWENUM did not result in a valid object
// //
throw new ComFailException("Can't obtain EnumVARIANT"); throw new ComFailException("Can't obtain EnumVARIANT");
EnumVariant tmp = evv.toEnumVariant(); EnumVariant tmp = evv.toEnumVariant();
m_pIEnumVARIANT = tmp.m_pIEnumVARIANT; m_pIEnumVARIANT = tmp.m_pIEnumVARIANT;
tmp.m_pIEnumVARIANT = 0; tmp.m_pIEnumVARIANT = 0;
} }
/** /**
* Implements java.util.Enumeration * Implements java.util.Enumeration
* *
* @return boolean true if there are more elements in this enumeration * @return boolean true if there are more elements in this enumeration
*/ */
public boolean hasMoreElements() { public boolean hasMoreElements() {
{ {
if (m_recBuf[0] == null) { if (m_recBuf[0] == null) {
if (this.Next(m_recBuf) <= 0) if (this.Next(m_recBuf) <= 0)
return false; return false;
} }
return true; return true;
} }
} }
/** /**
* Implements java.util.Enumeration * Implements java.util.Enumeration
* *
* @return next element in the enumeration * @return next element in the enumeration
*/ */
public Variant nextElement() { public Variant nextElement() {
Variant last = m_recBuf[0]; Variant last = m_recBuf[0];
if (last == null) { if (last == null) {
if (this.Next(m_recBuf) <= 0) if (this.Next(m_recBuf) <= 0)
throw new java.util.NoSuchElementException(); throw new java.util.NoSuchElementException();
last = m_recBuf[0]; last = m_recBuf[0];
} }
m_recBuf[0] = null; m_recBuf[0] = null;
return last; return last;
} }
/** /**
* Get next element in collection or null if at end * Get next element in collection or null if at end
* *
* @return Variant that is next in the collection * @return Variant that is next in the collection
* @deprecated use nextElement() instead * @deprecated use nextElement() instead
*/ */
@Deprecated @Deprecated
public Variant Next() { public Variant Next() {
if (hasMoreElements()) if (hasMoreElements())
return nextElement(); return nextElement();
return null; return null;
} }
/** /**
* This should be private and wrapped to protect JNI layer. * This should be private and wrapped to protect JNI layer.
* *
* @param receiverArray * @param receiverArray
* @return Returns the next variant object pointer as an int from windows * @return Returns the next variant object pointer as an int from windows
* layer * layer
*/ */
public native int Next(Variant[] receiverArray); public native int Next(Variant[] receiverArray);
/** /**
* This should be private and wrapped to protect JNI layer. * This should be private and wrapped to protect JNI layer.
* *
* @param count * @param count
* number to skip * number to skip
*/ */
public native void Skip(int count); public native void Skip(int count);
/** /**
* This should be private and wrapped to protect JNI layer * This should be private and wrapped to protect JNI layer
*/ */
public native void Reset(); public native void Reset();
/** /**
* now private so only this object can access was: call this to explicitly * now private so only this object can access was: call this to explicitly
* release the com object before gc * release the com object before gc
* *
*/ */
private native void release(); private native void release();
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see java.lang.Object#finalize() * @see java.lang.Object#finalize()
*/ */
protected void finalize() { protected void finalize() {
safeRelease(); safeRelease();
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see com.jacob.com.JacobObject#safeRelease() * @see com.jacob.com.JacobObject#safeRelease()
*/ */
public void safeRelease() { public void safeRelease() {
super.safeRelease(); super.safeRelease();
if (m_pIEnumVARIANT != 0) { if (m_pIEnumVARIANT != 0) {
this.release(); this.release();
m_pIEnumVARIANT = 0; m_pIEnumVARIANT = 0;
} else { } else {
// looks like a double release // looks like a double release
if (isDebugEnabled()) { if (isDebugEnabled()) {
debug(this.getClass().getName() + ":" + this.hashCode() debug(this.getClass().getName() + ":" + this.hashCode()
+ " double release"); + " double release");
} }
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -58,70 +58,70 @@ package com.jacob.com;
*/ */
public abstract class InvocationProxy { public abstract class InvocationProxy {
/** /**
* the object we will try and forward to. * the object we will try and forward to.
*/ */
protected Object mTargetObject = null; protected Object mTargetObject = null;
/** /**
* dummy constructor for subclasses that don't actually wrap anything and * dummy constructor for subclasses that don't actually wrap anything and
* just want to override the invoke() method * just want to override the invoke() method
*/ */
protected InvocationProxy() { protected InvocationProxy() {
super(); super();
} }
/** /**
* The method actually invoked by EventProxy.cpp. The method name is * The method actually invoked by EventProxy.cpp. The method name is
* calculated by the underlying JNI code from the MS windows Callback * calculated by the underlying JNI code from the MS windows Callback
* function name. The method is assumed to take an array of Variant objects. * function name. The method is assumed to take an array of Variant objects.
* The method may return a Variant or be a void. Those are the only two * The method may return a Variant or be a void. Those are the only two
* options that will not blow up. * options that will not blow up.
* <p> * <p>
* Subclasses that override this should make sure mTargetObject is not null * Subclasses that override this should make sure mTargetObject is not null
* before processing. * before processing.
* *
* @param methodName * @param methodName
* name of method in mTargetObject we will invoke * name of method in mTargetObject we will invoke
* @param targetParameters * @param targetParameters
* Variant[] that is the single parameter to the method * Variant[] that is the single parameter to the method
* @return an object that will be returned to the com event caller * @return an object that will be returned to the com event caller
*/ */
public abstract Variant invoke(String methodName, public abstract Variant invoke(String methodName,
Variant targetParameters[]); Variant targetParameters[]);
/** /**
* used by EventProxy.cpp to create variant objects in the right thread * used by EventProxy.cpp to create variant objects in the right thread
* *
* @return Variant object that will be used by the COM layer * @return Variant object that will be used by the COM layer
*/ */
public Variant getVariant() { public Variant getVariant() {
return new VariantViaEvent(); return new VariantViaEvent();
} }
/** /**
* Sets the target for this InvocationProxy. * Sets the target for this InvocationProxy.
* *
* @param pTargetObject * @param pTargetObject
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if target is not publicly accessible * if target is not publicly accessible
*/ */
public void setTarget(Object pTargetObject) { public void setTarget(Object pTargetObject) {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("InvocationProxy: setting target " JacobObject.debug("InvocationProxy: setting target "
+ pTargetObject); + pTargetObject);
} }
if (pTargetObject != null) { if (pTargetObject != null) {
// JNI code apparently bypasses this check and could operate against // JNI code apparently bypasses this check and could operate against
// protected classes. This seems like a security issue... // protected classes. This seems like a security issue...
// maybe it was because JNI code isn't in a package? // maybe it was because JNI code isn't in a package?
if (!java.lang.reflect.Modifier.isPublic(pTargetObject.getClass() if (!java.lang.reflect.Modifier.isPublic(pTargetObject.getClass()
.getModifiers())) { .getModifiers())) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"InvocationProxy only public classes can receive event notifications"); "InvocationProxy only public classes can receive event notifications");
} }
} }
mTargetObject = pTargetObject; mTargetObject = pTargetObject;
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -55,88 +55,88 @@ import java.lang.reflect.Method;
*/ */
public class InvocationProxyAllVariants extends InvocationProxy { public class InvocationProxyAllVariants extends InvocationProxy {
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see com.jacob.com.InvocationProxy#invoke(java.lang.String, * @see com.jacob.com.InvocationProxy#invoke(java.lang.String,
* com.jacob.com.Variant[]) * com.jacob.com.Variant[])
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Variant invoke(String methodName, Variant targetParameters[]) { public Variant invoke(String methodName, Variant targetParameters[]) {
Variant mVariantToBeReturned = null; Variant mVariantToBeReturned = null;
if (mTargetObject == null) { if (mTargetObject == null) {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("InvocationProxy: received notification (" JacobObject.debug("InvocationProxy: received notification ("
+ methodName + ") with no target set"); + methodName + ") with no target set");
} }
// structured programming guidlines say this return should not be up // structured programming guidlines say this return should not be up
// here // here
return null; return null;
} }
Class targetClass = mTargetObject.getClass(); Class targetClass = mTargetObject.getClass();
if (methodName == null) { if (methodName == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"InvocationProxy: missing method name"); "InvocationProxy: missing method name");
} }
if (targetParameters == null) { if (targetParameters == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"InvocationProxy: missing Variant parameters"); "InvocationProxy: missing Variant parameters");
} }
try { try {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("InvocationProxy: trying to invoke " JacobObject.debug("InvocationProxy: trying to invoke "
+ methodName + " on " + mTargetObject); + methodName + " on " + mTargetObject);
} }
Method targetMethod; Method targetMethod;
targetMethod = targetClass.getMethod(methodName, targetMethod = targetClass.getMethod(methodName,
new Class[] { Variant[].class }); new Class[] { Variant[].class });
if (targetMethod != null) { if (targetMethod != null) {
// protected classes can't be invoked against even if they // protected classes can't be invoked against even if they
// let you grab the method. you could do // let you grab the method. you could do
// targetMethod.setAccessible(true); // targetMethod.setAccessible(true);
// but that should be stopped by the security manager // but that should be stopped by the security manager
Object mReturnedByInvocation = null; Object mReturnedByInvocation = null;
mReturnedByInvocation = targetMethod.invoke(mTargetObject, mReturnedByInvocation = targetMethod.invoke(mTargetObject,
new Object[] { targetParameters }); new Object[] { targetParameters });
if (mReturnedByInvocation == null) { if (mReturnedByInvocation == null) {
mVariantToBeReturned = null; mVariantToBeReturned = null;
} else if (!(mReturnedByInvocation instanceof Variant)) { } else if (!(mReturnedByInvocation instanceof Variant)) {
// could try and convert to Variant here. // could try and convert to Variant here.
throw new IllegalArgumentException( throw new IllegalArgumentException(
"InvocationProxy: invokation of target method returned " "InvocationProxy: invokation of target method returned "
+ "non-null non-variant object: " + "non-null non-variant object: "
+ mReturnedByInvocation); + mReturnedByInvocation);
} else { } else {
mVariantToBeReturned = (Variant) mReturnedByInvocation; mVariantToBeReturned = (Variant) mReturnedByInvocation;
} }
} }
} catch (SecurityException e) { } catch (SecurityException e) {
// what causes this exception? // what causes this exception?
e.printStackTrace(); e.printStackTrace();
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
// this happens whenever the listener doesn't implement all the // this happens whenever the listener doesn't implement all the
// methods // methods
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("InvocationProxy: listener (" + mTargetObject JacobObject.debug("InvocationProxy: listener (" + mTargetObject
+ ") doesn't implement " + methodName); + ") doesn't implement " + methodName);
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
e.printStackTrace(); e.printStackTrace();
// we can throw these inside the catch block so need to re-throw it // we can throw these inside the catch block so need to re-throw it
throw e; throw e;
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
// can't access the method on the target instance for some reason // can't access the method on the target instance for some reason
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject JacobObject
.debug("InvocationProxy: probably tried to access public method on non public class" .debug("InvocationProxy: probably tried to access public method on non public class"
+ methodName); + methodName);
} }
e.printStackTrace(); e.printStackTrace();
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
// invocation of target method failed // invocation of target method failed
e.printStackTrace(); e.printStackTrace();
} }
return mVariantToBeReturned; return mVariantToBeReturned;
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -45,24 +45,24 @@ package com.jacob.com;
*/ */
public class JacobException extends RuntimeException { public class JacobException extends RuntimeException {
/** /**
* *
*/ */
private static final long serialVersionUID = -1637125318746002715L; private static final long serialVersionUID = -1637125318746002715L;
/** /**
* Default constructor. Calls super with a "No Message Provided" string * Default constructor. Calls super with a "No Message Provided" string
*/ */
public JacobException() { public JacobException() {
super("No Message Provided"); super("No Message Provided");
} }
/** /**
* standard constructor * standard constructor
* *
* @param message * @param message
*/ */
public JacobException(String message) { public JacobException(String message) {
super(message); super(message);
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -53,78 +53,78 @@ package com.jacob.com;
*/ */
public class JacobObject { public class JacobObject {
/** /**
* Standard constructor that adds this JacobObject to the memory management * Standard constructor that adds this JacobObject to the memory management
* pool. * pool.
*/ */
public JacobObject() { public JacobObject() {
ROT.addObject(this); ROT.addObject(this);
} }
/** /**
* Finalizers call this method. This method should release any COM data * Finalizers call this method. This method should release any COM data
* structures in a way that it can be called multiple times. This can happen * structures in a way that it can be called multiple times. This can happen
* if someone manually calls this and then a finalizer calls it. * if someone manually calls this and then a finalizer calls it.
*/ */
public void safeRelease() { public void safeRelease() {
// currently does nothing - subclasses may do something // currently does nothing - subclasses may do something
if (isDebugEnabled()) { if (isDebugEnabled()) {
// this used to do a toString() but that is bad for SafeArray // this used to do a toString() but that is bad for SafeArray
debug("SafeRelease: " + this.getClass().getName()); debug("SafeRelease: " + this.getClass().getName());
} }
} }
/** /**
* When things go wrong, it is useful to be able to debug the ROT. * When things go wrong, it is useful to be able to debug the ROT.
*/ */
private static final boolean DEBUG = private static final boolean DEBUG =
// true; // true;
"true".equalsIgnoreCase(System.getProperty("com.jacob.debug")); "true".equalsIgnoreCase(System.getProperty("com.jacob.debug"));
protected static boolean isDebugEnabled() { protected static boolean isDebugEnabled() {
// return true; // return true;
return DEBUG; return DEBUG;
} }
/** /**
* Loads JacobVersion.Properties and returns the value of version in it * Loads JacobVersion.Properties and returns the value of version in it
* *
* @deprecated use JacobReleaseInfo.getBuildDate() instead. * @deprecated use JacobReleaseInfo.getBuildDate() instead.
* @return String value of version in JacobVersion.Properties or "" if none * @return String value of version in JacobVersion.Properties or "" if none
*/ */
@Deprecated @Deprecated
public static String getBuildDate() { public static String getBuildDate() {
return JacobReleaseInfo.getBuildDate(); return JacobReleaseInfo.getBuildDate();
} }
/** /**
* Loads JacobVersion.Properties and returns the value of version in it * Loads JacobVersion.Properties and returns the value of version in it
* *
* @deprecated use JacobReleaseInfo.getBuildVersion() instead. * @deprecated use JacobReleaseInfo.getBuildVersion() instead.
* @return String value of version in JacobVersion.Properties or "" if none * @return String value of version in JacobVersion.Properties or "" if none
*/ */
@Deprecated @Deprecated
public static String getBuildVersion() { public static String getBuildVersion() {
return JacobReleaseInfo.getBuildVersion(); return JacobReleaseInfo.getBuildVersion();
} }
/** /**
* Very basic debugging function. * Very basic debugging function.
* *
* @param istrMessage * @param istrMessage
*/ */
protected static void debug(String istrMessage) { protected static void debug(String istrMessage) {
if (isDebugEnabled()) { if (isDebugEnabled()) {
System.out.println(Thread.currentThread().getName() + ": " System.out.println(Thread.currentThread().getName() + ": "
+ istrMessage); + istrMessage);
} }
} }
/** /**
* force the jacob DLL to be loaded whenever this class is referenced * force the jacob DLL to be loaded whenever this class is referenced
*/ */
static { static {
LibraryLoader.loadJacobLibrary(); LibraryLoader.loadJacobLibrary();
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -49,86 +49,86 @@ import java.util.Properties;
*/ */
public class JacobReleaseInfo { public class JacobReleaseInfo {
/** /**
* holds the build version as retrieved from the version properties file * holds the build version as retrieved from the version properties file
* that exists in the JAR. This can be retrieved by calling the static * that exists in the JAR. This can be retrieved by calling the static
* method getBuildVersion() * method getBuildVersion()
* *
* @see #getBuildVersion() * @see #getBuildVersion()
*/ */
private static String buildVersion = ""; private static String buildVersion = "";
/** /**
* holds the build date as retrieved from the version properties file that * holds the build date as retrieved from the version properties file that
* exists in the JAR This can be retrieved by calling the static method * exists in the JAR This can be retrieved by calling the static method
* getBuildDate() * getBuildDate()
* *
* @see #getBuildDate() * @see #getBuildDate()
*/ */
private static String buildDate = ""; private static String buildDate = "";
/** the name of the jacob version properties file */ /** the name of the jacob version properties file */
private static final String PROPERTY_FILE_NAME = "META-INF/JacobVersion.properties"; private static final String PROPERTY_FILE_NAME = "META-INF/JacobVersion.properties";
/** /**
* Loads version information from PROPERTY_FILE_NAME that was built as part * Loads version information from PROPERTY_FILE_NAME that was built as part
* of this release. * of this release.
* *
* @throws IllegalStateException * @throws IllegalStateException
* when it can't find the version properties file * when it can't find the version properties file
*/ */
private static void loadVersionProperties() { private static void loadVersionProperties() {
Properties versionProps = new Properties(); Properties versionProps = new Properties();
// can't use system class loader cause won't work in JavaWebStart // can't use system class loader cause won't work in JavaWebStart
InputStream stream = JacobReleaseInfo.class.getClassLoader() InputStream stream = JacobReleaseInfo.class.getClassLoader()
.getResourceAsStream(PROPERTY_FILE_NAME); .getResourceAsStream(PROPERTY_FILE_NAME);
// This should never happen. This is an attempt to make something work // This should never happen. This is an attempt to make something work
// for WebSphere. They may be using some kind of Servlet loader that // for WebSphere. They may be using some kind of Servlet loader that
// needs an absolute path based search // needs an absolute path based search
if (stream == null) { if (stream == null) {
stream = JacobReleaseInfo.class.getClassLoader() stream = JacobReleaseInfo.class.getClassLoader()
.getResourceAsStream("/" + PROPERTY_FILE_NAME); .getResourceAsStream("/" + PROPERTY_FILE_NAME);
} }
// A report came in that WebSphere had trouble finding the file // A report came in that WebSphere had trouble finding the file
// so lets trap it. Plus, it's a good idea anyway. // so lets trap it. Plus, it's a good idea anyway.
if (stream == null) { if (stream == null) {
throw new IllegalStateException( throw new IllegalStateException(
"Can't find " "Can't find "
+ PROPERTY_FILE_NAME + PROPERTY_FILE_NAME
+ " using JacobReleaseInfo.class.getClassLoader().getResourceAsStream()"); + " using JacobReleaseInfo.class.getClassLoader().getResourceAsStream()");
} else { } else {
try { try {
versionProps.load(stream); versionProps.load(stream);
stream.close(); stream.close();
buildVersion = (String) versionProps.get("version"); buildVersion = (String) versionProps.get("version");
buildDate = (String) versionProps.get("build.date"); buildDate = (String) versionProps.get("build.date");
} catch (IOException ioe) { } catch (IOException ioe) {
ioe.printStackTrace(); ioe.printStackTrace();
System.err.println("Warning! Couldn't load props " + ioe); System.err.println("Warning! Couldn't load props " + ioe);
} }
} }
} }
/** /**
* loads PROPERT_FILE_NAME and returns the value of version in it * loads PROPERT_FILE_NAME and returns the value of version in it
* *
* @return String value of version in PROPERT_FILE_NAME or "" if none * @return String value of version in PROPERT_FILE_NAME or "" if none
*/ */
public static String getBuildDate() { public static String getBuildDate() {
if (buildDate.equals("")) { if (buildDate.equals("")) {
loadVersionProperties(); loadVersionProperties();
} }
return buildDate; return buildDate;
} }
/** /**
* loads PROPERT_FILE_NAME and returns the value of version in it * loads PROPERT_FILE_NAME and returns the value of version in it
* *
* @return String value of version in PROPERT_FILE_NAME or "" if none * @return String value of version in PROPERT_FILE_NAME or "" if none
*/ */
public static String getBuildVersion() { public static String getBuildVersion() {
if (buildVersion.equals("")) { if (buildVersion.equals("")) {
loadVersionProperties(); loadVersionProperties();
} }
return buildVersion; return buildVersion;
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -47,13 +47,13 @@ import com.github.boukefalos.jlibloader.Native;
* @author Jason Smith * @author Jason Smith
*/ */
public final class LibraryLoader { public final class LibraryLoader {
/** /**
* Load the jacob dll * Load the jacob dll
* *
* @throws UnsatisfiedLinkError * @throws UnsatisfiedLinkError
* if the library does not exist. * if the library does not exist.
*/ */
public static void loadJacobLibrary() { public static void loadJacobLibrary() {
Native.load("com.github.boukefalos", "jlibcom"); Native.load("com.github.boukefalos", "jlibcom");
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -45,16 +45,16 @@ package com.jacob.com;
*/ */
public class NotImplementedException extends JacobException { public class NotImplementedException extends JacobException {
/** /**
* *
*/ */
private static final long serialVersionUID = -9169900832852356445L; private static final long serialVersionUID = -9169900832852356445L;
/** /**
* @param description * @param description
*/ */
public NotImplementedException(String description) { public NotImplementedException(String description) {
super(description); super(description);
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -60,239 +60,239 @@ import java.util.WeakHashMap;
* Is [ 1116101 ] jacob-msg 0284 relevant??? * Is [ 1116101 ] jacob-msg 0284 relevant???
*/ */
public abstract class ROT { public abstract class ROT {
/** /**
* Manual garbage collection was the only option pre 1.9 Can staticly cache * Manual garbage collection was the only option pre 1.9 Can staticly cache
* the results because only one value and we don't let it change during a * the results because only one value and we don't let it change during a
* run * run
*/ */
protected static final boolean USE_AUTOMATIC_GARBAGE_COLLECTION = "true" protected static final boolean USE_AUTOMATIC_GARBAGE_COLLECTION = "true"
.equalsIgnoreCase(System.getProperty("com.jacob.autogc")); .equalsIgnoreCase(System.getProperty("com.jacob.autogc"));
/** /**
* If the code is ran from an applet that is called from javascript the Java * If the code is ran from an applet that is called from javascript the Java
* Plugin does not give full permissions to the code and thus System * Plugin does not give full permissions to the code and thus System
* properties cannot be accessed. They can be accessed at class * properties cannot be accessed. They can be accessed at class
* initialization time. * initialization time.
* *
* The default behavior is to include all classes in the ROT, setting a * The default behavior is to include all classes in the ROT, setting a
* boolean here to indicate this prevents a call to System.getProperty as * boolean here to indicate this prevents a call to System.getProperty as
* part of the general call flow. * part of the general call flow.
*/ */
protected static final Boolean INCLUDE_ALL_CLASSES_IN_ROT = Boolean protected static final Boolean INCLUDE_ALL_CLASSES_IN_ROT = Boolean
.valueOf(System.getProperty("com.jacob.includeAllClassesInROT", .valueOf(System.getProperty("com.jacob.includeAllClassesInROT",
"true")); "true"));
/** /**
* Suffix added to class name to make up property name that determines if * Suffix added to class name to make up property name that determines if
* this object should be stored in the ROT. This 1.13 "feature" makes it * this object should be stored in the ROT. This 1.13 "feature" makes it
* possible to cause VariantViaEvent objects to not be added to the ROT in * possible to cause VariantViaEvent objects to not be added to the ROT in
* event callbacks. * event callbacks.
* <p> * <p>
* We don't have a static for the actual property because there is a * We don't have a static for the actual property because there is a
* different property for each class that may make use of this feature. * different property for each class that may make use of this feature.
*/ */
protected static String PUT_IN_ROT_SUFFIX = ".PutInROT"; protected static String PUT_IN_ROT_SUFFIX = ".PutInROT";
/** /**
* A hash table where each element is another HashMap that represents a * A hash table where each element is another HashMap that represents a
* thread. Each thread HashMap contains the com objects created in that * thread. Each thread HashMap contains the com objects created in that
* thread * thread
*/ */
private static HashMap<String, Map<JacobObject, String>> rot = new HashMap<String, Map<JacobObject, String>>(); private static HashMap<String, Map<JacobObject, String>> rot = new HashMap<String, Map<JacobObject, String>>();
/** /**
* adds a new thread storage area to rot * adds a new thread storage area to rot
* *
* @return Map corresponding to the thread that this call was made in * @return Map corresponding to the thread that this call was made in
*/ */
protected synchronized static Map<JacobObject, String> addThread() { protected synchronized static Map<JacobObject, String> addThread() {
// should use the id here instead of the name because the name can be // should use the id here instead of the name because the name can be
// changed // changed
String t_name = Thread.currentThread().getName(); String t_name = Thread.currentThread().getName();
if (rot.containsKey(t_name)) { if (rot.containsKey(t_name)) {
// nothing to do // nothing to do
} else { } else {
Map<JacobObject, String> tab = null; Map<JacobObject, String> tab = null;
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: Automatic GC flag == " JacobObject.debug("ROT: Automatic GC flag == "
+ USE_AUTOMATIC_GARBAGE_COLLECTION); + USE_AUTOMATIC_GARBAGE_COLLECTION);
} }
if (!USE_AUTOMATIC_GARBAGE_COLLECTION) { if (!USE_AUTOMATIC_GARBAGE_COLLECTION) {
tab = new HashMap<JacobObject, String>(); tab = new HashMap<JacobObject, String>();
} else { } else {
tab = new WeakHashMap<JacobObject, String>(); tab = new WeakHashMap<JacobObject, String>();
} }
rot.put(t_name, tab); rot.put(t_name, tab);
} }
return getThreadObjects(false); return getThreadObjects(false);
} }
/** /**
* Returns the pool for this thread if it exists. can create a new one if * Returns the pool for this thread if it exists. can create a new one if
* you wish by passing in TRUE * you wish by passing in TRUE
* *
* @param createIfDoesNotExist * @param createIfDoesNotExist
* @return Map the collection that holds the objects created in the current * @return Map the collection that holds the objects created in the current
* thread * thread
*/ */
protected synchronized static Map<JacobObject, String> getThreadObjects( protected synchronized static Map<JacobObject, String> getThreadObjects(
boolean createIfDoesNotExist) { boolean createIfDoesNotExist) {
String t_name = Thread.currentThread().getName(); String t_name = Thread.currentThread().getName();
if (!rot.containsKey(t_name) && createIfDoesNotExist) { if (!rot.containsKey(t_name) && createIfDoesNotExist) {
addThread(); addThread();
} }
return rot.get(t_name); return rot.get(t_name);
} }
/** /**
* Iterates across all of the entries in the Hashmap in the rot that * Iterates across all of the entries in the Hashmap in the rot that
* corresponds to this thread. This calls safeRelease() on each entry and * corresponds to this thread. This calls safeRelease() on each entry and
* then clears the map when done and removes it from the rot. All traces of * then clears the map when done and removes it from the rot. All traces of
* this thread's objects will disappear. This is called by COMThread in the * this thread's objects will disappear. This is called by COMThread in the
* tear down and provides a synchronous way of releasing memory * tear down and provides a synchronous way of releasing memory
*/ */
protected static void clearObjects() { protected static void clearObjects() {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: " + rot.keySet().size() JacobObject.debug("ROT: " + rot.keySet().size()
+ " thread tables exist"); + " thread tables exist");
} }
Map<JacobObject, String> tab = getThreadObjects(false); Map<JacobObject, String> tab = getThreadObjects(false);
if (tab != null) { if (tab != null) {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: " + tab.keySet().size() JacobObject.debug("ROT: " + tab.keySet().size()
+ " objects to clear in this thread's ROT "); + " objects to clear in this thread's ROT ");
} }
// walk the values // walk the values
Iterator<JacobObject> it = tab.keySet().iterator(); Iterator<JacobObject> it = tab.keySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
JacobObject o = it.next(); JacobObject o = it.next();
if (o != null if (o != null
// can't use this cause creates a Variant if calling SafeAray // can't use this cause creates a Variant if calling SafeAray
// and we get an exception modifying the collection while // and we get an exception modifying the collection while
// iterating // iterating
// && o.toString() != null // && o.toString() != null
) { ) {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
if (o instanceof SafeArray) { if (o instanceof SafeArray) {
// SafeArray create more objects when calling // SafeArray create more objects when calling
// toString() // toString()
// which causes a concurrent modification exception // which causes a concurrent modification exception
// in HashMap // in HashMap
JacobObject.debug("ROT: removing " JacobObject.debug("ROT: removing "
+ o.getClass().getName()); + o.getClass().getName());
} else { } else {
// Variant toString() is probably always bad in here // Variant toString() is probably always bad in here
JacobObject.debug("ROT: removing " + o.hashCode() JacobObject.debug("ROT: removing " + o.hashCode()
+ "->" + o.getClass().getName()); + "->" + o.getClass().getName());
} }
} }
o.safeRelease(); o.safeRelease();
} }
} }
// empty the collection // empty the collection
tab.clear(); tab.clear();
// remove the collection from rot // remove the collection from rot
ROT.removeThread(); ROT.removeThread();
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: thread table cleared and removed"); JacobObject.debug("ROT: thread table cleared and removed");
} }
} else { } else {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: nothing to clear!"); JacobObject.debug("ROT: nothing to clear!");
} }
} }
} }
/** /**
* Removes the map from the rot that is associated with the current thread. * Removes the map from the rot that is associated with the current thread.
*/ */
private synchronized static void removeThread() { private synchronized static void removeThread() {
// should this see if it exists first? // should this see if it exists first?
rot.remove(Thread.currentThread().getName()); rot.remove(Thread.currentThread().getName());
} }
/** /**
* @deprecated the java model leave the responsibility of clearing up * @deprecated the java model leave the responsibility of clearing up
* objects to the Garbage Collector. Our programming model * objects to the Garbage Collector. Our programming model
* should not require that the user specifically remove object * should not require that the user specifically remove object
* from the thread. <br> * from the thread. <br>
* This will remove an object from the ROT <br> * This will remove an object from the ROT <br>
* This does not need to be synchronized because only the rot * This does not need to be synchronized because only the rot
* modification related methods need to synchronized. Each * modification related methods need to synchronized. Each
* individual map is only modified in a single thread. * individual map is only modified in a single thread.
* @param o * @param o
*/ */
@Deprecated @Deprecated
protected static void removeObject(JacobObject o) { protected static void removeObject(JacobObject o) {
Map<JacobObject, String> tab = ROT.getThreadObjects(false); Map<JacobObject, String> tab = ROT.getThreadObjects(false);
if (tab != null) { if (tab != null) {
tab.remove(o); tab.remove(o);
} }
o.safeRelease(); o.safeRelease();
} }
/** /**
* Adds an object to the HashMap for the current thread. <br> * Adds an object to the HashMap for the current thread. <br>
* <p> * <p>
* This method does not need to be threaded because the only concurrent * This method does not need to be threaded because the only concurrent
* modification risk is on the hash map that contains all of the thread * modification risk is on the hash map that contains all of the thread
* related hash maps. The individual thread related maps are only used on a * related hash maps. The individual thread related maps are only used on a
* per thread basis so there isn't a locking issue. * per thread basis so there isn't a locking issue.
* <p> * <p>
* In addition, this method cannot be threaded because it calls * In addition, this method cannot be threaded because it calls
* ComThread.InitMTA. The ComThread object has some methods that call ROT so * ComThread.InitMTA. The ComThread object has some methods that call ROT so
* we could end up deadlocked. This method should be safe without the * we could end up deadlocked. This method should be safe without the
* synchronization because the ROT works on per thread basis and the methods * synchronization because the ROT works on per thread basis and the methods
* that add threads and remove thread related entries are all synchronized * that add threads and remove thread related entries are all synchronized
* *
* *
* @param o * @param o
*/ */
protected static void addObject(JacobObject o) { protected static void addObject(JacobObject o) {
String shouldIncludeClassInROT = "true"; String shouldIncludeClassInROT = "true";
// only call System.getProperty if we are not including all classes in // only call System.getProperty if we are not including all classes in
// the ROT. This lets us run with standard Jacob behavior in Applets // the ROT. This lets us run with standard Jacob behavior in Applets
// without the security exception raised by System.getProperty in the // without the security exception raised by System.getProperty in the
// flow // flow
if (!ROT.INCLUDE_ALL_CLASSES_IN_ROT) { if (!ROT.INCLUDE_ALL_CLASSES_IN_ROT) {
shouldIncludeClassInROT = System.getProperty(o.getClass().getName() shouldIncludeClassInROT = System.getProperty(o.getClass().getName()
+ PUT_IN_ROT_SUFFIX, "true"); + PUT_IN_ROT_SUFFIX, "true");
} }
if (shouldIncludeClassInROT.equalsIgnoreCase("false")) { if (shouldIncludeClassInROT.equalsIgnoreCase("false")) {
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("JacobObject: New instance of " JacobObject.debug("JacobObject: New instance of "
+ o.getClass().getName() + " not added to ROT"); + o.getClass().getName() + " not added to ROT");
} }
} else { } else {
// first see if we have a table for this thread // first see if we have a table for this thread
Map<JacobObject, String> tab = getThreadObjects(false); Map<JacobObject, String> tab = getThreadObjects(false);
if (tab == null) { if (tab == null) {
// this thread has not been initialized as a COM thread // this thread has not been initialized as a COM thread
// so make it part of MTA for backwards compatibility // so make it part of MTA for backwards compatibility
ComThread.InitMTA(false); ComThread.InitMTA(false);
// don't really need the "true" because the InitMTA will have // don't really need the "true" because the InitMTA will have
// called back to the ROT to create a table for this thread // called back to the ROT to create a table for this thread
tab = getThreadObjects(true); tab = getThreadObjects(true);
} }
if (JacobObject.isDebugEnabled()) { if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: adding " + o + "->" JacobObject.debug("ROT: adding " + o + "->"
+ o.getClass().getName() + o.getClass().getName()
+ " table size prior to addition:" + tab.size()); + " table size prior to addition:" + tab.size());
} }
// add the object to the table that is specific to this thread // add the object to the table that is specific to this thread
if (tab != null) { if (tab != null) {
tab.put(o, null); tab.put(o, null);
} }
} }
} }
/** /**
* ROT can't be a subclass of JacobObject because of the way ROT pools are * ROT can't be a subclass of JacobObject because of the way ROT pools are
* managed so we force a DLL load here by referencing JacobObject * managed so we force a DLL load here by referencing JacobObject
*/ */
static { static {
LibraryLoader.loadJacobLibrary(); LibraryLoader.loadJacobLibrary();
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -44,77 +44,77 @@ package com.jacob.com;
* component that wants to run in an STA other than the main STA. * component that wants to run in an STA other than the main STA.
*/ */
public class STA extends Thread { public class STA extends Thread {
/** /**
* referenced by STA.cpp * referenced by STA.cpp
*/ */
public int threadID; public int threadID;
/** /**
* constructor for STA * constructor for STA
*/ */
public STA() { public STA() {
start(); // start the thread start(); // start the thread
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see java.lang.Thread#run() * @see java.lang.Thread#run()
*/ */
public void run() { public void run() {
// init COM // init COM
ComThread.InitSTA(); ComThread.InitSTA();
if (OnInit()) { if (OnInit()) {
// this call blocks in the win32 message loop // this call blocks in the win32 message loop
// until quitMessagePump is called // until quitMessagePump is called
doMessagePump(); doMessagePump();
} }
OnQuit(); OnQuit();
// uninit COM // uninit COM
ComThread.Release(); ComThread.Release();
} }
/** /**
* Override this method to create and initialize any COM component that you * Override this method to create and initialize any COM component that you
* want to run in this thread. If anything fails, return false to terminate * want to run in this thread. If anything fails, return false to terminate
* the thread. * the thread.
* *
* @return always returns true * @return always returns true
*/ */
public boolean OnInit() { public boolean OnInit() {
return true; return true;
} }
/** /**
* Override this method to destroy any resource before the thread exits and * Override this method to destroy any resource before the thread exits and
* COM in uninitialized * COM in uninitialized
*/ */
public void OnQuit() { public void OnQuit() {
// there is nothing to see here // there is nothing to see here
} }
/** /**
* calls quitMessagePump * calls quitMessagePump
*/ */
public void quit() { public void quit() {
quitMessagePump(); quitMessagePump();
} }
/** /**
* run a message pump for the main STA * run a message pump for the main STA
*/ */
public native void doMessagePump(); public native void doMessagePump();
/** /**
* quit message pump for the main STA * quit message pump for the main STA
*/ */
public native void quitMessagePump(); public native void quitMessagePump();
/** /**
* STA isn't a subclass of JacobObject so a reference to it doesn't load the * STA isn't a subclass of JacobObject so a reference to it doesn't load the
* DLL without this * DLL without this
*/ */
static { static {
LibraryLoader.loadJacobLibrary(); LibraryLoader.loadJacobLibrary();
} }
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
/** /**
* *
@@ -51,485 +51,485 @@ import java.util.Date;
* A utility class used to convert between Java objects and Variants * A utility class used to convert between Java objects and Variants
*/ */
public final class VariantUtilities { public final class VariantUtilities {
private VariantUtilities() { private VariantUtilities() {
// utility class with only static methods don't need constructors // utility class with only static methods don't need constructors
} }
/** /**
* Populates a variant object from a java object. This method attempts to * Populates a variant object from a java object. This method attempts to
* figure out the appropriate Variant type * figure out the appropriate Variant type
* *
* @param targetVariant * @param targetVariant
* @param pValueObject * @param pValueObject
* @param fByRef * @param fByRef
*/ */
protected static void populateVariant(Variant targetVariant, protected static void populateVariant(Variant targetVariant,
Object pValueObject, boolean fByRef) { Object pValueObject, boolean fByRef) {
if (pValueObject == null) { if (pValueObject == null) {
targetVariant.putEmpty(); targetVariant.putEmpty();
} else if (pValueObject instanceof Integer) { } else if (pValueObject instanceof Integer) {
if (fByRef) { if (fByRef) {
targetVariant.putIntRef(((Integer) pValueObject).intValue()); targetVariant.putIntRef(((Integer) pValueObject).intValue());
} else { } else {
targetVariant.putInt(((Integer) pValueObject).intValue()); targetVariant.putInt(((Integer) pValueObject).intValue());
} }
} else if (pValueObject instanceof Short) { } else if (pValueObject instanceof Short) {
if (fByRef) { if (fByRef) {
targetVariant.putShortRef(((Short) pValueObject).shortValue()); targetVariant.putShortRef(((Short) pValueObject).shortValue());
} else { } else {
targetVariant.putShort(((Short) pValueObject).shortValue()); targetVariant.putShort(((Short) pValueObject).shortValue());
} }
} else if (pValueObject instanceof String) { } else if (pValueObject instanceof String) {
if (fByRef) { if (fByRef) {
targetVariant.putStringRef((String) pValueObject); targetVariant.putStringRef((String) pValueObject);
} else { } else {
targetVariant.putString((String) pValueObject); targetVariant.putString((String) pValueObject);
} }
} else if (pValueObject instanceof Boolean) { } else if (pValueObject instanceof Boolean) {
if (fByRef) { if (fByRef) {
targetVariant.putBooleanRef(((Boolean) pValueObject) targetVariant.putBooleanRef(((Boolean) pValueObject)
.booleanValue()); .booleanValue());
} else { } else {
targetVariant.putBoolean(((Boolean) pValueObject) targetVariant.putBoolean(((Boolean) pValueObject)
.booleanValue()); .booleanValue());
} }
} else if (pValueObject instanceof Double) { } else if (pValueObject instanceof Double) {
if (fByRef) { if (fByRef) {
targetVariant.putDoubleRef(((Double) pValueObject) targetVariant.putDoubleRef(((Double) pValueObject)
.doubleValue()); .doubleValue());
} else { } else {
targetVariant.putDouble(((Double) pValueObject).doubleValue()); targetVariant.putDouble(((Double) pValueObject).doubleValue());
} }
} else if (pValueObject instanceof Float) { } else if (pValueObject instanceof Float) {
if (fByRef) { if (fByRef) {
targetVariant.putFloatRef(((Float) pValueObject).floatValue()); targetVariant.putFloatRef(((Float) pValueObject).floatValue());
} else { } else {
targetVariant.putFloat(((Float) pValueObject).floatValue()); targetVariant.putFloat(((Float) pValueObject).floatValue());
} }
} else if (pValueObject instanceof BigDecimal) { } else if (pValueObject instanceof BigDecimal) {
if (fByRef) { if (fByRef) {
targetVariant.putDecimalRef(((BigDecimal) pValueObject)); targetVariant.putDecimalRef(((BigDecimal) pValueObject));
} else { } else {
targetVariant.putDecimal(((BigDecimal) pValueObject)); targetVariant.putDecimal(((BigDecimal) pValueObject));
} }
} else if (pValueObject instanceof Byte) { } else if (pValueObject instanceof Byte) {
if (fByRef) { if (fByRef) {
targetVariant.putByteRef(((Byte) pValueObject).byteValue()); targetVariant.putByteRef(((Byte) pValueObject).byteValue());
} else { } else {
targetVariant.putByte(((Byte) pValueObject).byteValue()); targetVariant.putByte(((Byte) pValueObject).byteValue());
} }
} else if (pValueObject instanceof Date) { } else if (pValueObject instanceof Date) {
if (fByRef) { if (fByRef) {
targetVariant.putDateRef((Date) pValueObject); targetVariant.putDateRef((Date) pValueObject);
} else { } else {
targetVariant.putDate((Date) pValueObject); targetVariant.putDate((Date) pValueObject);
} }
} else if (pValueObject instanceof Long) { } else if (pValueObject instanceof Long) {
if (fByRef) { if (fByRef) {
targetVariant.putLongRef(((Long) pValueObject).longValue()); targetVariant.putLongRef(((Long) pValueObject).longValue());
} else { } else {
targetVariant.putLong(((Long) pValueObject).longValue()); targetVariant.putLong(((Long) pValueObject).longValue());
} }
} else if (pValueObject instanceof Currency) { } else if (pValueObject instanceof Currency) {
if (fByRef) { if (fByRef) {
targetVariant.putCurrencyRef(((Currency) pValueObject)); targetVariant.putCurrencyRef(((Currency) pValueObject));
} else { } else {
targetVariant.putCurrency(((Currency) pValueObject)); targetVariant.putCurrency(((Currency) pValueObject));
} }
} else if (pValueObject instanceof SafeArray) { } else if (pValueObject instanceof SafeArray) {
if (fByRef) { if (fByRef) {
targetVariant.putSafeArrayRef((SafeArray) pValueObject); targetVariant.putSafeArrayRef((SafeArray) pValueObject);
} else { } else {
targetVariant.putSafeArray((SafeArray) pValueObject); targetVariant.putSafeArray((SafeArray) pValueObject);
} }
} else if (pValueObject instanceof Dispatch) { } else if (pValueObject instanceof Dispatch) {
if (fByRef) { if (fByRef) {
targetVariant.putDispatchRef((Dispatch) pValueObject); targetVariant.putDispatchRef((Dispatch) pValueObject);
} else { } else {
targetVariant.putDispatch((Dispatch) pValueObject); targetVariant.putDispatch((Dispatch) pValueObject);
} }
} else if (pValueObject instanceof Variant) { } else if (pValueObject instanceof Variant) {
// newly added 1.12-pre6 to support VT_VARIANT // newly added 1.12-pre6 to support VT_VARIANT
targetVariant.putVariant(pValueObject); targetVariant.putVariant(pValueObject);
} else { } else {
// sourceforge patch 2171967 // sourceforge patch 2171967
// used to rely on coercion but sometimes crashed VM // used to rely on coercion but sometimes crashed VM
throw new NotImplementedException( throw new NotImplementedException(
"populateVariant() not implemented for " "populateVariant() not implemented for "
+ pValueObject.getClass()); + pValueObject.getClass());
} }
} }
/** /**
* Map arguments based on msdn documentation. This method relies on the * Map arguments based on msdn documentation. This method relies on the
* variant constructor except for arrays. * variant constructor except for arrays.
* *
* @param objectToBeMadeIntoVariant * @param objectToBeMadeIntoVariant
* @return Variant that represents the object * @return Variant that represents the object
*/ */
protected static Variant objectToVariant(Object objectToBeMadeIntoVariant) { protected static Variant objectToVariant(Object objectToBeMadeIntoVariant) {
if (objectToBeMadeIntoVariant == null) { if (objectToBeMadeIntoVariant == null) {
return new Variant(); return new Variant();
} else if (objectToBeMadeIntoVariant instanceof Variant) { } else if (objectToBeMadeIntoVariant instanceof Variant) {
// if a variant was passed in then be a slacker and just return it // if a variant was passed in then be a slacker and just return it
return (Variant) objectToBeMadeIntoVariant; return (Variant) objectToBeMadeIntoVariant;
} else if (objectToBeMadeIntoVariant.getClass().isArray()) { } else if (objectToBeMadeIntoVariant.getClass().isArray()) {
// automatically convert arrays using reflection // automatically convert arrays using reflection
// handle it differently based on the type of array // handle it differently based on the type of array
// added primitive support sourceforge 2762275 // added primitive support sourceforge 2762275
SafeArray sa = null; SafeArray sa = null;
int len1 = Array.getLength(objectToBeMadeIntoVariant); int len1 = Array.getLength(objectToBeMadeIntoVariant);
Class componentType = objectToBeMadeIntoVariant.getClass() Class componentType = objectToBeMadeIntoVariant.getClass()
.getComponentType(); .getComponentType();
if (componentType.isArray()) { // array of arrays if (componentType.isArray()) { // array of arrays
int max = 0; int max = 0;
for (int i = 0; i < len1; i++) { for (int i = 0; i < len1; i++) {
Object e1 = Array.get(objectToBeMadeIntoVariant, i); Object e1 = Array.get(objectToBeMadeIntoVariant, i);
int len2 = Array.getLength(e1); int len2 = Array.getLength(e1);
if (max < len2) { if (max < len2) {
max = len2; max = len2;
} }
} }
sa = new SafeArray(Variant.VariantVariant, len1, max); sa = new SafeArray(Variant.VariantVariant, len1, max);
for (int i = 0; i < len1; i++) { for (int i = 0; i < len1; i++) {
Object e1 = Array.get(objectToBeMadeIntoVariant, i); Object e1 = Array.get(objectToBeMadeIntoVariant, i);
for (int j = 0; j < Array.getLength(e1); j++) { for (int j = 0; j < Array.getLength(e1); j++) {
sa.setVariant(i, j, objectToVariant(Array.get(e1, j))); sa.setVariant(i, j, objectToVariant(Array.get(e1, j)));
} }
} }
} else if (byte.class.equals(componentType)) { } else if (byte.class.equals(componentType)) {
byte[] arr = (byte[]) objectToBeMadeIntoVariant; byte[] arr = (byte[]) objectToBeMadeIntoVariant;
sa = new SafeArray(Variant.VariantByte, len1); sa = new SafeArray(Variant.VariantByte, len1);
for (int i = 0; i < len1; i++) { for (int i = 0; i < len1; i++) {
sa.setByte(i, arr[i]); sa.setByte(i, arr[i]);
} }
} else if (int.class.equals(componentType)) { } else if (int.class.equals(componentType)) {
int[] arr = (int[]) objectToBeMadeIntoVariant; int[] arr = (int[]) objectToBeMadeIntoVariant;
sa = new SafeArray(Variant.VariantInt, len1); sa = new SafeArray(Variant.VariantInt, len1);
for (int i = 0; i < len1; i++) { for (int i = 0; i < len1; i++) {
sa.setInt(i, arr[i]); sa.setInt(i, arr[i]);
} }
} else if (double.class.equals(componentType)) { } else if (double.class.equals(componentType)) {
double[] arr = (double[]) objectToBeMadeIntoVariant; double[] arr = (double[]) objectToBeMadeIntoVariant;
sa = new SafeArray(Variant.VariantDouble, len1); sa = new SafeArray(Variant.VariantDouble, len1);
for (int i = 0; i < len1; i++) { for (int i = 0; i < len1; i++) {
sa.setDouble(i, arr[i]); sa.setDouble(i, arr[i]);
} }
} else if (long.class.equals(componentType)) { } else if (long.class.equals(componentType)) {
long[] arr = (long[]) objectToBeMadeIntoVariant; long[] arr = (long[]) objectToBeMadeIntoVariant;
sa = new SafeArray(Variant.VariantLongInt, len1); sa = new SafeArray(Variant.VariantLongInt, len1);
for (int i = 0; i < len1; i++) { for (int i = 0; i < len1; i++) {
sa.setLong(i, arr[i]); sa.setLong(i, arr[i]);
} }
} else { } else {
// array of object // array of object
sa = new SafeArray(Variant.VariantVariant, len1); sa = new SafeArray(Variant.VariantVariant, len1);
for (int i = 0; i < len1; i++) { for (int i = 0; i < len1; i++) {
sa.setVariant(i, objectToVariant(Array.get( sa.setVariant(i, objectToVariant(Array.get(
objectToBeMadeIntoVariant, i))); objectToBeMadeIntoVariant, i)));
} }
} }
Variant returnVariant = new Variant(); Variant returnVariant = new Variant();
populateVariant(returnVariant, sa, false); populateVariant(returnVariant, sa, false);
return returnVariant; return returnVariant;
} else { } else {
// rely on populateVariant to throw an exception if its an // rely on populateVariant to throw an exception if its an
// invalid type // invalid type
Variant returnVariant = new Variant(); Variant returnVariant = new Variant();
populateVariant(returnVariant, objectToBeMadeIntoVariant, false); populateVariant(returnVariant, objectToBeMadeIntoVariant, false);
return returnVariant; return returnVariant;
} }
} }
/** /**
* converts an array of objects into an array of Variants by repeatedly * converts an array of objects into an array of Variants by repeatedly
* calling obj2Variant(Object) * calling obj2Variant(Object)
* *
* @param arrayOfObjectsToBeConverted * @param arrayOfObjectsToBeConverted
* @return Variant[] * @return Variant[]
*/ */
protected static Variant[] objectsToVariants( protected static Variant[] objectsToVariants(
Object[] arrayOfObjectsToBeConverted) { Object[] arrayOfObjectsToBeConverted) {
Variant vArg[] = new Variant[arrayOfObjectsToBeConverted.length]; Variant vArg[] = new Variant[arrayOfObjectsToBeConverted.length];
for (int i = 0; i < arrayOfObjectsToBeConverted.length; i++) { for (int i = 0; i < arrayOfObjectsToBeConverted.length; i++) {
vArg[i] = objectToVariant(arrayOfObjectsToBeConverted[i]); vArg[i] = objectToVariant(arrayOfObjectsToBeConverted[i]);
} }
return vArg; return vArg;
} }
/** /**
* Convert a JACOB Variant value to a Java object (type conversions). * Convert a JACOB Variant value to a Java object (type conversions).
* provided in Sourceforge feature request 959381. A fix was done to handle * provided in Sourceforge feature request 959381. A fix was done to handle
* byRef bug report 1607878. * byRef bug report 1607878.
* <p> * <p>
* Unlike other toXXX() methods, it does not do a type conversion except for * Unlike other toXXX() methods, it does not do a type conversion except for
* special data types (it shouldn't do any!) * special data types (it shouldn't do any!)
* <p> * <p>
* Converts Variant.VariantArray types to SafeArrays * Converts Variant.VariantArray types to SafeArrays
* *
* @return Corresponding Java object of the type matching the Variant type. * @return Corresponding Java object of the type matching the Variant type.
* @throws IllegalStateException * @throws IllegalStateException
* if no underlying windows data structure * if no underlying windows data structure
* @throws NotImplementedException * @throws NotImplementedException
* if unsupported conversion is requested * if unsupported conversion is requested
* @throws JacobException * @throws JacobException
* if the calculated result was a JacobObject usually as a * if the calculated result was a JacobObject usually as a
* result of error * result of error
*/ */
protected static Object variantToObject(Variant sourceData) { protected static Object variantToObject(Variant sourceData) {
Object result = null; Object result = null;
short type = sourceData.getvt(); // variant type short type = sourceData.getvt(); // variant type
if ((type & Variant.VariantArray) == Variant.VariantArray) { // array if ((type & Variant.VariantArray) == Variant.VariantArray) { // array
// returned? // returned?
SafeArray array = null; SafeArray array = null;
type = (short) (type - Variant.VariantArray); type = (short) (type - Variant.VariantArray);
// From SF Bug 1840487 // From SF Bug 1840487
// This did call toSafeArray(false) but that meant // This did call toSafeArray(false) but that meant
// this was the only variantToObject() that didn't have its own // this was the only variantToObject() that didn't have its own
// copy of the data so you would end up with weird run time // copy of the data so you would end up with weird run time
// errors after some GC. So now we just get stupid about it and // errors after some GC. So now we just get stupid about it and
// always make a copy just like toSafeArray() does. // always make a copy just like toSafeArray() does.
array = sourceData.toSafeArray(); array = sourceData.toSafeArray();
result = array; result = array;
} else { // non-array object returned } else { // non-array object returned
switch (type) { switch (type) {
case Variant.VariantEmpty: // 0 case Variant.VariantEmpty: // 0
case Variant.VariantNull: // 1 case Variant.VariantNull: // 1
break; break;
case Variant.VariantShort: // 2 case Variant.VariantShort: // 2
result = new Short(sourceData.getShort()); result = new Short(sourceData.getShort());
break; break;
case Variant.VariantShort | Variant.VariantByref: // 2 case Variant.VariantShort | Variant.VariantByref: // 2
result = new Short(sourceData.getShortRef()); result = new Short(sourceData.getShortRef());
break; break;
case Variant.VariantInt: // 3 case Variant.VariantInt: // 3
result = new Integer(sourceData.getInt()); result = new Integer(sourceData.getInt());
break; break;
case Variant.VariantInt | Variant.VariantByref: // 3 case Variant.VariantInt | Variant.VariantByref: // 3
result = new Integer(sourceData.getIntRef()); result = new Integer(sourceData.getIntRef());
break; break;
case Variant.VariantFloat: // 4 case Variant.VariantFloat: // 4
result = new Float(sourceData.getFloat()); result = new Float(sourceData.getFloat());
break; break;
case Variant.VariantFloat | Variant.VariantByref: // 4 case Variant.VariantFloat | Variant.VariantByref: // 4
result = new Float(sourceData.getFloatRef()); result = new Float(sourceData.getFloatRef());
break; break;
case Variant.VariantDouble: // 5 case Variant.VariantDouble: // 5
result = new Double(sourceData.getDouble()); result = new Double(sourceData.getDouble());
break; break;
case Variant.VariantDouble | Variant.VariantByref: // 5 case Variant.VariantDouble | Variant.VariantByref: // 5
result = new Double(sourceData.getDoubleRef()); result = new Double(sourceData.getDoubleRef());
break; break;
case Variant.VariantCurrency: // 6 case Variant.VariantCurrency: // 6
result = sourceData.getCurrency(); result = sourceData.getCurrency();
break; break;
case Variant.VariantCurrency | Variant.VariantByref: // 6 case Variant.VariantCurrency | Variant.VariantByref: // 6
result = sourceData.getCurrencyRef(); result = sourceData.getCurrencyRef();
break; break;
case Variant.VariantDate: // 7 case Variant.VariantDate: // 7
result = sourceData.getJavaDate(); result = sourceData.getJavaDate();
break; break;
case Variant.VariantDate | Variant.VariantByref: // 7 case Variant.VariantDate | Variant.VariantByref: // 7
result = sourceData.getJavaDateRef(); result = sourceData.getJavaDateRef();
break; break;
case Variant.VariantString: // 8 case Variant.VariantString: // 8
result = sourceData.getString(); result = sourceData.getString();
break; break;
case Variant.VariantString | Variant.VariantByref: // 8 case Variant.VariantString | Variant.VariantByref: // 8
result = sourceData.getStringRef(); result = sourceData.getStringRef();
break; break;
case Variant.VariantDispatch: // 9 case Variant.VariantDispatch: // 9
result = sourceData.getDispatch(); result = sourceData.getDispatch();
break; break;
case Variant.VariantDispatch | Variant.VariantByref: // 9 case Variant.VariantDispatch | Variant.VariantByref: // 9
result = sourceData.getDispatchRef(); // Can dispatches even result = sourceData.getDispatchRef(); // Can dispatches even
// be byRef? // be byRef?
break; break;
case Variant.VariantError: // 10 case Variant.VariantError: // 10
result = new NotImplementedException( result = new NotImplementedException(
"toJavaObject() Not implemented for VariantError"); "toJavaObject() Not implemented for VariantError");
break; break;
case Variant.VariantBoolean: // 11 case Variant.VariantBoolean: // 11
result = new Boolean(sourceData.getBoolean()); result = new Boolean(sourceData.getBoolean());
break; break;
case Variant.VariantBoolean | Variant.VariantByref: // 11 case Variant.VariantBoolean | Variant.VariantByref: // 11
result = new Boolean(sourceData.getBooleanRef()); result = new Boolean(sourceData.getBooleanRef());
break; break;
case Variant.VariantVariant: // 12 they are always by ref case Variant.VariantVariant: // 12 they are always by ref
result = new NotImplementedException( result = new NotImplementedException(
"toJavaObject() Not implemented for VariantVariant without ByRef"); "toJavaObject() Not implemented for VariantVariant without ByRef");
break; break;
case Variant.VariantVariant | Variant.VariantByref: // 12 case Variant.VariantVariant | Variant.VariantByref: // 12
result = sourceData.getVariant(); result = sourceData.getVariant();
break; break;
case Variant.VariantObject: // 13 case Variant.VariantObject: // 13
result = new NotImplementedException( result = new NotImplementedException(
"toJavaObject() Not implemented for VariantObject"); "toJavaObject() Not implemented for VariantObject");
break; break;
case Variant.VariantDecimal: // 14 case Variant.VariantDecimal: // 14
result = sourceData.getDecimal(); result = sourceData.getDecimal();
break; break;
case Variant.VariantDecimal | Variant.VariantByref: // 14 case Variant.VariantDecimal | Variant.VariantByref: // 14
result = sourceData.getDecimalRef(); result = sourceData.getDecimalRef();
break; break;
case Variant.VariantByte: // 17 case Variant.VariantByte: // 17
result = new Byte(sourceData.getByte()); result = new Byte(sourceData.getByte());
break; break;
case Variant.VariantByte | Variant.VariantByref: // 17 case Variant.VariantByte | Variant.VariantByref: // 17
result = new Byte(sourceData.getByteRef()); result = new Byte(sourceData.getByteRef());
break; break;
case Variant.VariantLongInt: // 20 case Variant.VariantLongInt: // 20
result = new Long(sourceData.getLong()); result = new Long(sourceData.getLong());
break; break;
case Variant.VariantLongInt | Variant.VariantByref: // 20 case Variant.VariantLongInt | Variant.VariantByref: // 20
result = new Long(sourceData.getLongRef()); result = new Long(sourceData.getLongRef());
break; break;
case Variant.VariantTypeMask: // 4095 case Variant.VariantTypeMask: // 4095
result = new NotImplementedException( result = new NotImplementedException(
"toJavaObject() Not implemented for VariantTypeMask"); "toJavaObject() Not implemented for VariantTypeMask");
break; break;
case Variant.VariantArray: // 8192 case Variant.VariantArray: // 8192
result = new NotImplementedException( result = new NotImplementedException(
"toJavaObject() Not implemented for VariantArray"); "toJavaObject() Not implemented for VariantArray");
break; break;
case Variant.VariantByref: // 16384 case Variant.VariantByref: // 16384
result = new NotImplementedException( result = new NotImplementedException(
"toJavaObject() Not implemented for VariantByref"); "toJavaObject() Not implemented for VariantByref");
break; break;
default: default:
result = new NotImplementedException("Unknown return type: " result = new NotImplementedException("Unknown return type: "
+ type); + type);
// there was a "return result" here that caused defect 1602118 // there was a "return result" here that caused defect 1602118
// so it was removed // so it was removed
break; break;
}// switch (type) }// switch (type)
if (result instanceof JacobException) { if (result instanceof JacobException) {
throw (JacobException) result; throw (JacobException) result;
} }
} }
return result; return result;
}// toJava() }// toJava()
/** /**
* Verifies that we have a scale 0 <= x <= 28 and now more than 96 bits of * Verifies that we have a scale 0 <= x <= 28 and now more than 96 bits of
* data. The roundToMSDecimal method will attempt to adjust a BigDecimal to * data. The roundToMSDecimal method will attempt to adjust a BigDecimal to
* pass this set of tests * pass this set of tests
* *
* @param in * @param in
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if out of bounds * if out of bounds
*/ */
protected static void validateDecimalScaleAndBits(BigDecimal in) { protected static void validateDecimalScaleAndBits(BigDecimal in) {
BigInteger allWordBigInt = in.unscaledValue(); BigInteger allWordBigInt = in.unscaledValue();
if (in.scale() > 28) { if (in.scale() > 28) {
// should this cast to a string and call putStringRef()? // should this cast to a string and call putStringRef()?
throw new IllegalArgumentException( throw new IllegalArgumentException(
"VT_DECIMAL only supports a maximum scale of 28 and the passed" "VT_DECIMAL only supports a maximum scale of 28 and the passed"
+ " in value has a scale of " + in.scale()); + " in value has a scale of " + in.scale());
} else if (in.scale() < 0) { } else if (in.scale() < 0) {
// should this cast to a string and call putStringRef()? // should this cast to a string and call putStringRef()?
throw new IllegalArgumentException( throw new IllegalArgumentException(
"VT_DECIMAL only supports a minimum scale of 0 and the passed" "VT_DECIMAL only supports a minimum scale of 0 and the passed"
+ " in value has a scale of " + in.scale()); + " in value has a scale of " + in.scale());
} else if (allWordBigInt.bitLength() > 12 * 8) { } else if (allWordBigInt.bitLength() > 12 * 8) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"VT_DECIMAL supports a maximum of " "VT_DECIMAL supports a maximum of "
+ 12 + 12
* 8 * 8
+ " bits not counting scale and the number passed in has " + " bits not counting scale and the number passed in has "
+ allWordBigInt.bitLength()); + allWordBigInt.bitLength());
} else { } else {
// no bounds problem to be handled // no bounds problem to be handled
} }
} }
/** /**
* Largest possible number with scale set to 0 * Largest possible number with scale set to 0
*/ */
private static final BigDecimal LARGEST_DECIMAL = new BigDecimal( private static final BigDecimal LARGEST_DECIMAL = new BigDecimal(
new BigInteger("ffffffffffffffffffffffff", 16)); new BigInteger("ffffffffffffffffffffffff", 16));
/** /**
* Smallest possible number with scale set to 0. MS doesn't support negative * Smallest possible number with scale set to 0. MS doesn't support negative
* scales like BigDecimal. * scales like BigDecimal.
*/ */
private static final BigDecimal SMALLEST_DECIMAL = new BigDecimal( private static final BigDecimal SMALLEST_DECIMAL = new BigDecimal(
new BigInteger("ffffffffffffffffffffffff", 16).negate()); new BigInteger("ffffffffffffffffffffffff", 16).negate());
/** /**
* Does any validation that couldn't have been fixed by rounding or scale * Does any validation that couldn't have been fixed by rounding or scale
* modification. * modification.
* *
* @param in * @param in
* The BigDecimal to be validated * The BigDecimal to be validated
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if the number is too large or too small or null * if the number is too large or too small or null
*/ */
protected static void validateDecimalMinMax(BigDecimal in) { protected static void validateDecimalMinMax(BigDecimal in) {
if (in == null) { if (in == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"null is not a supported Decimal value."); "null is not a supported Decimal value.");
} else if (LARGEST_DECIMAL.compareTo(in) < 0) { } else if (LARGEST_DECIMAL.compareTo(in) < 0) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Value too large for VT_DECIMAL data type:" + in.toString() "Value too large for VT_DECIMAL data type:" + in.toString()
+ " integer: " + in.toBigInteger().toString(16) + " integer: " + in.toBigInteger().toString(16)
+ " scale: " + in.scale()); + " scale: " + in.scale());
} else if (SMALLEST_DECIMAL.compareTo(in) > 0) { } else if (SMALLEST_DECIMAL.compareTo(in) > 0) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Value too small for VT_DECIMAL data type:" + in.toString() "Value too small for VT_DECIMAL data type:" + in.toString()
+ " integer: " + in.toBigInteger().toString(16) + " integer: " + in.toBigInteger().toString(16)
+ " scale: " + in.scale()); + " scale: " + in.scale());
} }
} }
/** /**
* Rounds the scale and bit length so that it will pass * Rounds the scale and bit length so that it will pass
* validateDecimalScaleBits(). Developers should call this method if they * validateDecimalScaleBits(). Developers should call this method if they
* really want MS Decimal and don't want to lose precision. * really want MS Decimal and don't want to lose precision.
* <p> * <p>
* Changing the scale on a number that can fit in an MS Decimal can change * Changing the scale on a number that can fit in an MS Decimal can change
* the number's representation enough that it will round to a number too * the number's representation enough that it will round to a number too
* large to be represented by an MS VT_DECIMAL * large to be represented by an MS VT_DECIMAL
* *
* @param sourceDecimal * @param sourceDecimal
* @return BigDecimal a new big decimal that was rounded to fit in an MS * @return BigDecimal a new big decimal that was rounded to fit in an MS
* VT_DECIMAL * VT_DECIMAL
*/ */
public static BigDecimal roundToMSDecimal(BigDecimal sourceDecimal) { public static BigDecimal roundToMSDecimal(BigDecimal sourceDecimal) {
BigInteger sourceDecimalIntComponent = sourceDecimal.unscaledValue(); BigInteger sourceDecimalIntComponent = sourceDecimal.unscaledValue();
BigDecimal destinationDecimal = new BigDecimal( BigDecimal destinationDecimal = new BigDecimal(
sourceDecimalIntComponent, sourceDecimal.scale()); sourceDecimalIntComponent, sourceDecimal.scale());
int roundingModel = BigDecimal.ROUND_HALF_UP; int roundingModel = BigDecimal.ROUND_HALF_UP;
validateDecimalMinMax(destinationDecimal); validateDecimalMinMax(destinationDecimal);
// First limit the number of digits and then the precision. // First limit the number of digits and then the precision.
// Try and round to 29 digits because we can sometimes do that // Try and round to 29 digits because we can sometimes do that
BigInteger allWordBigInt; BigInteger allWordBigInt;
allWordBigInt = destinationDecimal.unscaledValue(); allWordBigInt = destinationDecimal.unscaledValue();
if (allWordBigInt.bitLength() > 96) { if (allWordBigInt.bitLength() > 96) {
destinationDecimal = destinationDecimal.round(new MathContext(29)); destinationDecimal = destinationDecimal.round(new MathContext(29));
// see if 29 digits uses more than 96 bits // see if 29 digits uses more than 96 bits
if (allWordBigInt.bitLength() > 96) { if (allWordBigInt.bitLength() > 96) {
// Dang. It was over 97 bits so shorten it one more digit to // Dang. It was over 97 bits so shorten it one more digit to
// stay <= 96 bits // stay <= 96 bits
destinationDecimal = destinationDecimal.round(new MathContext( destinationDecimal = destinationDecimal.round(new MathContext(
28)); 28));
} }
} }
// the bit manipulations above may change the scale so do it afterwards // the bit manipulations above may change the scale so do it afterwards
// round the scale to the max MS can support // round the scale to the max MS can support
if (destinationDecimal.scale() > 28) { if (destinationDecimal.scale() > 28) {
destinationDecimal = destinationDecimal.setScale(28, roundingModel); destinationDecimal = destinationDecimal.setScale(28, roundingModel);
} }
if (destinationDecimal.scale() < 0) { if (destinationDecimal.scale() < 0) {
destinationDecimal = destinationDecimal.setScale(0, roundingModel); destinationDecimal = destinationDecimal.setScale(0, roundingModel);
} }
return destinationDecimal; return destinationDecimal;
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -44,10 +44,10 @@ package com.jacob.com;
*/ */
public class VariantViaEvent extends Variant { public class VariantViaEvent extends Variant {
/** /**
* Standard constructor used by JNI event handling layer * Standard constructor used by JNI event handling layer
*/ */
public VariantViaEvent() { public VariantViaEvent() {
super(); super();
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -42,25 +42,25 @@ package com.jacob.com;
* thrown in util.cpp * thrown in util.cpp
*/ */
public class WrongThreadException extends JacobException { public class WrongThreadException extends JacobException {
/** /**
* identifier generated by Eclipse * identifier generated by Eclipse
*/ */
private static final long serialVersionUID = 6308780364980228692L; private static final long serialVersionUID = 6308780364980228692L;
/** /**
* standard 0 arg constructor with no message * standard 0 arg constructor with no message
* *
*/ */
public WrongThreadException() { public WrongThreadException() {
super("No Message Provided."); super("No Message Provided.");
} }
/** /**
* standard constructor with a string message * standard constructor with a string message
* *
* @param s * @param s
*/ */
public WrongThreadException(String s) { public WrongThreadException(String s) {
super(s); super(s);
} }
} }

View File

@@ -13,71 +13,71 @@ import com.jacob.com.Variant;
* options. * options.
*/ */
class MathTest { class MathTest {
/** /**
* standard main program to run the sample * standard main program to run the sample
* *
* @param args * @param args
* command line parameters * command line parameters
*/ */
public static void main(String[] args) { public static void main(String[] args) {
MathTest me = new MathTest(); MathTest me = new MathTest();
me.runTest(); me.runTest();
} }
/** default constructor */ /** default constructor */
public MathTest() { public MathTest() {
} }
/** /**
* not clear why we need a class and run method but that's the way it was * not clear why we need a class and run method but that's the way it was
* written * written
*/ */
public void runTest() { public void runTest() {
// deprecated // deprecated
// System.runFinalizersOnExit(true); // System.runFinalizersOnExit(true);
Dispatch test = new ActiveXComponent("MathTest.Math"); Dispatch test = new ActiveXComponent("MathTest.Math");
TestEvents te = new TestEvents(); TestEvents te = new TestEvents();
DispatchEvents de = new DispatchEvents(test, te); DispatchEvents de = new DispatchEvents(test, te);
if (de == null) { if (de == null) {
System.out System.out
.println("null returned when trying to create DispatchEvents"); .println("null returned when trying to create DispatchEvents");
} }
System.out.println(Dispatch.call(test, "Add", new Variant(1), System.out.println(Dispatch.call(test, "Add", new Variant(1),
new Variant(2))); new Variant(2)));
System.out.println(Dispatch.call(test, "Mult", new Variant(2), System.out.println(Dispatch.call(test, "Mult", new Variant(2),
new Variant(2))); new Variant(2)));
Variant v = Dispatch.call(test, "Mult", new Variant(2), new Variant(2)); Variant v = Dispatch.call(test, "Mult", new Variant(2), new Variant(2));
// this should return false // this should return false
System.out.println("v.isNull=" + v.isNull()); System.out.println("v.isNull=" + v.isNull());
v = Dispatch.call(test, "getNothing"); v = Dispatch.call(test, "getNothing");
// these should return nothing // these should return nothing
System.out.println("v.isNull=" + v.isNull()); System.out.println("v.isNull=" + v.isNull());
System.out.println("v.toDispatch=" + v.toDispatch()); System.out.println("v.toDispatch=" + v.toDispatch());
} }
/** /**
* *
* sample class to catch the events * sample class to catch the events
* *
*/ */
public class TestEvents { public class TestEvents {
/** /**
* catches the DoneAdd event * catches the DoneAdd event
* *
* @param args * @param args
*/ */
public void DoneAdd(Variant[] args) { public void DoneAdd(Variant[] args) {
System.out.println("DoneAdd called in java"); System.out.println("DoneAdd called in java");
} }
/** /**
* catches the DoneMult event * catches the DoneMult event
* *
* @param args * @param args
*/ */
public void DoneMult(Variant[] args) { public void DoneMult(Variant[] args) {
System.out.println("DoneMult called in java"); System.out.println("DoneMult called in java");
} }
} }
} }

View File

@@ -31,114 +31,114 @@ import com.jacob.com.Variant;
* *
*/ */
class Access { class Access {
/** /**
* the main loop for the test * the main loop for the test
* *
* @param args * @param args
* @throws Exception * @throws Exception
*/ */
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ComThread.InitSTA(); ComThread.InitSTA();
// original test used this // original test used this
// ActiveXComponent ax = new ActiveXComponent("DAO.PrivateDBEngine"); // ActiveXComponent ax = new ActiveXComponent("DAO.PrivateDBEngine");
// my xp box with a later release of access needed this // my xp box with a later release of access needed this
ActiveXComponent ax = new ActiveXComponent("DAO.PrivateDBEngine.35"); ActiveXComponent ax = new ActiveXComponent("DAO.PrivateDBEngine.35");
// this only works for access files pre-access-2000 // this only works for access files pre-access-2000
// this line doesn't work on my xp box in Eclipse // this line doesn't work on my xp box in Eclipse
// Dispatch db = open(ax, ".\\sample2.mdb"); // Dispatch db = open(ax, ".\\sample2.mdb");
// this works when running in eclipse because the test cases run pwd // this works when running in eclipse because the test cases run pwd
// project root // project root
Dispatch db = open(ax, "samples/com/jacob/samples/access/sample2.mdb"); Dispatch db = open(ax, "samples/com/jacob/samples/access/sample2.mdb");
String sql = "select * from MainTable"; String sql = "select * from MainTable";
// make a temporary querydef // make a temporary querydef
Dispatch qd = Dispatch.call(db, "CreateQueryDef", "").toDispatch(); Dispatch qd = Dispatch.call(db, "CreateQueryDef", "").toDispatch();
// set the SQL string on it // set the SQL string on it
Dispatch.put(qd, "SQL", sql); Dispatch.put(qd, "SQL", sql);
Variant result = getByQueryDef(qd); Variant result = getByQueryDef(qd);
// the 2-d safearray is transposed from what you might expect // the 2-d safearray is transposed from what you might expect
System.out.println("resulting array is " + result.toSafeArray()); System.out.println("resulting array is " + result.toSafeArray());
close(db); close(db);
System.out.println("about to call ComThread.Release()"); System.out.println("about to call ComThread.Release()");
ComThread.Release(); ComThread.Release();
} }
/** /**
* Open a database * Open a database
* *
* @param ax * @param ax
* @param fileName * @param fileName
* @return dispatch object that was opened * @return dispatch object that was opened
*/ */
public static Dispatch open(ActiveXComponent ax, String fileName) { public static Dispatch open(ActiveXComponent ax, String fileName) {
Variant f = new Variant(false); Variant f = new Variant(false);
// open the file in read-only mode // open the file in read-only mode
Variant[] args = new Variant[] { new Variant(fileName), f, f }; Variant[] args = new Variant[] { new Variant(fileName), f, f };
Dispatch openDB = ax.invoke("OpenDatabase", args).toDispatch(); Dispatch openDB = ax.invoke("OpenDatabase", args).toDispatch();
return openDB; return openDB;
} }
/** /**
* Close a database * Close a database
* *
* @param openDB * @param openDB
* db to be closed * db to be closed
*/ */
public static void close(Dispatch openDB) { public static void close(Dispatch openDB) {
Dispatch.call(openDB, "Close"); Dispatch.call(openDB, "Close");
} }
/** /**
* Extract the values from the recordset * Extract the values from the recordset
* *
* @param recset * @param recset
* @return Variant that is the returned values * @return Variant that is the returned values
*/ */
public static Variant getValues(Dispatch recset) { public static Variant getValues(Dispatch recset) {
Dispatch.callSub(recset, "moveFirst"); Dispatch.callSub(recset, "moveFirst");
Variant vi = new Variant(4096); Variant vi = new Variant(4096);
Variant v = Dispatch.call(recset, "GetRows", vi); Variant v = Dispatch.call(recset, "GetRows", vi);
return v; return v;
} }
/** /**
* should return ?? for the passed in ?? * should return ?? for the passed in ??
* *
* @param qd * @param qd
* @return Variant results of query? * @return Variant results of query?
*/ */
public static Variant getByQueryDef(Dispatch qd) { public static Variant getByQueryDef(Dispatch qd) {
// get a reference to the recordset // get a reference to the recordset
Dispatch recset = Dispatch.call(qd, "OpenRecordset").toDispatch(); Dispatch recset = Dispatch.call(qd, "OpenRecordset").toDispatch();
// get the values as a safe array // get the values as a safe array
String[] cols = getColumns(recset); String[] cols = getColumns(recset);
for (int i = 0; i < cols.length; i++) { for (int i = 0; i < cols.length; i++) {
System.out.print(cols[i] + " "); System.out.print(cols[i] + " ");
} }
System.out.println(""); System.out.println("");
Variant vals = getValues(recset); Variant vals = getValues(recset);
return vals; return vals;
} }
/** /**
* gets the columns form the rec set * gets the columns form the rec set
* *
* @param recset * @param recset
* @return list of column names * @return list of column names
*/ */
public static String[] getColumns(Dispatch recset) { public static String[] getColumns(Dispatch recset) {
Dispatch flds = Dispatch.get(recset, "Fields").toDispatch(); Dispatch flds = Dispatch.get(recset, "Fields").toDispatch();
int n_flds = Dispatch.get(flds, "Count").getInt(); int n_flds = Dispatch.get(flds, "Count").getInt();
String[] s = new String[n_flds]; String[] s = new String[n_flds];
Variant vi = new Variant(); Variant vi = new Variant();
for (int i = 0; i < n_flds; i++) { for (int i = 0; i < n_flds; i++) {
vi.putInt(i); vi.putInt(i);
// must use the invoke method because this is a method call // must use the invoke method because this is a method call
// that wants to have a Dispatch.Get flag... // that wants to have a Dispatch.Get flag...
Dispatch fld = Dispatch.invoke(recset, "Fields", Dispatch.Get, Dispatch fld = Dispatch.invoke(recset, "Fields", Dispatch.Get,
new Object[] { vi }, new int[1]).toDispatch(); new Object[] { vi }, new int[1]).toDispatch();
Variant name = Dispatch.get(fld, "Name"); Variant name = Dispatch.get(fld, "Name");
s[i] = name.toString(); s[i] = name.toString();
} }
return s; return s;
} }
} }

View File

@@ -9,199 +9,199 @@ import com.jacob.com.Variant;
* *
*/ */
public class Command extends Dispatch { public class Command extends Dispatch {
/** /**
* standard constructor * standard constructor
*/ */
public Command() { public Command() {
super("ADODB.Command"); super("ADODB.Command");
} }
/** /**
* This constructor is used instead of a case operation to turn a Dispatch * This constructor is used instead of a case operation to turn a Dispatch
* object into a wider object - it must exist in every wrapper class whose * object into a wider object - it must exist in every wrapper class whose
* instances may be returned from method calls wrapped in VT_DISPATCH * instances may be returned from method calls wrapped in VT_DISPATCH
* Variants. * Variants.
* *
* @param dispatchTarget * @param dispatchTarget
*/ */
public Command(Dispatch dispatchTarget) { public Command(Dispatch dispatchTarget) {
super(dispatchTarget); super(dispatchTarget);
} }
/** /**
* runs the "Properties" command * runs the "Properties" command
* *
* @return the properties * @return the properties
*/ */
public Variant getProperties() { public Variant getProperties() {
return Dispatch.get(this, "Properties"); return Dispatch.get(this, "Properties");
} }
/** /**
* runs the "ActiveConnection" command * runs the "ActiveConnection" command
* *
* @return a Connection object * @return a Connection object
*/ */
public Connection getActiveConnection() { public Connection getActiveConnection() {
return new Connection(Dispatch.get(this, "ActiveConnection") return new Connection(Dispatch.get(this, "ActiveConnection")
.toDispatch()); .toDispatch());
} }
/** /**
* Sets the "ActiveConnection" object * Sets the "ActiveConnection" object
* *
* @param ppvObject * @param ppvObject
* the new connection * the new connection
*/ */
public void setActiveConnection(Connection ppvObject) { public void setActiveConnection(Connection ppvObject) {
Dispatch.put(this, "ActiveConnection", ppvObject); Dispatch.put(this, "ActiveConnection", ppvObject);
} }
/** /**
* *
* @return the results from "CommandText" * @return the results from "CommandText"
*/ */
public String getCommandText() { public String getCommandText() {
return Dispatch.get(this, "CommandText").toString(); return Dispatch.get(this, "CommandText").toString();
} }
/** /**
* *
* @param pbstr * @param pbstr
* the new "CommandText" * the new "CommandText"
*/ */
public void setCommandText(String pbstr) { public void setCommandText(String pbstr) {
Dispatch.put(this, "CommandText", pbstr); Dispatch.put(this, "CommandText", pbstr);
} }
/** /**
* *
* @return the results of "CommandTimeout" * @return the results of "CommandTimeout"
*/ */
public int getCommandTimeout() { public int getCommandTimeout() {
return Dispatch.get(this, "CommandTimeout").getInt(); return Dispatch.get(this, "CommandTimeout").getInt();
} }
/** /**
* *
* @param plTimeout * @param plTimeout
* the new "CommandTimeout" * the new "CommandTimeout"
*/ */
public void setCommandTimeout(int plTimeout) { public void setCommandTimeout(int plTimeout) {
Dispatch.put(this, "CommandTimeout", new Variant(plTimeout)); Dispatch.put(this, "CommandTimeout", new Variant(plTimeout));
} }
/** /**
* *
* @return results from "Prepared" * @return results from "Prepared"
*/ */
public boolean getPrepared() { public boolean getPrepared() {
return Dispatch.get(this, "Prepared").getBoolean(); return Dispatch.get(this, "Prepared").getBoolean();
} }
/** /**
* *
* @param pfPrepared * @param pfPrepared
* the new value for "Prepared" * the new value for "Prepared"
*/ */
public void setPrepared(boolean pfPrepared) { public void setPrepared(boolean pfPrepared) {
Dispatch.put(this, "Prepared", new Variant(pfPrepared)); Dispatch.put(this, "Prepared", new Variant(pfPrepared));
} }
/** /**
* "Execute"s a command * "Execute"s a command
* *
* @param RecordsAffected * @param RecordsAffected
* @param Parameters * @param Parameters
* @param Options * @param Options
* @return * @return
*/ */
public Recordset Execute(Variant RecordsAffected, Variant Parameters, public Recordset Execute(Variant RecordsAffected, Variant Parameters,
int Options) { int Options) {
return (Recordset) Dispatch.call(this, "Execute", RecordsAffected, return (Recordset) Dispatch.call(this, "Execute", RecordsAffected,
Parameters, new Variant(Options)).toDispatch(); Parameters, new Variant(Options)).toDispatch();
} }
/** /**
* "Execute"s a command * "Execute"s a command
* *
* @return * @return
*/ */
public Recordset Execute() { public Recordset Execute() {
Variant dummy = new Variant(); Variant dummy = new Variant();
return new Recordset(Dispatch.call(this, "Execute", dummy).toDispatch()); return new Recordset(Dispatch.call(this, "Execute", dummy).toDispatch());
} }
/** /**
* creates a parameter * creates a parameter
* *
* @param Name * @param Name
* @param Type * @param Type
* @param Direction * @param Direction
* @param Size * @param Size
* @param Value * @param Value
* @return * @return
*/ */
public Variant CreateParameter(String Name, int Type, int Direction, public Variant CreateParameter(String Name, int Type, int Direction,
int Size, Variant Value) { int Size, Variant Value) {
return Dispatch.call(this, "CreateParameter", Name, new Variant(Type), return Dispatch.call(this, "CreateParameter", Name, new Variant(Type),
new Variant(Direction), new Variant(Size), Value); new Variant(Direction), new Variant(Size), Value);
} }
// need to wrap Parameters // need to wrap Parameters
/** /**
* @return "Parameters" * @return "Parameters"
*/ */
public Variant getParameters() { public Variant getParameters() {
return Dispatch.get(this, "Parameters"); return Dispatch.get(this, "Parameters");
} }
/** /**
* *
* @param plCmdType * @param plCmdType
* new "CommandType" * new "CommandType"
*/ */
public void setCommandType(int plCmdType) { public void setCommandType(int plCmdType) {
Dispatch.put(this, "CommandType", new Variant(plCmdType)); Dispatch.put(this, "CommandType", new Variant(plCmdType));
} }
/** /**
* *
* @return current "CommandType" * @return current "CommandType"
*/ */
public int getCommandType() { public int getCommandType() {
return Dispatch.get(this, "CommandType").getInt(); return Dispatch.get(this, "CommandType").getInt();
} }
/** /**
* *
* @return "Name" * @return "Name"
*/ */
public String getName() { public String getName() {
return Dispatch.get(this, "Name").toString(); return Dispatch.get(this, "Name").toString();
} }
/** /**
* *
* @param pbstrName * @param pbstrName
* new "Name" * new "Name"
*/ */
public void setName(String pbstrName) { public void setName(String pbstrName) {
Dispatch.put(this, "Name", pbstrName); Dispatch.put(this, "Name", pbstrName);
} }
/** /**
* *
* @return curent "State" * @return curent "State"
*/ */
public int getState() { public int getState() {
return Dispatch.get(this, "State").getInt(); return Dispatch.get(this, "State").getInt();
} }
/** /**
* cancel whatever it is we're doing * cancel whatever it is we're doing
*/ */
public void Cancel() { public void Cancel() {
Dispatch.call(this, "Cancel"); Dispatch.call(this, "Cancel");
} }
} }

View File

@@ -3,11 +3,11 @@ package com.jacob.samples.ado;
// Enum: CommandTypeEnum // Enum: CommandTypeEnum
public interface CommandTypeEnum { public interface CommandTypeEnum {
public static final int adCmdUnspecified = -1; public static final int adCmdUnspecified = -1;
public static final int adCmdUnknown = 8; public static final int adCmdUnknown = 8;
public static final int adCmdText = 1; public static final int adCmdText = 1;
public static final int adCmdTable = 2; public static final int adCmdTable = 2;
public static final int adCmdStoredProc = 4; public static final int adCmdStoredProc = 4;
public static final int adCmdFile = 256; public static final int adCmdFile = 256;
public static final int adCmdTableDirect = 512; public static final int adCmdTableDirect = 512;
} }

View File

@@ -4,148 +4,148 @@ import com.jacob.com.Dispatch;
import com.jacob.com.Variant; import com.jacob.com.Variant;
public class Connection extends Dispatch { public class Connection extends Dispatch {
public Connection() { public Connection() {
super("ADODB.Connection"); super("ADODB.Connection");
} }
/** /**
* This constructor is used instead of a case operation to turn a Dispatch * This constructor is used instead of a case operation to turn a Dispatch
* object into a wider object - it must exist in every wrapper class whose * object into a wider object - it must exist in every wrapper class whose
* instances may be returned from method calls wrapped in VT_DISPATCH * instances may be returned from method calls wrapped in VT_DISPATCH
* Variants. * Variants.
*/ */
public Connection(Dispatch d) { public Connection(Dispatch d) {
super(d); super(d);
} }
// need to wrap Properties // need to wrap Properties
public Variant getProperties() { public Variant getProperties() {
return Dispatch.get(this, "Properties"); return Dispatch.get(this, "Properties");
} }
public String getConnectionString() { public String getConnectionString() {
return Dispatch.get(this, "ConnectionString").toString(); return Dispatch.get(this, "ConnectionString").toString();
} }
public void setConnectionString(String pbstr) { public void setConnectionString(String pbstr) {
Dispatch.put(this, "ConnectionString", pbstr); Dispatch.put(this, "ConnectionString", pbstr);
} }
public int getCommandTimeout() { public int getCommandTimeout() {
return Dispatch.get(this, "CommandTimeout").getInt(); return Dispatch.get(this, "CommandTimeout").getInt();
} }
public void setCommandTimeout(int plTimeout) { public void setCommandTimeout(int plTimeout) {
Dispatch.put(this, "CommandTimeout", new Variant(plTimeout)); Dispatch.put(this, "CommandTimeout", new Variant(plTimeout));
} }
public int getConnectionTimeout() { public int getConnectionTimeout() {
return Dispatch.get(this, "ConnectionTimeout").getInt(); return Dispatch.get(this, "ConnectionTimeout").getInt();
} }
public void setConnectionTimeout(int plTimeout) { public void setConnectionTimeout(int plTimeout) {
Dispatch.put(this, "ConnectionTimeout", new Variant(plTimeout)); Dispatch.put(this, "ConnectionTimeout", new Variant(plTimeout));
} }
public String getVersion() { public String getVersion() {
return Dispatch.get(this, "Version").toString(); return Dispatch.get(this, "Version").toString();
} }
public void Close() { public void Close() {
Dispatch.call(this, "Close"); Dispatch.call(this, "Close");
} }
// how to deal with RecordsAffected being output? // how to deal with RecordsAffected being output?
public Variant Execute(String CommandText, Variant RecordsAffected, public Variant Execute(String CommandText, Variant RecordsAffected,
int Options) { int Options) {
return Dispatch.call(this, CommandText, RecordsAffected, new Variant( return Dispatch.call(this, CommandText, RecordsAffected, new Variant(
Options)); Options));
} }
public int BeginTrans() { public int BeginTrans() {
return Dispatch.call(this, "BeginTrans").getInt(); return Dispatch.call(this, "BeginTrans").getInt();
} }
public void CommitTrans() { public void CommitTrans() {
Dispatch.call(this, "CommitTrans"); Dispatch.call(this, "CommitTrans");
} }
public void RollbackTrans() { public void RollbackTrans() {
Dispatch.call(this, "RollbackTrans"); Dispatch.call(this, "RollbackTrans");
} }
public void Open(String ConnectionString, String UserID, String Password, public void Open(String ConnectionString, String UserID, String Password,
int Options) { int Options) {
Dispatch.call(this, "Open", ConnectionString, UserID, Password, Dispatch.call(this, "Open", ConnectionString, UserID, Password,
new Variant(Options)); new Variant(Options));
} }
public void Open() { public void Open() {
Dispatch.call(this, "Open"); Dispatch.call(this, "Open");
} }
public Variant getErrors() { public Variant getErrors() {
return Dispatch.get(this, "Errors"); return Dispatch.get(this, "Errors");
} }
public String getDefaultDatabase() { public String getDefaultDatabase() {
return Dispatch.get(this, "DefaultDatabase").toString(); return Dispatch.get(this, "DefaultDatabase").toString();
} }
public void setDefaultDatabase(String pbstr) { public void setDefaultDatabase(String pbstr) {
Dispatch.put(this, "DefaultDatabase", pbstr); Dispatch.put(this, "DefaultDatabase", pbstr);
} }
public int getIsolationLevel() { public int getIsolationLevel() {
return Dispatch.get(this, "IsolationLevel").getInt(); return Dispatch.get(this, "IsolationLevel").getInt();
} }
public void setIsolationLevel(int Level) { public void setIsolationLevel(int Level) {
Dispatch.put(this, "IsolationLevel", new Variant(Level)); Dispatch.put(this, "IsolationLevel", new Variant(Level));
} }
public int getAttributes() { public int getAttributes() {
return Dispatch.get(this, "Attributes").getInt(); return Dispatch.get(this, "Attributes").getInt();
} }
public void setAttributes(int plAttr) { public void setAttributes(int plAttr) {
Dispatch.put(this, "Attributes", new Variant(plAttr)); Dispatch.put(this, "Attributes", new Variant(plAttr));
} }
public int getCursorLocation() { public int getCursorLocation() {
return Dispatch.get(this, "CursorLocation").getInt(); return Dispatch.get(this, "CursorLocation").getInt();
} }
public void setCursorLocation(int plCursorLoc) { public void setCursorLocation(int plCursorLoc) {
Dispatch.put(this, "CursorLocation", new Variant(plCursorLoc)); Dispatch.put(this, "CursorLocation", new Variant(plCursorLoc));
} }
public int getMode() { public int getMode() {
return Dispatch.get(this, "Mode").getInt(); return Dispatch.get(this, "Mode").getInt();
} }
public void setMode(int plMode) { public void setMode(int plMode) {
Dispatch.put(this, "Mode", new Variant(plMode)); Dispatch.put(this, "Mode", new Variant(plMode));
} }
public String getProvider() { public String getProvider() {
return Dispatch.get(this, "Provider").toString(); return Dispatch.get(this, "Provider").toString();
} }
public void setProvider(String pbstr) { public void setProvider(String pbstr) {
Dispatch.put(this, "Provider", pbstr); Dispatch.put(this, "Provider", pbstr);
} }
public int getState() { public int getState() {
return Dispatch.get(this, "State").getInt(); return Dispatch.get(this, "State").getInt();
} }
public Variant OpenSchema(int Schema, Variant Restrictions, Variant SchemaID) { public Variant OpenSchema(int Schema, Variant Restrictions, Variant SchemaID) {
return Dispatch.call(this, "OpenSchema", new Variant(Schema), return Dispatch.call(this, "OpenSchema", new Variant(Schema),
Restrictions, SchemaID); Restrictions, SchemaID);
} }
public void Cancel() { public void Cancel() {
Dispatch.call(this, "Cancel"); Dispatch.call(this, "Cancel");
} }
} }

View File

@@ -4,98 +4,98 @@ import com.jacob.com.Dispatch;
import com.jacob.com.Variant; import com.jacob.com.Variant;
public class Field extends Dispatch { public class Field extends Dispatch {
/** /**
* This constructor is used instead of a case operation to turn a Dispatch * This constructor is used instead of a case operation to turn a Dispatch
* object into a wider object - it must exist in every wrapper class whose * object into a wider object - it must exist in every wrapper class whose
* instances may be returned from method calls wrapped in VT_DISPATCH * instances may be returned from method calls wrapped in VT_DISPATCH
* Variants. * Variants.
*/ */
public Field(Dispatch d) { public Field(Dispatch d) {
super(d); super(d);
} }
public Variant getProperties() { public Variant getProperties() {
return Dispatch.get(this, "Properties"); return Dispatch.get(this, "Properties");
} }
public int getActualSize() { public int getActualSize() {
return Dispatch.get(this, "ActualSize").getInt(); return Dispatch.get(this, "ActualSize").getInt();
} }
public int getAttributes() { public int getAttributes() {
return Dispatch.get(this, "Attributes").getInt(); return Dispatch.get(this, "Attributes").getInt();
} }
public int getDefinedSize() { public int getDefinedSize() {
return Dispatch.get(this, "DefinedSize").getInt(); return Dispatch.get(this, "DefinedSize").getInt();
} }
public String getName() { public String getName() {
return Dispatch.get(this, "Name").toString(); return Dispatch.get(this, "Name").toString();
} }
public int getType() { public int getType() {
return Dispatch.get(this, "Type").getInt(); return Dispatch.get(this, "Type").getInt();
} }
public Variant getValue() { public Variant getValue() {
return Dispatch.get(this, "Value"); return Dispatch.get(this, "Value");
} }
public void setValue(Variant pvar) { public void setValue(Variant pvar) {
Dispatch.put(this, "Value", pvar); Dispatch.put(this, "Value", pvar);
} }
public byte getPrecision() { public byte getPrecision() {
return Dispatch.get(this, "Precision").getByte(); return Dispatch.get(this, "Precision").getByte();
} }
public byte getNumericScale() { public byte getNumericScale() {
return Dispatch.get(this, "NumericScale").getByte(); return Dispatch.get(this, "NumericScale").getByte();
} }
public void AppendChunk(Variant Data) { public void AppendChunk(Variant Data) {
Dispatch.call(this, "AppendChunk", Data); Dispatch.call(this, "AppendChunk", Data);
} }
public Variant GetChunk(int Length) { public Variant GetChunk(int Length) {
return Dispatch.call(this, "GetChunk", new Variant(Length)); return Dispatch.call(this, "GetChunk", new Variant(Length));
} }
public Variant getOriginalValue() { public Variant getOriginalValue() {
return Dispatch.get(this, "OriginalValue"); return Dispatch.get(this, "OriginalValue");
} }
public Variant getUnderlyingValue() { public Variant getUnderlyingValue() {
return Dispatch.get(this, "UnderlyingValue"); return Dispatch.get(this, "UnderlyingValue");
} }
public Variant getDataFormat() { public Variant getDataFormat() {
return Dispatch.get(this, "DataFormat"); return Dispatch.get(this, "DataFormat");
} }
public void setDataFormat(Variant ppiDF) { public void setDataFormat(Variant ppiDF) {
Dispatch.put(this, "DataFormat", ppiDF); Dispatch.put(this, "DataFormat", ppiDF);
} }
public void setPrecision(byte pb) { public void setPrecision(byte pb) {
Dispatch.put(this, "Precision", new Variant(pb)); Dispatch.put(this, "Precision", new Variant(pb));
} }
public void setNumericScale(byte pb) { public void setNumericScale(byte pb) {
Dispatch.put(this, "NumericScale", new Variant(pb)); Dispatch.put(this, "NumericScale", new Variant(pb));
} }
public void setType(int pDataType) { public void setType(int pDataType) {
Dispatch.put(this, "Type", new Variant(pDataType)); Dispatch.put(this, "Type", new Variant(pDataType));
} }
public void setDefinedSize(int pl) { public void setDefinedSize(int pl) {
Dispatch.put(this, "DefinedSize", new Variant(pl)); Dispatch.put(this, "DefinedSize", new Variant(pl));
} }
public void setAttributes(int pl) { public void setAttributes(int pl) {
Dispatch.put(this, "Attributes", new Variant(pl)); Dispatch.put(this, "Attributes", new Variant(pl));
} }
} }

View File

@@ -4,40 +4,40 @@ import com.jacob.com.Dispatch;
import com.jacob.com.Variant; import com.jacob.com.Variant;
public class Fields extends Dispatch { public class Fields extends Dispatch {
/** /**
* This constructor is used instead of a case operation to turn a Dispatch * This constructor is used instead of a case operation to turn a Dispatch
* object into a wider object - it must exist in every wrapper class whose * object into a wider object - it must exist in every wrapper class whose
* instances may be returned from method calls wrapped in VT_DISPATCH * instances may be returned from method calls wrapped in VT_DISPATCH
* Variants. * Variants.
*/ */
public Fields(Dispatch d) { public Fields(Dispatch d) {
super(d); super(d);
} }
public int getCount() { public int getCount() {
return Dispatch.get(this, "Count").getInt(); return Dispatch.get(this, "Count").getInt();
} }
public Variant _NewEnum() { public Variant _NewEnum() {
return Dispatch.call(this, "_NewEnum"); return Dispatch.call(this, "_NewEnum");
} }
public void Refresh() { public void Refresh() {
Dispatch.call(this, "Refresh"); Dispatch.call(this, "Refresh");
} }
public Field getItem(int Index) { public Field getItem(int Index) {
return new Field(Dispatch.call(this, "Item", new Variant(Index)) return new Field(Dispatch.call(this, "Item", new Variant(Index))
.toDispatch()); .toDispatch());
} }
public void Append(String Name, int Type, int DefinedSize, int Attrib) { public void Append(String Name, int Type, int DefinedSize, int Attrib) {
Dispatch.call(this, "Append", Name, new Variant(Type), new Variant( Dispatch.call(this, "Append", Name, new Variant(Type), new Variant(
DefinedSize), new Variant(Attrib)); DefinedSize), new Variant(Attrib));
} }
public void Delete(Variant Index) { public void Delete(Variant Index) {
Dispatch.call(this, "Delete", Index); Dispatch.call(this, "Delete", Index);
} }
} }

View File

@@ -4,339 +4,339 @@ import com.jacob.com.Dispatch;
import com.jacob.com.Variant; import com.jacob.com.Variant;
public class Recordset extends Dispatch { public class Recordset extends Dispatch {
public Recordset() { public Recordset() {
super("ADODB.Recordset"); super("ADODB.Recordset");
} }
/** /**
* This constructor is used instead of a case operation to turn a Dispatch * This constructor is used instead of a case operation to turn a Dispatch
* object into a wider object - it must exist in every wrapper class whose * object into a wider object - it must exist in every wrapper class whose
* instances may be returned from method calls wrapped in VT_DISPATCH * instances may be returned from method calls wrapped in VT_DISPATCH
* Variants. * Variants.
*/ */
public Recordset(Dispatch d) { public Recordset(Dispatch d) {
super(d); super(d);
} }
public Variant getProperties() { public Variant getProperties() {
return Dispatch.get(this, "Properties"); return Dispatch.get(this, "Properties");
} }
public int getAbsolutePosition() { public int getAbsolutePosition() {
return Dispatch.get(this, "AbsolutePosition").getInt(); return Dispatch.get(this, "AbsolutePosition").getInt();
} }
public void setAbsolutePosition(int pl) { public void setAbsolutePosition(int pl) {
Dispatch.put(this, "AbsolutePosition", new Variant(pl)); Dispatch.put(this, "AbsolutePosition", new Variant(pl));
} }
public Connection getActiveConnection() { public Connection getActiveConnection() {
return new Connection(Dispatch.get(this, "ActiveConnection") return new Connection(Dispatch.get(this, "ActiveConnection")
.toDispatch()); .toDispatch());
} }
public void setActiveConnection(Connection ppvObject) { public void setActiveConnection(Connection ppvObject) {
Dispatch.put(this, "ActiveConnection", ppvObject); Dispatch.put(this, "ActiveConnection", ppvObject);
} }
public void setActiveConnection(Variant ppvObject) { public void setActiveConnection(Variant ppvObject) {
Dispatch.put(this, "ActiveConnection", ppvObject); Dispatch.put(this, "ActiveConnection", ppvObject);
} }
public boolean getBOF() { public boolean getBOF() {
return Dispatch.get(this, "BOF").getBoolean(); return Dispatch.get(this, "BOF").getBoolean();
} }
public Variant getBookmark() { public Variant getBookmark() {
return Dispatch.get(this, "Bookmark"); return Dispatch.get(this, "Bookmark");
} }
public void setBookmark(Variant pvBookmark) { public void setBookmark(Variant pvBookmark) {
Dispatch.put(this, "Bookmark", pvBookmark); Dispatch.put(this, "Bookmark", pvBookmark);
} }
public int getCacheSize() { public int getCacheSize() {
return Dispatch.get(this, "CacheSize").getInt(); return Dispatch.get(this, "CacheSize").getInt();
} }
public void setCacheSize(int pl) { public void setCacheSize(int pl) {
Dispatch.put(this, "CacheSize", new Variant(pl)); Dispatch.put(this, "CacheSize", new Variant(pl));
} }
public int getCursorType() { public int getCursorType() {
return Dispatch.get(this, "CursorType").getInt(); return Dispatch.get(this, "CursorType").getInt();
} }
public void setCursorType(int pl) { public void setCursorType(int pl) {
Dispatch.put(this, "CursorType", new Variant(pl)); Dispatch.put(this, "CursorType", new Variant(pl));
} }
public boolean getEOF() { public boolean getEOF() {
return Dispatch.get(this, "EOF").getBoolean(); return Dispatch.get(this, "EOF").getBoolean();
} }
public Fields getFields() { public Fields getFields() {
return new Fields(Dispatch.get(this, "Fields").toDispatch()); return new Fields(Dispatch.get(this, "Fields").toDispatch());
} }
public int getLockType() { public int getLockType() {
return Dispatch.get(this, "LockType").getInt(); return Dispatch.get(this, "LockType").getInt();
} }
public void setLockType(int plLockType) { public void setLockType(int plLockType) {
Dispatch.put(this, "LockType", new Variant(plLockType)); Dispatch.put(this, "LockType", new Variant(plLockType));
} }
public int getMaxRecords() { public int getMaxRecords() {
return Dispatch.get(this, "MaxRecords").getInt(); return Dispatch.get(this, "MaxRecords").getInt();
} }
public void setMaxRecords(int pl) { public void setMaxRecords(int pl) {
Dispatch.put(this, "MaxRecords", new Variant(pl)); Dispatch.put(this, "MaxRecords", new Variant(pl));
} }
public int getRecordCount() { public int getRecordCount() {
return Dispatch.get(this, "RecordCount").getInt(); return Dispatch.get(this, "RecordCount").getInt();
} }
public void setSource(Object pvSource) { public void setSource(Object pvSource) {
Dispatch.put(this, "Source", pvSource); Dispatch.put(this, "Source", pvSource);
} }
public void setSource(String pvSource) { public void setSource(String pvSource) {
Dispatch.put(this, "Source", pvSource); Dispatch.put(this, "Source", pvSource);
} }
public Variant getSource() { public Variant getSource() {
return Dispatch.get(this, "Source"); return Dispatch.get(this, "Source");
} }
public void AddNew(Variant FieldList, Variant Values) { public void AddNew(Variant FieldList, Variant Values) {
Dispatch.call(this, "AddNew", FieldList, Values); Dispatch.call(this, "AddNew", FieldList, Values);
} }
public void CancelUpdate() { public void CancelUpdate() {
Dispatch.call(this, "CancelUpdate"); Dispatch.call(this, "CancelUpdate");
} }
public void Close() { public void Close() {
Dispatch.call(this, "Close"); Dispatch.call(this, "Close");
} }
public void Delete(int AffectRecords) { public void Delete(int AffectRecords) {
Dispatch.call(this, "Delete", new Variant(AffectRecords)); Dispatch.call(this, "Delete", new Variant(AffectRecords));
} }
public Variant GetRows(int Rows, Variant Start, Variant Fields) { public Variant GetRows(int Rows, Variant Start, Variant Fields) {
return Dispatch.call(this, "GetRows", new Variant(Rows), Start, Fields); return Dispatch.call(this, "GetRows", new Variant(Rows), Start, Fields);
} }
// get all rows // get all rows
public Variant GetRows() { public Variant GetRows() {
return Dispatch.call(this, "GetRows"); return Dispatch.call(this, "GetRows");
} }
public void Move(int NumRecords, Variant Start) { public void Move(int NumRecords, Variant Start) {
Dispatch.call(this, "Move", new Variant(NumRecords), Start); Dispatch.call(this, "Move", new Variant(NumRecords), Start);
} }
public void MoveNext() { public void MoveNext() {
Dispatch.call(this, "MoveNext"); Dispatch.call(this, "MoveNext");
} }
public void MovePrevious() { public void MovePrevious() {
Dispatch.call(this, "MovePrevious"); Dispatch.call(this, "MovePrevious");
} }
public void MoveFirst() { public void MoveFirst() {
Dispatch.call(this, "MoveFirst"); Dispatch.call(this, "MoveFirst");
} }
public void MoveLast() { public void MoveLast() {
Dispatch.call(this, "MoveLast"); Dispatch.call(this, "MoveLast");
} }
public void Open(Variant Source, Variant ActiveConnection, int CursorType, public void Open(Variant Source, Variant ActiveConnection, int CursorType,
int LockType, int Options) { int LockType, int Options) {
Dispatch.call(this, "Open", Source, ActiveConnection, new Variant( Dispatch.call(this, "Open", Source, ActiveConnection, new Variant(
CursorType), new Variant(LockType), new Variant(Options)); CursorType), new Variant(LockType), new Variant(Options));
} }
public void Open(Variant Source, Variant ActiveConnection) { public void Open(Variant Source, Variant ActiveConnection) {
Dispatch.call(this, "Open", Source, ActiveConnection); Dispatch.call(this, "Open", Source, ActiveConnection);
} }
public void Requery(int Options) { public void Requery(int Options) {
Dispatch.call(this, "Requery", new Variant(Options)); Dispatch.call(this, "Requery", new Variant(Options));
} }
public void Update(Variant Fields, Variant Values) { public void Update(Variant Fields, Variant Values) {
Dispatch.call(this, "Update", Fields, Values); Dispatch.call(this, "Update", Fields, Values);
} }
public int getAbsolutePage() { public int getAbsolutePage() {
return Dispatch.get(this, "AbsolutePage").getInt(); return Dispatch.get(this, "AbsolutePage").getInt();
} }
public void setAbsolutePage(int pl) { public void setAbsolutePage(int pl) {
Dispatch.put(this, "AbsolutePage", new Variant(pl)); Dispatch.put(this, "AbsolutePage", new Variant(pl));
} }
public int getEditMode() { public int getEditMode() {
return Dispatch.get(this, "EditMode").getInt(); return Dispatch.get(this, "EditMode").getInt();
} }
public Variant getFilter() { public Variant getFilter() {
return Dispatch.get(this, "Filter"); return Dispatch.get(this, "Filter");
} }
public void setFilter(Variant Criteria) { public void setFilter(Variant Criteria) {
Dispatch.put(this, "Filter", Criteria); Dispatch.put(this, "Filter", Criteria);
} }
public int getPageCount() { public int getPageCount() {
return Dispatch.get(this, "PageCount").getInt(); return Dispatch.get(this, "PageCount").getInt();
} }
public int getPageSize() { public int getPageSize() {
return Dispatch.get(this, "PageSize").getInt(); return Dispatch.get(this, "PageSize").getInt();
} }
public void setPageSize(int pl) { public void setPageSize(int pl) {
Dispatch.put(this, "PageSize", new Variant(pl)); Dispatch.put(this, "PageSize", new Variant(pl));
} }
public String getSort() { public String getSort() {
return Dispatch.get(this, "Sort").toString(); return Dispatch.get(this, "Sort").toString();
} }
public void setSort(String Criteria) { public void setSort(String Criteria) {
Dispatch.put(this, "Sort", Criteria); Dispatch.put(this, "Sort", Criteria);
} }
public int getStatus() { public int getStatus() {
return Dispatch.get(this, "Status").getInt(); return Dispatch.get(this, "Status").getInt();
} }
public int getState() { public int getState() {
return Dispatch.get(this, "State").getInt(); return Dispatch.get(this, "State").getInt();
} }
public void UpdateBatch(int AffectRecords) { public void UpdateBatch(int AffectRecords) {
Dispatch.call(this, "UpdateBatch", new Variant(AffectRecords)); Dispatch.call(this, "UpdateBatch", new Variant(AffectRecords));
} }
public void CancelBatch(int AffectRecords) { public void CancelBatch(int AffectRecords) {
Dispatch.call(this, "CancelBatch", new Variant(AffectRecords)); Dispatch.call(this, "CancelBatch", new Variant(AffectRecords));
} }
public int getCursorLocation() { public int getCursorLocation() {
return Dispatch.get(this, "CursorLocation").getInt(); return Dispatch.get(this, "CursorLocation").getInt();
} }
public void setCursorLocation(int pl) { public void setCursorLocation(int pl) {
Dispatch.put(this, "CursorLocation", new Variant(pl)); Dispatch.put(this, "CursorLocation", new Variant(pl));
} }
public Recordset NextRecordset(Variant RecordsAffected) { public Recordset NextRecordset(Variant RecordsAffected) {
return new Recordset(Dispatch.call(this, "NextRecordset", return new Recordset(Dispatch.call(this, "NextRecordset",
RecordsAffected).toDispatch()); RecordsAffected).toDispatch());
} }
public boolean Supports(int CursorOptions) { public boolean Supports(int CursorOptions) {
return Dispatch.call(this, "Supports", new Variant(CursorOptions)) return Dispatch.call(this, "Supports", new Variant(CursorOptions))
.getBoolean(); .getBoolean();
} }
public Variant getCollect(Variant Index) { public Variant getCollect(Variant Index) {
return Dispatch.get(this, "Collect"); return Dispatch.get(this, "Collect");
} }
public void setCollect(Variant Index, Variant pvar) { public void setCollect(Variant Index, Variant pvar) {
Dispatch.call(this, "Collect", Index, pvar); Dispatch.call(this, "Collect", Index, pvar);
} }
public int getMarshalOptions() { public int getMarshalOptions() {
return Dispatch.get(this, "MarshalOptions").getInt(); return Dispatch.get(this, "MarshalOptions").getInt();
} }
public void setMarshalOptions(int pl) { public void setMarshalOptions(int pl) {
Dispatch.put(this, "MarshalOptions", new Variant(pl)); Dispatch.put(this, "MarshalOptions", new Variant(pl));
} }
public void Find(String Criteria, int SkipRecords, int SearchDirection, public void Find(String Criteria, int SkipRecords, int SearchDirection,
Variant Start) { Variant Start) {
Dispatch.call(this, "Find", Criteria, new Variant(SkipRecords), Dispatch.call(this, "Find", Criteria, new Variant(SkipRecords),
new Variant(SearchDirection), Start); new Variant(SearchDirection), Start);
} }
public void Cancel() { public void Cancel() {
Dispatch.call(this, "Cancel"); Dispatch.call(this, "Cancel");
} }
public Variant getDataSource() { public Variant getDataSource() {
return Dispatch.get(this, "DataSource"); return Dispatch.get(this, "DataSource");
} }
public void setDataSource(Variant ppunkDataSource) { public void setDataSource(Variant ppunkDataSource) {
Dispatch.put(this, "DataSource", ppunkDataSource); Dispatch.put(this, "DataSource", ppunkDataSource);
} }
public void Save(String FileName, int PersistFormat) { public void Save(String FileName, int PersistFormat) {
Dispatch.call(this, "Save", FileName, new Variant(PersistFormat)); Dispatch.call(this, "Save", FileName, new Variant(PersistFormat));
} }
public Variant getActiveCommand() { public Variant getActiveCommand() {
return Dispatch.get(this, "ActiveCommand"); return Dispatch.get(this, "ActiveCommand");
} }
public void setStayInSync(boolean pb) { public void setStayInSync(boolean pb) {
Dispatch.put(this, "StayInSync", new Variant(pb)); Dispatch.put(this, "StayInSync", new Variant(pb));
} }
public boolean getStayInSync() { public boolean getStayInSync() {
return Dispatch.get(this, "StayInSync").getBoolean(); return Dispatch.get(this, "StayInSync").getBoolean();
} }
public String GetString(int StringFormat, int NumRows, public String GetString(int StringFormat, int NumRows,
String ColumnDelimeter, String RowDelimeter, String NullExpr) { String ColumnDelimeter, String RowDelimeter, String NullExpr) {
return Dispatch.call(this, "GetString", new Variant(StringFormat), return Dispatch.call(this, "GetString", new Variant(StringFormat),
new Variant(NumRows), ColumnDelimeter, RowDelimeter, NullExpr) new Variant(NumRows), ColumnDelimeter, RowDelimeter, NullExpr)
.toString(); .toString();
} }
public String getDataMember() { public String getDataMember() {
return Dispatch.get(this, "DataMember").toString(); return Dispatch.get(this, "DataMember").toString();
} }
public void setDataMember(String pl) { public void setDataMember(String pl) {
Dispatch.put(this, "DataMember", new Variant(pl)); Dispatch.put(this, "DataMember", new Variant(pl));
} }
public int CompareBookmarks(Variant Bookmark1, Variant Bookmark2) { public int CompareBookmarks(Variant Bookmark1, Variant Bookmark2) {
return Dispatch.call(this, "CompareBookmarks", Bookmark1, Bookmark2) return Dispatch.call(this, "CompareBookmarks", Bookmark1, Bookmark2)
.getInt(); .getInt();
} }
public Recordset Clone(int LockType) { public Recordset Clone(int LockType) {
return new Recordset(Dispatch return new Recordset(Dispatch
.call(this, "Clone", new Variant(LockType)).toDispatch()); .call(this, "Clone", new Variant(LockType)).toDispatch());
} }
public void Resync(int AffectRecords, int ResyncValues) { public void Resync(int AffectRecords, int ResyncValues) {
Dispatch.call(this, "Resync", new Variant(AffectRecords), new Variant( Dispatch.call(this, "Resync", new Variant(AffectRecords), new Variant(
ResyncValues)); ResyncValues));
} }
public void Seek(Variant KeyValues, int SeekOption) { public void Seek(Variant KeyValues, int SeekOption) {
Dispatch.call(this, "Seek", KeyValues, new Variant(SeekOption)); Dispatch.call(this, "Seek", KeyValues, new Variant(SeekOption));
} }
public void setIndex(String pl) { public void setIndex(String pl) {
Dispatch.put(this, "Index", new Variant(pl)); Dispatch.put(this, "Index", new Variant(pl));
} }
public String getIndex() { public String getIndex() {
return Dispatch.get(this, "Index)").toString(); return Dispatch.get(this, "Index)").toString();
} }
} }

View File

@@ -3,54 +3,54 @@ package com.jacob.samples.ado;
import com.jacob.com.Variant; import com.jacob.com.Variant;
public class test { public class test {
public static void printRS(Recordset rs) { public static void printRS(Recordset rs) {
Fields fs = rs.getFields(); Fields fs = rs.getFields();
for (int i = 0; i < fs.getCount(); i++) { for (int i = 0; i < fs.getCount(); i++) {
System.out.print(fs.getItem(i).getName() + " "); System.out.print(fs.getItem(i).getName() + " ");
} }
System.out.println(""); System.out.println("");
rs.MoveFirst(); rs.MoveFirst();
while (!rs.getEOF()) { while (!rs.getEOF()) {
for (int i = 0; i < fs.getCount(); i++) { for (int i = 0; i < fs.getCount(); i++) {
Field f = fs.getItem(i); Field f = fs.getItem(i);
Variant v = f.getValue(); Variant v = f.getValue();
System.out.print(v + " "); System.out.print(v + " ");
} }
System.out.println(""); System.out.println("");
rs.MoveNext(); rs.MoveNext();
} }
} }
// open a recordset directly // open a recordset directly
public static void getRS(String con, String query) { public static void getRS(String con, String query) {
System.out.println("Recordset Open"); System.out.println("Recordset Open");
Recordset rs = new Recordset(); Recordset rs = new Recordset();
rs.Open(new Variant(query), new Variant(con)); rs.Open(new Variant(query), new Variant(con));
printRS(rs); printRS(rs);
} }
// create connection and command objects and use them // create connection and command objects and use them
// to get a recordset // to get a recordset
public static void getCommand(String con, String query) { public static void getCommand(String con, String query) {
System.out.println("Command+Connection -> Recordset"); System.out.println("Command+Connection -> Recordset");
Connection c = new Connection(); Connection c = new Connection();
c.setConnectionString(con); c.setConnectionString(con);
c.Open(); c.Open();
Command comm = new Command(); Command comm = new Command();
comm.setActiveConnection(c); comm.setActiveConnection(c);
comm.setCommandType(CommandTypeEnum.adCmdText); comm.setCommandType(CommandTypeEnum.adCmdText);
comm.setCommandText(query); comm.setCommandText(query);
Recordset rs = comm.Execute(); Recordset rs = comm.Execute();
printRS(rs); printRS(rs);
c.Close(); c.Close();
} }
public static void main(String[] args) { public static void main(String[] args) {
String connectStr = "DRIVER=SQL Server;SERVER=DANADLER;UID=sa;PWD=;WSID=DANADLER;DATABASE=pubs"; String connectStr = "DRIVER=SQL Server;SERVER=DANADLER;UID=sa;PWD=;WSID=DANADLER;DATABASE=pubs";
String queryStr = "select * from authors"; String queryStr = "select * from authors";
getCommand(connectStr, queryStr); getCommand(connectStr, queryStr);
getRS(connectStr, queryStr); getRS(connectStr, queryStr);
} }
} }

View File

@@ -26,63 +26,63 @@ import com.jacob.com.Variant;
public class JacobTestApplet extends Applet implements ActionListener { public class JacobTestApplet extends Applet implements ActionListener {
private static final long serialVersionUID = 4492492907986849158L; private static final long serialVersionUID = 4492492907986849158L;
TextField in; TextField in;
TextField out; TextField out;
Button calc; Button calc;
ActiveXComponent sC = null; ActiveXComponent sC = null;
/** /**
* startup method * startup method
*/ */
@Override @Override
public void init() { public void init() {
setLayout(new FlowLayout()); setLayout(new FlowLayout());
add(this.in = new TextField("1+1", 16)); add(this.in = new TextField("1+1", 16));
add(this.out = new TextField("?", 16)); add(this.out = new TextField("?", 16));
add(this.calc = new Button("Calculate")); add(this.calc = new Button("Calculate"));
this.calc.addActionListener(this); this.calc.addActionListener(this);
} }
/** /**
* Returns information about this applet. * Returns information about this applet.
* According to the java spec: * According to the java spec:
* "An applet should override this method to return a String containing information about the author, version, and copyright of the applet." * "An applet should override this method to return a String containing information about the author, version, and copyright of the applet."
* *
* @return information about the applet. * @return information about the applet.
*/ */
@Override @Override
public String getAppletInfo() { public String getAppletInfo() {
return "Jacob Test Applet. Written by ttreeck, nepatec GmbH & Co. KG.\nhttp://www.nepatec.de"; return "Jacob Test Applet. Written by ttreeck, nepatec GmbH & Co. KG.\nhttp://www.nepatec.de";
} }
/** /**
* Returns information about the parameters that are understood by this applet. * Returns information about the parameters that are understood by this applet.
* According to the java spec: * According to the java spec:
* "An applet should override this method to return an array of Strings describing these parameters." * "An applet should override this method to return an array of Strings describing these parameters."
* *
* @return array with a set of three Strings containing the name, the type, and a description. * @return array with a set of three Strings containing the name, the type, and a description.
*/ */
@Override @Override
public String[][] getParameterInfo(){ public String[][] getParameterInfo(){
return new String[][]{}; return new String[][]{};
} }
/** /**
* action method that receives button actions * action method that receives button actions
* *
* @param ev the event * @param ev the event
*/ */
public void actionPerformed(ActionEvent ev) { public void actionPerformed(ActionEvent ev) {
if (this.sC == null) { if (this.sC == null) {
String lang = "VBScript"; String lang = "VBScript";
this.sC = new ActiveXComponent("ScriptControl"); this.sC = new ActiveXComponent("ScriptControl");
Dispatch.put(this.sC, "Language", lang); Dispatch.put(this.sC, "Language", lang);
} }
Variant v = Dispatch.call(this.sC, "Eval", this.in.getText()); Variant v = Dispatch.call(this.sC, "Eval", this.in.getText());
this.out.setText(v.toString()); this.out.setText(v.toString());
} }
} }

View File

@@ -9,59 +9,59 @@
STDMETHODIMP Face::InterfaceSupportsErrorInfo(REFIID riid) STDMETHODIMP Face::InterfaceSupportsErrorInfo(REFIID riid)
{ {
static const IID* arr[] = static const IID* arr[] =
{ {
&IID_IFace1, &IID_IFace1,
&IID_IFace2, &IID_IFace2,
&IID_IFace3, &IID_IFace3,
}; };
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++) for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{ {
if (InlineIsEqualGUID(*arr[i],riid)) if (InlineIsEqualGUID(*arr[i],riid))
return S_OK; return S_OK;
} }
return S_FALSE; return S_FALSE;
} }
STDMETHODIMP Face::get_Face1Name(BSTR *pVal) STDMETHODIMP Face::get_Face1Name(BSTR *pVal)
{ {
// TODO: Add your implementation code here // TODO: Add your implementation code here
*pVal = name1; *pVal = name1;
return S_OK; return S_OK;
} }
STDMETHODIMP Face::put_Face1Name(BSTR newVal) STDMETHODIMP Face::put_Face1Name(BSTR newVal)
{ {
// TODO: Add your implementation code here // TODO: Add your implementation code here
name1 = newVal; name1 = newVal;
return S_OK; return S_OK;
} }
STDMETHODIMP Face::get_Face2Nam(BSTR *pVal) STDMETHODIMP Face::get_Face2Nam(BSTR *pVal)
{ {
// TODO: Add your implementation code here // TODO: Add your implementation code here
*pVal = name2; *pVal = name2;
return S_OK; return S_OK;
} }
STDMETHODIMP Face::put_Face2Nam(BSTR newVal) STDMETHODIMP Face::put_Face2Nam(BSTR newVal)
{ {
// TODO: Add your implementation code here // TODO: Add your implementation code here
name2 = newVal; name2 = newVal;
return S_OK; return S_OK;
} }
STDMETHODIMP Face::get_Face3Name(BSTR *pVal) STDMETHODIMP Face::get_Face3Name(BSTR *pVal)
{ {
// TODO: Add your implementation code here // TODO: Add your implementation code here
*pVal = name3; *pVal = name3;
return S_OK; return S_OK;
} }
STDMETHODIMP Face::put_Face3Name(BSTR newVal) STDMETHODIMP Face::put_Face3Name(BSTR newVal)
{ {
// TODO: Add your implementation code here // TODO: Add your implementation code here
name3 = newVal; name3 = newVal;
return S_OK; return S_OK;
} }

View File

@@ -15,31 +15,31 @@
// Face // Face
class Face : class Face :
public IDispatchImpl<IFace1, &IID_IFace1, &LIBID_MULTIFACELib>, public IDispatchImpl<IFace1, &IID_IFace1, &LIBID_MULTIFACELib>,
public IDispatchImpl<IFace2, &IID_IFace2, &LIBID_MULTIFACELib>, public IDispatchImpl<IFace2, &IID_IFace2, &LIBID_MULTIFACELib>,
public IDispatchImpl<IFace3, &IID_IFace3, &LIBID_MULTIFACELib>, public IDispatchImpl<IFace3, &IID_IFace3, &LIBID_MULTIFACELib>,
public ISupportErrorInfo, public ISupportErrorInfo,
public CComObjectRoot, public CComObjectRoot,
public CComCoClass<Face,&CLSID_Face> public CComCoClass<Face,&CLSID_Face>
{ {
// IFace1 // IFace1
private: private:
CComBSTR name1; CComBSTR name1;
// IFace2 // IFace2
CComBSTR name2; CComBSTR name2;
// IFace3 // IFace3
CComBSTR name3; CComBSTR name3;
public: public:
Face() {} Face() {}
BEGIN_COM_MAP(Face) BEGIN_COM_MAP(Face)
COM_INTERFACE_ENTRY2(IDispatch, IFace1) COM_INTERFACE_ENTRY2(IDispatch, IFace1)
COM_INTERFACE_ENTRY(IFace1) COM_INTERFACE_ENTRY(IFace1)
COM_INTERFACE_ENTRY(IFace2) COM_INTERFACE_ENTRY(IFace2)
COM_INTERFACE_ENTRY(IFace3) COM_INTERFACE_ENTRY(IFace3)
COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY(ISupportErrorInfo)
END_COM_MAP() END_COM_MAP()
//DECLARE_NOT_AGGREGATABLE(Face) //DECLARE_NOT_AGGREGATABLE(Face)
// Remove the comment from the line above if you don't want your object to // Remove the comment from the line above if you don't want your object to
@@ -47,17 +47,17 @@ END_COM_MAP()
DECLARE_REGISTRY_RESOURCEID(IDR_Face) DECLARE_REGISTRY_RESOURCEID(IDR_Face)
// ISupportsErrorInfo // ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
public: public:
STDMETHOD(get_Face3Name)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_Face3Name)(/*[out, retval]*/ BSTR *pVal);
STDMETHOD(put_Face3Name)(/*[in]*/ BSTR newVal); STDMETHOD(put_Face3Name)(/*[in]*/ BSTR newVal);
STDMETHOD(get_Face2Nam)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_Face2Nam)(/*[out, retval]*/ BSTR *pVal);
STDMETHOD(put_Face2Nam)(/*[in]*/ BSTR newVal); STDMETHOD(put_Face2Nam)(/*[in]*/ BSTR newVal);
STDMETHOD(get_Face1Name)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_Face1Name)(/*[out, retval]*/ BSTR *pVal);
STDMETHOD(put_Face1Name)(/*[in]*/ BSTR newVal); STDMETHOD(put_Face1Name)(/*[in]*/ BSTR newVal);
}; };
#endif // !defined(AFX_FACE_H__9BF24413_B2E0_11D4_A695_00104BFF3241__INCLUDED_) #endif // !defined(AFX_FACE_H__9BF24413_B2E0_11D4_A695_00104BFF3241__INCLUDED_)

View File

@@ -40,19 +40,19 @@ extern "C"{
#ifndef __IFace1_FWD_DEFINED__ #ifndef __IFace1_FWD_DEFINED__
#define __IFace1_FWD_DEFINED__ #define __IFace1_FWD_DEFINED__
typedef interface IFace1 IFace1; typedef interface IFace1 IFace1;
#endif /* __IFace1_FWD_DEFINED__ */ #endif /* __IFace1_FWD_DEFINED__ */
#ifndef __IFace2_FWD_DEFINED__ #ifndef __IFace2_FWD_DEFINED__
#define __IFace2_FWD_DEFINED__ #define __IFace2_FWD_DEFINED__
typedef interface IFace2 IFace2; typedef interface IFace2 IFace2;
#endif /* __IFace2_FWD_DEFINED__ */ #endif /* __IFace2_FWD_DEFINED__ */
#ifndef __IFace3_FWD_DEFINED__ #ifndef __IFace3_FWD_DEFINED__
#define __IFace3_FWD_DEFINED__ #define __IFace3_FWD_DEFINED__
typedef interface IFace3 IFace3; typedef interface IFace3 IFace3;
#endif /* __IFace3_FWD_DEFINED__ */ #endif /* __IFace3_FWD_DEFINED__ */
#ifndef __Face_FWD_DEFINED__ #ifndef __Face_FWD_DEFINED__
@@ -64,7 +64,7 @@ typedef class Face Face;
typedef struct Face Face; typedef struct Face Face;
#endif /* __cplusplus */ #endif /* __cplusplus */
#endif /* __Face_FWD_DEFINED__ */ #endif /* __Face_FWD_DEFINED__ */
/* header files for imported files */ /* header files for imported files */
@@ -97,7 +97,7 @@ EXTERN_C const IID IID_IFace1;
}; };
#else /* C style interface */ #else /* C style interface */
typedef struct IFace1Vtbl typedef struct IFace1Vtbl
{ {
@@ -164,39 +164,39 @@ EXTERN_C const IID IID_IFace1;
#ifdef COBJMACROS #ifdef COBJMACROS
#define IFace1_QueryInterface(This,riid,ppvObject) \ #define IFace1_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject) (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IFace1_AddRef(This) \ #define IFace1_AddRef(This) \
(This)->lpVtbl -> AddRef(This) (This)->lpVtbl -> AddRef(This)
#define IFace1_Release(This) \ #define IFace1_Release(This) \
(This)->lpVtbl -> Release(This) (This)->lpVtbl -> Release(This)
#define IFace1_GetTypeInfoCount(This,pctinfo) \ #define IFace1_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define IFace1_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ #define IFace1_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define IFace1_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ #define IFace1_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define IFace1_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ #define IFace1_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define IFace1_get_Face1Name(This,pVal) \ #define IFace1_get_Face1Name(This,pVal) \
(This)->lpVtbl -> get_Face1Name(This,pVal) (This)->lpVtbl -> get_Face1Name(This,pVal)
#define IFace1_put_Face1Name(This,newVal) \ #define IFace1_put_Face1Name(This,newVal) \
(This)->lpVtbl -> put_Face1Name(This,newVal) (This)->lpVtbl -> put_Face1Name(This,newVal)
#endif /* COBJMACROS */ #endif /* COBJMACROS */
#endif /* C style interface */ #endif /* C style interface */
@@ -225,7 +225,7 @@ void __RPC_STUB IFace1_put_Face1Name_Stub(
#endif /* __IFace1_INTERFACE_DEFINED__ */ #endif /* __IFace1_INTERFACE_DEFINED__ */
#ifndef __IFace2_INTERFACE_DEFINED__ #ifndef __IFace2_INTERFACE_DEFINED__
@@ -251,7 +251,7 @@ EXTERN_C const IID IID_IFace2;
}; };
#else /* C style interface */ #else /* C style interface */
typedef struct IFace2Vtbl typedef struct IFace2Vtbl
{ {
@@ -318,39 +318,39 @@ EXTERN_C const IID IID_IFace2;
#ifdef COBJMACROS #ifdef COBJMACROS
#define IFace2_QueryInterface(This,riid,ppvObject) \ #define IFace2_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject) (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IFace2_AddRef(This) \ #define IFace2_AddRef(This) \
(This)->lpVtbl -> AddRef(This) (This)->lpVtbl -> AddRef(This)
#define IFace2_Release(This) \ #define IFace2_Release(This) \
(This)->lpVtbl -> Release(This) (This)->lpVtbl -> Release(This)
#define IFace2_GetTypeInfoCount(This,pctinfo) \ #define IFace2_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define IFace2_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ #define IFace2_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define IFace2_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ #define IFace2_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define IFace2_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ #define IFace2_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define IFace2_get_Face2Nam(This,pVal) \ #define IFace2_get_Face2Nam(This,pVal) \
(This)->lpVtbl -> get_Face2Nam(This,pVal) (This)->lpVtbl -> get_Face2Nam(This,pVal)
#define IFace2_put_Face2Nam(This,newVal) \ #define IFace2_put_Face2Nam(This,newVal) \
(This)->lpVtbl -> put_Face2Nam(This,newVal) (This)->lpVtbl -> put_Face2Nam(This,newVal)
#endif /* COBJMACROS */ #endif /* COBJMACROS */
#endif /* C style interface */ #endif /* C style interface */
@@ -379,7 +379,7 @@ void __RPC_STUB IFace2_put_Face2Nam_Stub(
#endif /* __IFace2_INTERFACE_DEFINED__ */ #endif /* __IFace2_INTERFACE_DEFINED__ */
#ifndef __IFace3_INTERFACE_DEFINED__ #ifndef __IFace3_INTERFACE_DEFINED__
@@ -405,7 +405,7 @@ EXTERN_C const IID IID_IFace3;
}; };
#else /* C style interface */ #else /* C style interface */
typedef struct IFace3Vtbl typedef struct IFace3Vtbl
{ {
@@ -472,39 +472,39 @@ EXTERN_C const IID IID_IFace3;
#ifdef COBJMACROS #ifdef COBJMACROS
#define IFace3_QueryInterface(This,riid,ppvObject) \ #define IFace3_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject) (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IFace3_AddRef(This) \ #define IFace3_AddRef(This) \
(This)->lpVtbl -> AddRef(This) (This)->lpVtbl -> AddRef(This)
#define IFace3_Release(This) \ #define IFace3_Release(This) \
(This)->lpVtbl -> Release(This) (This)->lpVtbl -> Release(This)
#define IFace3_GetTypeInfoCount(This,pctinfo) \ #define IFace3_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define IFace3_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ #define IFace3_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define IFace3_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ #define IFace3_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define IFace3_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ #define IFace3_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define IFace3_get_Face3Name(This,pVal) \ #define IFace3_get_Face3Name(This,pVal) \
(This)->lpVtbl -> get_Face3Name(This,pVal) (This)->lpVtbl -> get_Face3Name(This,pVal)
#define IFace3_put_Face3Name(This,newVal) \ #define IFace3_put_Face3Name(This,newVal) \
(This)->lpVtbl -> put_Face3Name(This,newVal) (This)->lpVtbl -> put_Face3Name(This,newVal)
#endif /* COBJMACROS */ #endif /* COBJMACROS */
#endif /* C style interface */ #endif /* C style interface */
@@ -533,7 +533,7 @@ void __RPC_STUB IFace3_put_Face3Name_Stub(
#endif /* __IFace3_INTERFACE_DEFINED__ */ #endif /* __IFace3_INTERFACE_DEFINED__ */

View File

@@ -346,117 +346,117 @@ static const MIDL_PROC_FORMAT_STRING __MIDL_ProcFormatString =
0, 0,
{ {
/* Procedure get_Face3Name */ /* Procedure get_Face3Name */
/* Procedure get_Face2Nam */ /* Procedure get_Face2Nam */
/* Procedure get_Face1Name */ /* Procedure get_Face1Name */
0x33, /* FC_AUTO_HANDLE */ 0x33, /* FC_AUTO_HANDLE */
0x6c, /* Old Flags: object, Oi2 */ 0x6c, /* Old Flags: object, Oi2 */
/* 2 */ NdrFcLong( 0x0 ), /* 0 */ /* 2 */ NdrFcLong( 0x0 ), /* 0 */
/* 6 */ NdrFcShort( 0x7 ), /* 7 */ /* 6 */ NdrFcShort( 0x7 ), /* 7 */
#ifndef _ALPHA_ #ifndef _ALPHA_
/* 8 */ NdrFcShort( 0xc ), /* x86, MIPS, PPC Stack size/offset = 12 */ /* 8 */ NdrFcShort( 0xc ), /* x86, MIPS, PPC Stack size/offset = 12 */
#else #else
NdrFcShort( 0x18 ), /* Alpha Stack size/offset = 24 */ NdrFcShort( 0x18 ), /* Alpha Stack size/offset = 24 */
#endif #endif
/* 10 */ NdrFcShort( 0x0 ), /* 0 */ /* 10 */ NdrFcShort( 0x0 ), /* 0 */
/* 12 */ NdrFcShort( 0x8 ), /* 8 */ /* 12 */ NdrFcShort( 0x8 ), /* 8 */
/* 14 */ 0x5, /* Oi2 Flags: srv must size, has return, */ /* 14 */ 0x5, /* Oi2 Flags: srv must size, has return, */
0x2, /* 2 */ 0x2, /* 2 */
/* Parameter pVal */ /* Parameter pVal */
/* Parameter pVal */ /* Parameter pVal */
/* Parameter pVal */ /* Parameter pVal */
/* 16 */ NdrFcShort( 0x2113 ), /* Flags: must size, must free, out, simple ref, srv alloc size=8 */ /* 16 */ NdrFcShort( 0x2113 ), /* Flags: must size, must free, out, simple ref, srv alloc size=8 */
#ifndef _ALPHA_ #ifndef _ALPHA_
/* 18 */ NdrFcShort( 0x4 ), /* x86, MIPS, PPC Stack size/offset = 4 */ /* 18 */ NdrFcShort( 0x4 ), /* x86, MIPS, PPC Stack size/offset = 4 */
#else #else
NdrFcShort( 0x8 ), /* Alpha Stack size/offset = 8 */ NdrFcShort( 0x8 ), /* Alpha Stack size/offset = 8 */
#endif #endif
/* 20 */ NdrFcShort( 0x1e ), /* Type Offset=30 */ /* 20 */ NdrFcShort( 0x1e ), /* Type Offset=30 */
/* Return value */ /* Return value */
/* Return value */ /* Return value */
/* Return value */ /* Return value */
/* 22 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 22 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */
#ifndef _ALPHA_ #ifndef _ALPHA_
/* 24 */ NdrFcShort( 0x8 ), /* x86, MIPS, PPC Stack size/offset = 8 */ /* 24 */ NdrFcShort( 0x8 ), /* x86, MIPS, PPC Stack size/offset = 8 */
#else #else
NdrFcShort( 0x10 ), /* Alpha Stack size/offset = 16 */ NdrFcShort( 0x10 ), /* Alpha Stack size/offset = 16 */
#endif #endif
/* 26 */ 0x8, /* FC_LONG */ /* 26 */ 0x8, /* FC_LONG */
0x0, /* 0 */ 0x0, /* 0 */
/* Procedure put_Face3Name */ /* Procedure put_Face3Name */
/* Procedure put_Face2Nam */ /* Procedure put_Face2Nam */
/* Procedure put_Face1Name */ /* Procedure put_Face1Name */
/* 28 */ 0x33, /* FC_AUTO_HANDLE */ /* 28 */ 0x33, /* FC_AUTO_HANDLE */
0x6c, /* Old Flags: object, Oi2 */ 0x6c, /* Old Flags: object, Oi2 */
/* 30 */ NdrFcLong( 0x0 ), /* 0 */ /* 30 */ NdrFcLong( 0x0 ), /* 0 */
/* 34 */ NdrFcShort( 0x8 ), /* 8 */ /* 34 */ NdrFcShort( 0x8 ), /* 8 */
#ifndef _ALPHA_ #ifndef _ALPHA_
/* 36 */ NdrFcShort( 0xc ), /* x86, MIPS, PPC Stack size/offset = 12 */ /* 36 */ NdrFcShort( 0xc ), /* x86, MIPS, PPC Stack size/offset = 12 */
#else #else
NdrFcShort( 0x18 ), /* Alpha Stack size/offset = 24 */ NdrFcShort( 0x18 ), /* Alpha Stack size/offset = 24 */
#endif #endif
/* 38 */ NdrFcShort( 0x0 ), /* 0 */ /* 38 */ NdrFcShort( 0x0 ), /* 0 */
/* 40 */ NdrFcShort( 0x8 ), /* 8 */ /* 40 */ NdrFcShort( 0x8 ), /* 8 */
/* 42 */ 0x6, /* Oi2 Flags: clt must size, has return, */ /* 42 */ 0x6, /* Oi2 Flags: clt must size, has return, */
0x2, /* 2 */ 0x2, /* 2 */
/* Parameter newVal */ /* Parameter newVal */
/* Parameter newVal */ /* Parameter newVal */
/* Parameter newVal */ /* Parameter newVal */
/* 44 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */ /* 44 */ NdrFcShort( 0x8b ), /* Flags: must size, must free, in, by val, */
#ifndef _ALPHA_ #ifndef _ALPHA_
/* 46 */ NdrFcShort( 0x4 ), /* x86, MIPS, PPC Stack size/offset = 4 */ /* 46 */ NdrFcShort( 0x4 ), /* x86, MIPS, PPC Stack size/offset = 4 */
#else #else
NdrFcShort( 0x8 ), /* Alpha Stack size/offset = 8 */ NdrFcShort( 0x8 ), /* Alpha Stack size/offset = 8 */
#endif #endif
/* 48 */ NdrFcShort( 0x2c ), /* Type Offset=44 */ /* 48 */ NdrFcShort( 0x2c ), /* Type Offset=44 */
/* Return value */ /* Return value */
/* Return value */ /* Return value */
/* Return value */ /* Return value */
/* 50 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 50 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */
#ifndef _ALPHA_ #ifndef _ALPHA_
/* 52 */ NdrFcShort( 0x8 ), /* x86, MIPS, PPC Stack size/offset = 8 */ /* 52 */ NdrFcShort( 0x8 ), /* x86, MIPS, PPC Stack size/offset = 8 */
#else #else
NdrFcShort( 0x10 ), /* Alpha Stack size/offset = 16 */ NdrFcShort( 0x10 ), /* Alpha Stack size/offset = 16 */
#endif #endif
/* 54 */ 0x8, /* FC_LONG */ /* 54 */ 0x8, /* FC_LONG */
0x0, /* 0 */ 0x0, /* 0 */
0x0 0x0
} }
}; };
@@ -464,48 +464,48 @@ static const MIDL_TYPE_FORMAT_STRING __MIDL_TypeFormatString =
{ {
0, 0,
{ {
NdrFcShort( 0x0 ), /* 0 */ NdrFcShort( 0x0 ), /* 0 */
/* 2 */ /* 2 */
0x11, 0x4, /* FC_RP [alloced_on_stack] */ 0x11, 0x4, /* FC_RP [alloced_on_stack] */
/* 4 */ NdrFcShort( 0x1a ), /* Offset= 26 (30) */ /* 4 */ NdrFcShort( 0x1a ), /* Offset= 26 (30) */
/* 6 */ /* 6 */
0x13, 0x0, /* FC_OP */ 0x13, 0x0, /* FC_OP */
/* 8 */ NdrFcShort( 0xc ), /* Offset= 12 (20) */ /* 8 */ NdrFcShort( 0xc ), /* Offset= 12 (20) */
/* 10 */ /* 10 */
0x1b, /* FC_CARRAY */ 0x1b, /* FC_CARRAY */
0x1, /* 1 */ 0x1, /* 1 */
/* 12 */ NdrFcShort( 0x2 ), /* 2 */ /* 12 */ NdrFcShort( 0x2 ), /* 2 */
/* 14 */ 0x9, /* Corr desc: FC_ULONG */ /* 14 */ 0x9, /* Corr desc: FC_ULONG */
0x0, /* */ 0x0, /* */
/* 16 */ NdrFcShort( 0xfffc ), /* -4 */ /* 16 */ NdrFcShort( 0xfffc ), /* -4 */
/* 18 */ 0x6, /* FC_SHORT */ /* 18 */ 0x6, /* FC_SHORT */
0x5b, /* FC_END */ 0x5b, /* FC_END */
/* 20 */ /* 20 */
0x17, /* FC_CSTRUCT */ 0x17, /* FC_CSTRUCT */
0x3, /* 3 */ 0x3, /* 3 */
/* 22 */ NdrFcShort( 0x8 ), /* 8 */ /* 22 */ NdrFcShort( 0x8 ), /* 8 */
/* 24 */ NdrFcShort( 0xfffffff2 ), /* Offset= -14 (10) */ /* 24 */ NdrFcShort( 0xfffffff2 ), /* Offset= -14 (10) */
/* 26 */ 0x8, /* FC_LONG */ /* 26 */ 0x8, /* FC_LONG */
0x8, /* FC_LONG */ 0x8, /* FC_LONG */
/* 28 */ 0x5c, /* FC_PAD */ /* 28 */ 0x5c, /* FC_PAD */
0x5b, /* FC_END */ 0x5b, /* FC_END */
/* 30 */ 0xb4, /* FC_USER_MARSHAL */ /* 30 */ 0xb4, /* FC_USER_MARSHAL */
0x83, /* 131 */ 0x83, /* 131 */
/* 32 */ NdrFcShort( 0x0 ), /* 0 */ /* 32 */ NdrFcShort( 0x0 ), /* 0 */
/* 34 */ NdrFcShort( 0x4 ), /* 4 */ /* 34 */ NdrFcShort( 0x4 ), /* 4 */
/* 36 */ NdrFcShort( 0x0 ), /* 0 */ /* 36 */ NdrFcShort( 0x0 ), /* 0 */
/* 38 */ NdrFcShort( 0xffffffe0 ), /* Offset= -32 (6) */ /* 38 */ NdrFcShort( 0xffffffe0 ), /* Offset= -32 (6) */
/* 40 */ /* 40 */
0x12, 0x0, /* FC_UP */ 0x12, 0x0, /* FC_UP */
/* 42 */ NdrFcShort( 0xffffffea ), /* Offset= -22 (20) */ /* 42 */ NdrFcShort( 0xffffffea ), /* Offset= -22 (20) */
/* 44 */ 0xb4, /* FC_USER_MARSHAL */ /* 44 */ 0xb4, /* FC_USER_MARSHAL */
0x83, /* 131 */ 0x83, /* 131 */
/* 46 */ NdrFcShort( 0x0 ), /* 0 */ /* 46 */ NdrFcShort( 0x0 ), /* 0 */
/* 48 */ NdrFcShort( 0x4 ), /* 4 */ /* 48 */ NdrFcShort( 0x4 ), /* 4 */
/* 50 */ NdrFcShort( 0x0 ), /* 0 */ /* 50 */ NdrFcShort( 0x0 ), /* 0 */
/* 52 */ NdrFcShort( 0xfffffff4 ), /* Offset= -12 (40) */ /* 52 */ NdrFcShort( 0xfffffff4 ), /* Offset= -12 (40) */
0x0 0x0
} }
}; };
@@ -542,7 +542,7 @@ const IID * _MultiFace_BaseIIDList[] =
}; };
#define _MultiFace_CHECK_IID(n) IID_GENERIC_CHECK_IID( _MultiFace, pIID, n) #define _MultiFace_CHECK_IID(n) IID_GENERIC_CHECK_IID( _MultiFace, pIID, n)
int __stdcall _MultiFace_IID_Lookup( const IID * pIID, int * pIndex ) int __stdcall _MultiFace_IID_Lookup( const IID * pIID, int * pIndex )
{ {

View File

@@ -6,41 +6,41 @@ import com.jacob.com.Variant;
class MultiFaceTest { class MultiFaceTest {
/** /**
* standard main() test program * standard main() test program
* *
* @param args * @param args
* the command line arguments * the command line arguments
*/ */
public static void main(String[] args) { public static void main(String[] args) {
// this method has been deprecated as being unreliable. // this method has been deprecated as being unreliable.
// shutdown should be done through other means // shutdown should be done through other means
// whoever wrote this example should explain what this was intended to // whoever wrote this example should explain what this was intended to
// do // do
// System.runFinalizersOnExit(true); // System.runFinalizersOnExit(true);
ActiveXComponent mf = new ActiveXComponent("MultiFace.Face"); ActiveXComponent mf = new ActiveXComponent("MultiFace.Face");
try { try {
// I am now dealing with the default interface (IFace1) // I am now dealing with the default interface (IFace1)
Dispatch.put(mf, "Face1Name", new Variant("Hello Face1")); Dispatch.put(mf, "Face1Name", new Variant("Hello Face1"));
System.out.println(Dispatch.get(mf, "Face1Name")); System.out.println(Dispatch.get(mf, "Face1Name"));
// get to IFace2 through the IID // get to IFace2 through the IID
Dispatch f2 = mf Dispatch f2 = mf
.QueryInterface("{9BF24410-B2E0-11D4-A695-00104BFF3241}"); .QueryInterface("{9BF24410-B2E0-11D4-A695-00104BFF3241}");
// I am now dealing with IFace2 // I am now dealing with IFace2
Dispatch.put(f2, "Face2Nam", new Variant("Hello Face2")); Dispatch.put(f2, "Face2Nam", new Variant("Hello Face2"));
System.out.println(Dispatch.get(f2, "Face2Nam")); System.out.println(Dispatch.get(f2, "Face2Nam"));
// get to IFace3 through the IID // get to IFace3 through the IID
Dispatch f3 = mf Dispatch f3 = mf
.QueryInterface("{9BF24411-B2E0-11D4-A695-00104BFF3241}"); .QueryInterface("{9BF24411-B2E0-11D4-A695-00104BFF3241}");
// I am now dealing with IFace3 // I am now dealing with IFace3
Dispatch.put(f3, "Face3Name", new Variant("Hello Face3")); Dispatch.put(f3, "Face3Name", new Variant("Hello Face3"));
System.out.println(Dispatch.get(f3, "Face3Name")); System.out.println(Dispatch.get(f3, "Face3Name"));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View File

@@ -14,39 +14,39 @@ import com.jacob.com.Variant;
*/ */
public class ExcelDispatchTest { public class ExcelDispatchTest {
/** /**
* main run loop for test program * main run loop for test program
* *
* @param args * @param args
* standard command line arguments * standard command line arguments
*/ */
public static void main(String[] args) { public static void main(String[] args) {
ComThread.InitSTA(); ComThread.InitSTA();
ActiveXComponent xl = new ActiveXComponent("Excel.Application"); ActiveXComponent xl = new ActiveXComponent("Excel.Application");
try { try {
System.out.println("version=" + xl.getProperty("Version")); System.out.println("version=" + xl.getProperty("Version"));
System.out.println("version=" + Dispatch.get(xl, "Version")); System.out.println("version=" + Dispatch.get(xl, "Version"));
Dispatch.put(xl, "Visible", new Variant(true)); Dispatch.put(xl, "Visible", new Variant(true));
Dispatch workbooks = xl.getProperty("Workbooks").toDispatch(); Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
Dispatch workbook = Dispatch.get(workbooks, "Add").toDispatch(); Dispatch workbook = Dispatch.get(workbooks, "Add").toDispatch();
Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch(); Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
Dispatch a1 = Dispatch.invoke(sheet, "Range", Dispatch.Get, Dispatch a1 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { "A1" }, new int[1]).toDispatch(); new Object[] { "A1" }, new int[1]).toDispatch();
Dispatch a2 = Dispatch.invoke(sheet, "Range", Dispatch.Get, Dispatch a2 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { "A2" }, new int[1]).toDispatch(); new Object[] { "A2" }, new int[1]).toDispatch();
Dispatch.put(a1, "Value", "123.456"); Dispatch.put(a1, "Value", "123.456");
Dispatch.put(a2, "Formula", "=A1*2"); Dispatch.put(a2, "Formula", "=A1*2");
System.out.println("a1 from excel:" + Dispatch.get(a1, "Value")); System.out.println("a1 from excel:" + Dispatch.get(a1, "Value"));
System.out.println("a2 from excel:" + Dispatch.get(a2, "Value")); System.out.println("a2 from excel:" + Dispatch.get(a2, "Value"));
Variant f = new Variant(false); Variant f = new Variant(false);
Dispatch.call(workbook, "Close", f); Dispatch.call(workbook, "Close", f);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
xl.invoke("Quit", new Variant[] {}); xl.invoke("Quit", new Variant[] {});
ComThread.Release(); ComThread.Release();
} }
} }
} }

View File

@@ -14,35 +14,35 @@ import com.jacob.com.Dispatch;
*/ */
public class VisioPrintTest { public class VisioPrintTest {
/** /**
* Runs the print ant lets the user say ok or cancel. Note the funky Visio * Runs the print ant lets the user say ok or cancel. Note the funky Visio
* behavior if someone hits the cancel button * behavior if someone hits the cancel button
* *
*/ */
public void testPrintDialog() { public void testPrintDialog() {
ActiveXComponent oActiveX = new ActiveXComponent("Visio.Application"); ActiveXComponent oActiveX = new ActiveXComponent("Visio.Application");
Dispatch oDocuments = oActiveX.getProperty("Documents").toDispatch(); Dispatch oDocuments = oActiveX.getProperty("Documents").toDispatch();
// create a blank document // create a blank document
Dispatch.call(oDocuments, "Add", ""); Dispatch.call(oDocuments, "Add", "");
try { try {
Dispatch.call(oActiveX, "DoCmd", new Integer(1010)).getInt(); Dispatch.call(oActiveX, "DoCmd", new Integer(1010)).getInt();
System.out.println("User hit the ok button."); System.out.println("User hit the ok button.");
} catch (ComFailException e) { } catch (ComFailException e) {
System.out.println("User hit the cancel button: " + e); System.out.println("User hit the cancel button: " + e);
} finally { } finally {
oActiveX.invoke("Quit"); oActiveX.invoke("Quit");
} }
return; return;
} }
/** /**
* quick main() to test this * quick main() to test this
* *
* @param args * @param args
* standard command line arguments * standard command line arguments
*/ */
public static void main(String[] args) { public static void main(String[] args) {
VisioPrintTest testObject = new VisioPrintTest(); VisioPrintTest testObject = new VisioPrintTest();
testObject.testPrintDialog(); testObject.testPrintDialog();
} }
} }

View File

@@ -18,154 +18,154 @@ import com.jacob.com.Variant;
* are sections that could be enhanced * are sections that could be enhanced
*/ */
public class WordDocumentProperties { public class WordDocumentProperties {
// Declare word object // Declare word object
private ActiveXComponent objWord; private ActiveXComponent objWord;
// Declare Word Properties // Declare Word Properties
private Dispatch custDocprops; private Dispatch custDocprops;
private Dispatch builtInDocProps; private Dispatch builtInDocProps;
// the doucments object is important in any real app but this demo doesn't // the doucments object is important in any real app but this demo doesn't
// use it // use it
// private Dispatch documents; // private Dispatch documents;
private Dispatch document; private Dispatch document;
private Dispatch wordObject; private Dispatch wordObject;
/** /**
* Empty Constructor * Empty Constructor
* *
*/ */
public WordDocumentProperties() { public WordDocumentProperties() {
} }
/** /**
* Opens a document * Opens a document
* *
* @param filename * @param filename
*/ */
public void open(String filename) { public void open(String filename) {
// Instantiate objWord // Instantiate objWord
objWord = new ActiveXComponent("Word.Application"); objWord = new ActiveXComponent("Word.Application");
// Assign a local word object // Assign a local word object
wordObject = objWord.getObject(); wordObject = objWord.getObject();
// Create a Dispatch Parameter to hide the document that is opened // Create a Dispatch Parameter to hide the document that is opened
Dispatch.put(wordObject, "Visible", new Variant(false)); Dispatch.put(wordObject, "Visible", new Variant(false));
// Instantiate the Documents Property // Instantiate the Documents Property
Dispatch documents = objWord.getProperty("Documents").toDispatch(); Dispatch documents = objWord.getProperty("Documents").toDispatch();
// Open a word document, Current Active Document // Open a word document, Current Active Document
document = Dispatch.call(documents, "Open", filename).toDispatch(); document = Dispatch.call(documents, "Open", filename).toDispatch();
} }
/** /**
* Creates an instance of the VBA CustomDocumentProperties property * Creates an instance of the VBA CustomDocumentProperties property
* *
*/ */
public void selectCustomDocumentProperitiesMode() { public void selectCustomDocumentProperitiesMode() {
// Create CustomDocumentProperties and BuiltInDocumentProperties // Create CustomDocumentProperties and BuiltInDocumentProperties
// properties // properties
custDocprops = Dispatch.get(document, "CustomDocumentProperties") custDocprops = Dispatch.get(document, "CustomDocumentProperties")
.toDispatch(); .toDispatch();
} }
/** /**
* Creates an instance of the VBA BuiltInDocumentProperties property * Creates an instance of the VBA BuiltInDocumentProperties property
* *
*/ */
public void selectBuiltinPropertiesMode() { public void selectBuiltinPropertiesMode() {
// Create CustomDocumentProperties and BuiltInDocumentProperties // Create CustomDocumentProperties and BuiltInDocumentProperties
// properties // properties
builtInDocProps = Dispatch.get(document, "BuiltInDocumentProperties") builtInDocProps = Dispatch.get(document, "BuiltInDocumentProperties")
.toDispatch(); .toDispatch();
} }
/** /**
* Closes a document * Closes a document
* *
*/ */
public void close() { public void close() {
// Close object // Close object
Dispatch.call(document, "Close"); Dispatch.call(document, "Close");
} }
/** /**
* Custom Property Name is passed in * Custom Property Name is passed in
* *
* @param cusPropName * @param cusPropName
* @return String - Custom property value * @return String - Custom property value
*/ */
public String getCustomProperty(String cusPropName) { public String getCustomProperty(String cusPropName) {
try { try {
cusPropName = Dispatch.call(custDocprops, "Item", cusPropName) cusPropName = Dispatch.call(custDocprops, "Item", cusPropName)
.toString(); .toString();
} catch (ComException e) { } catch (ComException e) {
// Do nothing // Do nothing
cusPropName = null; cusPropName = null;
} }
return cusPropName; return cusPropName;
} }
/** /**
* Built In Property Name is passed in * Built In Property Name is passed in
* *
* @param builtInPropName * @param builtInPropName
* @return String - Built in property value * @return String - Built in property value
*/ */
public String getBuiltInProperty(String builtInPropName) { public String getBuiltInProperty(String builtInPropName) {
try { try {
builtInPropName = Dispatch.call(builtInDocProps, "Item", builtInPropName = Dispatch.call(builtInDocProps, "Item",
builtInPropName).toString(); builtInPropName).toString();
} catch (ComException e) { } catch (ComException e) {
// Do nothing // Do nothing
builtInPropName = null; builtInPropName = null;
} }
return builtInPropName; return builtInPropName;
} }
/** /**
* simple main program that gets some properties and prints them out * simple main program that gets some properties and prints them out
* *
* @param args * @param args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
try { try {
// Instantiate the class // Instantiate the class
WordDocumentProperties jacTest = new WordDocumentProperties(); WordDocumentProperties jacTest = new WordDocumentProperties();
// Open the word doc // Open the word doc
File doc = new File( File doc = new File(
"samples/com/jacob/samples/office/TestDocument.doc"); "samples/com/jacob/samples/office/TestDocument.doc");
jacTest.open(doc.getAbsolutePath()); jacTest.open(doc.getAbsolutePath());
// Set Custom Properties // Set Custom Properties
jacTest.selectCustomDocumentProperitiesMode(); jacTest.selectCustomDocumentProperitiesMode();
// Set Built In Properties // Set Built In Properties
jacTest.selectBuiltinPropertiesMode(); jacTest.selectBuiltinPropertiesMode();
// Get custom Property Value // Get custom Property Value
String custValue = jacTest.getCustomProperty("Information Source"); String custValue = jacTest.getCustomProperty("Information Source");
// Get built in prroperty Property Value // Get built in prroperty Property Value
String builtInValue = jacTest.getBuiltInProperty("Author"); String builtInValue = jacTest.getBuiltInProperty("Author");
// Close Word Doc // Close Word Doc
jacTest.close(); jacTest.close();
// Output data // Output data
System.out.println("Document Val One: " + custValue); System.out.println("Document Val One: " + custValue);
System.out.println("Document Author: " + builtInValue); System.out.println("Document Author: " + builtInValue);
} catch (Exception e) { } catch (Exception e) {
System.out.println(e); System.out.println(e);
} }
} }
} }

View File

@@ -14,67 +14,67 @@ import com.jacob.com.Variant;
*/ */
public class Outlook { public class Outlook {
private static String pad(int i) { private static String pad(int i) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
while (sb.length() < i) { while (sb.length() < i) {
sb.append(' '); sb.append(' ');
} }
return sb.toString(); return sb.toString();
} }
private static void recurseFolders(int iIndent, Dispatch o) { private static void recurseFolders(int iIndent, Dispatch o) {
if (o == null) { if (o == null) {
return; return;
} }
Dispatch oFolders = Dispatch.get(o, "Folders").toDispatch(); Dispatch oFolders = Dispatch.get(o, "Folders").toDispatch();
// System.out.println("oFolders=" + oFolders); // System.out.println("oFolders=" + oFolders);
if (oFolders == null) { if (oFolders == null) {
return; return;
} }
Dispatch oFolder = Dispatch.get(oFolders, "GetFirst").toDispatch(); Dispatch oFolder = Dispatch.get(oFolders, "GetFirst").toDispatch();
do { do {
Object oFolderName = Dispatch.get(oFolder, "Name"); Object oFolderName = Dispatch.get(oFolder, "Name");
if (null == oFolderName) { if (null == oFolderName) {
break; break;
} }
System.out.println(pad(iIndent) + oFolderName); System.out.println(pad(iIndent) + oFolderName);
recurseFolders(iIndent + 3, oFolder); recurseFolders(iIndent + 3, oFolder);
oFolder = Dispatch.get(oFolders, "GetNext").toDispatch(); oFolder = Dispatch.get(oFolders, "GetNext").toDispatch();
} while (true); } while (true);
} }
/** /**
* standard run loop * standard run loop
* *
* @param asArgs * @param asArgs
* command line arguments * command line arguments
* @throws Exception * @throws Exception
*/ */
public static void main(String asArgs[]) throws Exception { public static void main(String asArgs[]) throws Exception {
System.out.println("Outlook: IN"); System.out.println("Outlook: IN");
ActiveXComponent axOutlook = new ActiveXComponent("Outlook.Application"); ActiveXComponent axOutlook = new ActiveXComponent("Outlook.Application");
try { try {
System.out.println("version=" + axOutlook.getProperty("Version")); System.out.println("version=" + axOutlook.getProperty("Version"));
Dispatch oOutlook = axOutlook.getObject(); Dispatch oOutlook = axOutlook.getObject();
System.out.println("version=" + Dispatch.get(oOutlook, "Version")); System.out.println("version=" + Dispatch.get(oOutlook, "Version"));
Dispatch oNameSpace = axOutlook.getProperty("Session").toDispatch(); Dispatch oNameSpace = axOutlook.getProperty("Session").toDispatch();
System.out.println("oNameSpace=" + oNameSpace); System.out.println("oNameSpace=" + oNameSpace);
recurseFolders(0, oNameSpace); recurseFolders(0, oNameSpace);
} finally { } finally {
axOutlook.invoke("Quit", new Variant[] {}); axOutlook.invoke("Quit", new Variant[] {});
} }
} }
} }

View File

@@ -21,132 +21,132 @@ import com.jacob.com.Variant;
*/ */
public class DiskUtils { public class DiskUtils {
/** formatters aren't thread safe but the sample only has one thread */ /** formatters aren't thread safe but the sample only has one thread */
private static DecimalFormat sizeFormatter = new DecimalFormat( private static DecimalFormat sizeFormatter = new DecimalFormat(
"###,###,###,###"); "###,###,###,###");
/** a pointer to the scripting file system object */ /** a pointer to the scripting file system object */
private ActiveXComponent fileSystemApp = null; private ActiveXComponent fileSystemApp = null;
/** the dispatch that points at the drive this DiskUtil operates against */ /** the dispatch that points at the drive this DiskUtil operates against */
private Dispatch myDrive = null; private Dispatch myDrive = null;
/** /**
* Standard constructor * Standard constructor
* *
* @param drive * @param drive
* the drive to run the test against. * the drive to run the test against.
*/ */
public DiskUtils(String drive) { public DiskUtils(String drive) {
setUp(drive); setUp(drive);
} }
/** /**
* open the connection to the scripting object * open the connection to the scripting object
* *
* @param drive * @param drive
* the drive to run the test against * the drive to run the test against
*/ */
public void setUp(String drive) { public void setUp(String drive) {
if (fileSystemApp == null) { if (fileSystemApp == null) {
ComThread.InitSTA(); ComThread.InitSTA();
fileSystemApp = new ActiveXComponent("Scripting.FileSystemObject"); fileSystemApp = new ActiveXComponent("Scripting.FileSystemObject");
myDrive = Dispatch.call(fileSystemApp, "GetDrive", drive) myDrive = Dispatch.call(fileSystemApp, "GetDrive", drive)
.toDispatch(); .toDispatch();
} }
} }
/** /**
* Do any needed cleanup * Do any needed cleanup
*/ */
public void tearDown() { public void tearDown() {
ComThread.Release(); ComThread.Release();
} }
/** /**
* convenience method * convenience method
* *
* @return driver serial number * @return driver serial number
*/ */
public int getSerialNumber() { public int getSerialNumber() {
return Dispatch.get(myDrive, "SerialNumber").getInt(); return Dispatch.get(myDrive, "SerialNumber").getInt();
} }
/** /**
* Convenience method. We go through these formatting hoops so we can make * Convenience method. We go through these formatting hoops so we can make
* the size string pretty. We wouldn't have to do that if we didn't mind * the size string pretty. We wouldn't have to do that if we didn't mind
* long strings with Exxx at the end or the fact that the value returned can * long strings with Exxx at the end or the fact that the value returned can
* vary in size based on the size of the disk. * vary in size based on the size of the disk.
* *
* @return driver total size of the disk * @return driver total size of the disk
*/ */
public String getTotalSize() { public String getTotalSize() {
Variant returnValue = Dispatch.get(myDrive, "TotalSize"); Variant returnValue = Dispatch.get(myDrive, "TotalSize");
if (returnValue.getvt() == Variant.VariantDouble) { if (returnValue.getvt() == Variant.VariantDouble) {
return sizeFormatter.format(returnValue.getDouble()); return sizeFormatter.format(returnValue.getDouble());
} else if (returnValue.getvt() == Variant.VariantInt) { } else if (returnValue.getvt() == Variant.VariantInt) {
return sizeFormatter.format(returnValue.getInt()); return sizeFormatter.format(returnValue.getInt());
} else { } else {
return "Don't know type: " + returnValue.getvt(); return "Don't know type: " + returnValue.getvt();
} }
} }
/** /**
* Convenience method. We wouldn't have to do that if we didn't mind long * Convenience method. We wouldn't have to do that if we didn't mind long
* strings with Exxx at the end or the fact that the value returned can vary * strings with Exxx at the end or the fact that the value returned can vary
* in size based on the size of the disk. * in size based on the size of the disk.
* *
* @return driver free size of the disk * @return driver free size of the disk
*/ */
public String getFreeSpace() { public String getFreeSpace() {
Variant returnValue = Dispatch.get(myDrive, "FreeSpace"); Variant returnValue = Dispatch.get(myDrive, "FreeSpace");
if (returnValue.getvt() == Variant.VariantDouble) { if (returnValue.getvt() == Variant.VariantDouble) {
return sizeFormatter.format(returnValue.getDouble()); return sizeFormatter.format(returnValue.getDouble());
} else if (returnValue.getvt() == Variant.VariantInt) { } else if (returnValue.getvt() == Variant.VariantInt) {
return sizeFormatter.format(returnValue.getInt()); return sizeFormatter.format(returnValue.getInt());
} else { } else {
return "Don't know type: " + returnValue.getvt(); return "Don't know type: " + returnValue.getvt();
} }
} }
/** /**
* *
* @return file system on the drive * @return file system on the drive
*/ */
public String getFileSystemType() { public String getFileSystemType() {
// figure ot the actual variant type // figure ot the actual variant type
// Variant returnValue = Dispatch.get(myDrive, "FileSystem"); // Variant returnValue = Dispatch.get(myDrive, "FileSystem");
// System.out.println(returnValue.getvt()); // System.out.println(returnValue.getvt());
return Dispatch.get(myDrive, "FileSystem").getString(); return Dispatch.get(myDrive, "FileSystem").getString();
} }
/** /**
* *
* @return volume name * @return volume name
*/ */
public String getVolumeName() { public String getVolumeName() {
return Dispatch.get(myDrive, "VolumeName").getString(); return Dispatch.get(myDrive, "VolumeName").getString();
} }
/** /**
* Simple main program that creates a DiskUtils object and queries for the * Simple main program that creates a DiskUtils object and queries for the
* C: drive * C: drive
* *
* @param args * @param args
* standard command line arguments * standard command line arguments
*/ */
public static void main(String[] args) { public static void main(String[] args) {
// DiskUtils utilConnection = new DiskUtils("F"); // DiskUtils utilConnection = new DiskUtils("F");
DiskUtils utilConnection = new DiskUtils("C"); DiskUtils utilConnection = new DiskUtils("C");
System.out.println("Disk serial number is: " System.out.println("Disk serial number is: "
+ utilConnection.getSerialNumber()); + utilConnection.getSerialNumber());
System.out.println("FileSystem is: " System.out.println("FileSystem is: "
+ utilConnection.getFileSystemType()); + utilConnection.getFileSystemType());
System.out.println("Volume Name is: " + utilConnection.getVolumeName()); System.out.println("Volume Name is: " + utilConnection.getVolumeName());
System.out.println("Disk total size is: " System.out.println("Disk total size is: "
+ utilConnection.getTotalSize()); + utilConnection.getTotalSize());
System.out.println("Disk free space is: " System.out.println("Disk free space is: "
+ utilConnection.getFreeSpace()); + utilConnection.getFreeSpace());
utilConnection.tearDown(); utilConnection.tearDown();
} }
} }

View File

@@ -17,59 +17,59 @@ import com.jacob.com.Variant;
*/ */
public class SystemMonitor { public class SystemMonitor {
/** /**
* example run loop method called by main() * example run loop method called by main()
*/ */
public void runMonitor() { public void runMonitor() {
ActiveXComponent wmi = null; ActiveXComponent wmi = null;
wmi = new ActiveXComponent("WbemScripting.SWbemLocator"); wmi = new ActiveXComponent("WbemScripting.SWbemLocator");
// no connection parameters means to connect to the local machine // no connection parameters means to connect to the local machine
Variant conRet = wmi.invoke("ConnectServer"); Variant conRet = wmi.invoke("ConnectServer");
// the author liked the ActiveXComponent api style over the Dispatch // the author liked the ActiveXComponent api style over the Dispatch
// style // style
ActiveXComponent wmiconnect = new ActiveXComponent(conRet.toDispatch()); ActiveXComponent wmiconnect = new ActiveXComponent(conRet.toDispatch());
// the WMI supports a query language. // the WMI supports a query language.
String query = "select CategoryString, Message, TimeGenerated, User, Type " String query = "select CategoryString, Message, TimeGenerated, User, Type "
+ "from Win32_NtLogEvent " + "from Win32_NtLogEvent "
+ "where Logfile = 'Application' and TimeGenerated > '20070915000000.000000-***'"; + "where Logfile = 'Application' and TimeGenerated > '20070915000000.000000-***'";
Variant vCollection = wmiconnect Variant vCollection = wmiconnect
.invoke("ExecQuery", new Variant(query)); .invoke("ExecQuery", new Variant(query));
EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch()); EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
String resultString = ""; String resultString = "";
Dispatch item = null; Dispatch item = null;
while (enumVariant.hasMoreElements()) { while (enumVariant.hasMoreElements()) {
resultString = ""; resultString = "";
item = enumVariant.nextElement().toDispatch(); item = enumVariant.nextElement().toDispatch();
String categoryString = Dispatch.call(item, "CategoryString") String categoryString = Dispatch.call(item, "CategoryString")
.toString(); .toString();
String messageString = Dispatch.call(item, "Message").toString(); String messageString = Dispatch.call(item, "Message").toString();
String timeGenerated = Dispatch.call(item, "TimeGenerated") String timeGenerated = Dispatch.call(item, "TimeGenerated")
.toString(); .toString();
String eventUser = Dispatch.call(item, "User").toString(); String eventUser = Dispatch.call(item, "User").toString();
String eventType = Dispatch.call(item, "Type").toString(); String eventType = Dispatch.call(item, "Type").toString();
resultString += "TimeGenerated: " + timeGenerated + " Category: " resultString += "TimeGenerated: " + timeGenerated + " Category: "
+ categoryString + " User: " + eventUser + " EventType: " + categoryString + " User: " + eventUser + " EventType: "
+ eventType + " Message:" + messageString; + eventType + " Message:" + messageString;
System.out.println(resultString); System.out.println(resultString);
} }
} }
/** /**
* sample's main program * sample's main program
* *
* @param args * @param args
* command line arguments * command line arguments
*/ */
public static void main(String[] args) { public static void main(String[] args) {
SystemMonitor utilConnection = new SystemMonitor(); SystemMonitor utilConnection = new SystemMonitor();
utilConnection.runMonitor(); utilConnection.runMonitor();
} }
} }

View File

@@ -16,106 +16,106 @@ import com.jacob.com.Variant;
*/ */
public class VisioApp extends ActiveXComponent { public class VisioApp extends ActiveXComponent {
/** /**
* constructor that spins up Visio * constructor that spins up Visio
* *
* @throws VisioException * @throws VisioException
*/ */
public VisioApp() throws VisioException { public VisioApp() throws VisioException {
super("Visio.Application"); super("Visio.Application");
setVisible(false); setVisible(false);
} }
/** /**
* creates a DispatchEvents object to register o as a listener * creates a DispatchEvents object to register o as a listener
* *
* @param o * @param o
*/ */
public void addEventListener(VisioEventListener o) { public void addEventListener(VisioEventListener o) {
DispatchEvents events = new DispatchEvents(this, o); DispatchEvents events = new DispatchEvents(this, o);
if (events == null) { if (events == null) {
System.out System.out
.println("You should never get null back when creating a DispatchEvents object"); .println("You should never get null back when creating a DispatchEvents object");
} }
} }
/** /**
* opens the passed in file in Visio * opens the passed in file in Visio
* *
* @param f * @param f
* @throws VisioException * @throws VisioException
*/ */
public void open(File f) throws VisioException { public void open(File f) throws VisioException {
try { try {
ActiveXComponent documents = new ActiveXComponent(getProperty( ActiveXComponent documents = new ActiveXComponent(getProperty(
"Documents").toDispatch()); "Documents").toDispatch());
Variant[] args = new Variant[1]; Variant[] args = new Variant[1];
args[0] = new Variant(f.getPath()); args[0] = new Variant(f.getPath());
documents.invoke("Open", args); documents.invoke("Open", args);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new VisioException(e); throw new VisioException(e);
} }
} }
/** /**
* tells Visio to save the drawing * tells Visio to save the drawing
* *
* @throws VisioException * @throws VisioException
*/ */
public void save() throws VisioException { public void save() throws VisioException {
try { try {
ActiveXComponent document = new ActiveXComponent(getProperty( ActiveXComponent document = new ActiveXComponent(getProperty(
"ActiveDocument").toDispatch()); "ActiveDocument").toDispatch());
document.invoke("Save"); document.invoke("Save");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new VisioException(e); throw new VisioException(e);
} }
} }
/** /**
* terminates Visio * terminates Visio
*/ */
public void quit() { public void quit() {
System.out.println("Received quit()"); System.out.println("Received quit()");
// there can't be any open documents for this to work // there can't be any open documents for this to work
// you'll get a visio error if you don't close them // you'll get a visio error if you don't close them
ActiveXComponent document = new ActiveXComponent(getProperty( ActiveXComponent document = new ActiveXComponent(getProperty(
"ActiveDocument").toDispatch()); "ActiveDocument").toDispatch());
document.invoke("Close"); document.invoke("Close");
invoke("Quit"); invoke("Quit");
} }
/** /**
* runs the Visio export command * runs the Visio export command
* *
* @param f * @param f
* @throws VisioException * @throws VisioException
*/ */
public void export(File f) throws VisioException { public void export(File f) throws VisioException {
try { try {
ActiveXComponent document = new ActiveXComponent(getProperty( ActiveXComponent document = new ActiveXComponent(getProperty(
"ActivePage").toDispatch()); "ActivePage").toDispatch());
Variant[] args = new Variant[1]; Variant[] args = new Variant[1];
args[0] = new Variant(f.getPath()); args[0] = new Variant(f.getPath());
document.invoke("Export", args); document.invoke("Export", args);
} catch (Exception e) { } catch (Exception e) {
throw new VisioException(e); throw new VisioException(e);
} }
} }
/** /**
* makes Visio visible so the user can watch * makes Visio visible so the user can watch
* *
* @param b * @param b
* @throws VisioException * @throws VisioException
*/ */
public void setVisible(boolean b) throws VisioException { public void setVisible(boolean b) throws VisioException {
try { try {
setProperty("Visible", new Variant(b)); setProperty("Visible", new Variant(b));
} catch (Exception e) { } catch (Exception e) {
throw new VisioException(e); throw new VisioException(e);
} }
} }
} }

View File

@@ -22,159 +22,159 @@ import java.io.OutputStream;
*/ */
public class VisioAppFacade { public class VisioAppFacade {
private VisioApp app; private VisioApp app;
private static VisioAppFacade instance; private static VisioAppFacade instance;
/** extension for image files */ /** extension for image files */
public static final String IMAGE_EXT = ".jpg"; public static final String IMAGE_EXT = ".jpg";
/** extension for visio files */ /** extension for visio files */
public static final String VISIO_EXT = ".vsd"; public static final String VISIO_EXT = ".vsd";
/** the buffer size when we want to read stuff in */ /** the buffer size when we want to read stuff in */
public static final int BUFFER_SIZE = 2048; public static final int BUFFER_SIZE = 2048;
/** /**
* Wrapper around Visio * Wrapper around Visio
* *
* @throws VisioException * @throws VisioException
*/ */
private VisioAppFacade() throws VisioException { private VisioAppFacade() throws VisioException {
this.app = new VisioApp(); this.app = new VisioApp();
app.addEventListener(new VisioEventAdapter(app)); app.addEventListener(new VisioEventAdapter(app));
} }
/** /**
* @return the singleton instance of Visio * @return the singleton instance of Visio
* @throws VisioException * @throws VisioException
*/ */
public static VisioAppFacade getInstance() throws VisioException { public static VisioAppFacade getInstance() throws VisioException {
if (instance == null) { if (instance == null) {
instance = new VisioAppFacade(); instance = new VisioAppFacade();
} }
return instance; return instance;
} }
/** /**
* creates a preview in a temp file and returns the raw data. * creates a preview in a temp file and returns the raw data.
* *
* @param visioData * @param visioData
* @return raw preview data * @return raw preview data
* @throws VisioException * @throws VisioException
*/ */
public byte[] createPreview(byte[] visioData) throws VisioException { public byte[] createPreview(byte[] visioData) throws VisioException {
byte[] preview; byte[] preview;
File tmpFile; File tmpFile;
try { try {
tmpFile = getTempVisioFile(); tmpFile = getTempVisioFile();
OutputStream out = new FileOutputStream(tmpFile); OutputStream out = new FileOutputStream(tmpFile);
out.write(visioData); out.write(visioData);
out.close(); out.close();
} catch (IOException ioe) { } catch (IOException ioe) {
throw new VisioException(ioe); throw new VisioException(ioe);
} }
preview = createPreview(tmpFile); preview = createPreview(tmpFile);
tmpFile.delete(); tmpFile.delete();
return preview; return preview;
} }
/** /**
* reads a preview from a saved file * reads a preview from a saved file
* *
* @param visioFile * @param visioFile
* @return raw preview data * @return raw preview data
* @throws VisioException * @throws VisioException
*/ */
public byte[] createPreview(File visioFile) throws VisioException { public byte[] createPreview(File visioFile) throws VisioException {
try { try {
File imageFile; File imageFile;
imageFile = getTempImageFile(); imageFile = getTempImageFile();
app.open(visioFile); app.open(visioFile);
app.export(imageFile); app.export(imageFile);
ByteArrayOutputStream bout = new ByteArrayOutputStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream();
FileInputStream fin = new FileInputStream(imageFile); FileInputStream fin = new FileInputStream(imageFile);
copy(fin, bout); copy(fin, bout);
fin.close(); fin.close();
imageFile.delete(); imageFile.delete();
bout.close(); bout.close();
return bout.toByteArray(); return bout.toByteArray();
} catch (IOException ioe) { } catch (IOException ioe) {
throw new VisioException(ioe); throw new VisioException(ioe);
} }
} }
private void copy(InputStream in, OutputStream out) throws IOException { private void copy(InputStream in, OutputStream out) throws IOException {
byte[] buff = new byte[BUFFER_SIZE]; byte[] buff = new byte[BUFFER_SIZE];
int read; int read;
do { do {
read = in.read(buff); read = in.read(buff);
if (read > 0) { if (read > 0) {
out.write(buff, 0, read); out.write(buff, 0, read);
} }
} while (read > 0); } while (read > 0);
} }
/** /**
* creates a preview from an input stream * creates a preview from an input stream
* *
* @param in * @param in
* @return byte contents of the preview stream * @return byte contents of the preview stream
* @throws VisioException * @throws VisioException
*/ */
public byte[] createPreview(InputStream in) throws VisioException { public byte[] createPreview(InputStream in) throws VisioException {
byte[] preview; byte[] preview;
// byte[] buff = new byte[2048]; // byte[] buff = new byte[2048];
// int read = 0; // int read = 0;
OutputStream out; OutputStream out;
File tmpFile; File tmpFile;
try { try {
tmpFile = getTempVisioFile(); tmpFile = getTempVisioFile();
out = new FileOutputStream(tmpFile); out = new FileOutputStream(tmpFile);
copy(in, out); copy(in, out);
out.close(); out.close();
} catch (IOException ioe) { } catch (IOException ioe) {
throw new VisioException(ioe); throw new VisioException(ioe);
} }
preview = createPreview(tmpFile); preview = createPreview(tmpFile);
tmpFile.delete(); tmpFile.delete();
return preview; return preview;
} }
/** /**
* opens the file in Visio and makes the editor visible * opens the file in Visio and makes the editor visible
* *
* @param f * @param f
* the reference to the Visio file to be opened * the reference to the Visio file to be opened
* @throws VisioException * @throws VisioException
*/ */
public void editDiagram(File f) throws VisioException { public void editDiagram(File f) throws VisioException {
app.open(f); app.open(f);
app.setVisible(true); app.setVisible(true);
} }
/** /**
* creates a temporary viso file * creates a temporary viso file
* *
* @return created visio temporary file * @return created visio temporary file
* @throws IOException * @throws IOException
*/ */
private File getTempVisioFile() throws IOException { private File getTempVisioFile() throws IOException {
return File.createTempFile("java", VISIO_EXT); return File.createTempFile("java", VISIO_EXT);
} }
/** /**
* creates a temporary image file and returns the File object * creates a temporary image file and returns the File object
* *
* @return the created image file object * @return the created image file object
* @throws IOException * @throws IOException
*/ */
private File getTempImageFile() throws IOException { private File getTempImageFile() throws IOException {
return File.createTempFile("java", IMAGE_EXT); return File.createTempFile("java", IMAGE_EXT);
} }
/** exit visio */ /** exit visio */
public void quit() { public void quit() {
app.quit(); app.quit();
instance = null; instance = null;
} }
} }

View File

@@ -32,166 +32,166 @@ import com.jacob.com.ComThread;
*/ */
public class VisioDemo extends JFrame implements ActionListener, WindowListener { public class VisioDemo extends JFrame implements ActionListener, WindowListener {
/** /**
* Totally dummy value to make Eclipse quit complaining * Totally dummy value to make Eclipse quit complaining
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
JButton chooseButton; JButton chooseButton;
JButton openButton; JButton openButton;
JPanel buttons; JPanel buttons;
ImageIcon theImage; ImageIcon theImage;
JLabel theLabel; // the icon on the page is actually this button's icon JLabel theLabel; // the icon on the page is actually this button's icon
File selectedFile; File selectedFile;
/** everyone should get this through getVisio() */ /** everyone should get this through getVisio() */
private VisioAppFacade visioProxy = null; private VisioAppFacade visioProxy = null;
// put this up here so it remembers where we were on the last choose // put this up here so it remembers where we were on the last choose
JFileChooser chooser = null; JFileChooser chooser = null;
public class VisioFileFilter extends FileFilter { public class VisioFileFilter extends FileFilter {
public boolean accept(File f) { public boolean accept(File f) {
if (f.isDirectory()) { if (f.isDirectory()) {
return true; return true;
} else { } else {
return (f.getName().toUpperCase().endsWith(".VSD")); return (f.getName().toUpperCase().endsWith(".VSD"));
} }
} }
public String getDescription() { public String getDescription() {
return "Visio Drawings"; return "Visio Drawings";
} }
} }
public VisioDemo() { public VisioDemo() {
super("Visio in Swing POC"); super("Visio in Swing POC");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttons = new JPanel(); buttons = new JPanel();
getContentPane().setLayout(new BorderLayout()); getContentPane().setLayout(new BorderLayout());
chooseButton = new JButton("Choose file to display"); chooseButton = new JButton("Choose file to display");
openButton = new JButton("Open file chosen file in Visio"); openButton = new JButton("Open file chosen file in Visio");
chooseButton.addActionListener(this); chooseButton.addActionListener(this);
openButton.addActionListener(this); openButton.addActionListener(this);
buttons.add(chooseButton); buttons.add(chooseButton);
buttons.add(openButton); buttons.add(openButton);
getContentPane().add(buttons, BorderLayout.SOUTH); getContentPane().add(buttons, BorderLayout.SOUTH);
theLabel = new JLabel(""); theLabel = new JLabel("");
getContentPane().add(theLabel, BorderLayout.CENTER); getContentPane().add(theLabel, BorderLayout.CENTER);
addWindowListener(this); addWindowListener(this);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setSize(640, 480); setSize(640, 480);
this.setVisible(true); this.setVisible(true);
} }
public static void main(String args[]) throws Exception { public static void main(String args[]) throws Exception {
SwingUtilities.invokeLater(new Runnable() { SwingUtilities.invokeLater(new Runnable() {
public void run() { public void run() {
ComThread.InitSTA(); ComThread.InitSTA();
VisioDemo poc = new VisioDemo(); VisioDemo poc = new VisioDemo();
ComThread.Release(); ComThread.Release();
if (poc == null) { if (poc == null) {
System.out.println("poc== null? That should never happen!"); System.out.println("poc== null? That should never happen!");
} }
} }
}); });
} }
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (e.getSource() == chooseButton) { if (e.getSource() == chooseButton) {
pickFile(); pickFile();
} else if (e.getSource() == openButton) { } else if (e.getSource() == openButton) {
try { try {
openFile(); openFile();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
} else { } else {
System.out.println("Awesome!"); System.out.println("Awesome!");
} }
} }
private void pickFile() { private void pickFile() {
try { try {
chooser = new JFileChooser(); chooser = new JFileChooser();
// comment this out if you want it to always go to myDocuments // comment this out if you want it to always go to myDocuments
chooser chooser
.setCurrentDirectory(new File(System .setCurrentDirectory(new File(System
.getProperty("user.dir"))); .getProperty("user.dir")));
chooser.setFileFilter(new VisioFileFilter()); chooser.setFileFilter(new VisioFileFilter());
int returnVal = chooser.showOpenDialog(this); int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) { if (returnVal == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile(); selectedFile = chooser.getSelectedFile();
showSelectedFilePreview(); showSelectedFilePreview();
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* use this private method instead of initializing on boot up so that * use this private method instead of initializing on boot up so that
* instance and all listeners are created in this thread (event thread) * instance and all listeners are created in this thread (event thread)
* rather than root thread * rather than root thread
* *
* @return * @return
*/ */
private VisioAppFacade getVisio() { private VisioAppFacade getVisio() {
if (visioProxy == null) { if (visioProxy == null) {
try { try {
visioProxy = VisioAppFacade.getInstance(); visioProxy = VisioAppFacade.getInstance();
} catch (VisioException ve) { } catch (VisioException ve) {
System.out.println("ailed to openFile()"); System.out.println("ailed to openFile()");
ve.printStackTrace(); ve.printStackTrace();
} }
} }
return visioProxy; return visioProxy;
} }
private void showSelectedFilePreview() throws VisioException { private void showSelectedFilePreview() throws VisioException {
if (selectedFile != null) { if (selectedFile != null) {
byte[] image = getVisio().createPreview(selectedFile); byte[] image = getVisio().createPreview(selectedFile);
theImage = new ImageIcon(image); theImage = new ImageIcon(image);
theLabel.setIcon(theImage); theLabel.setIcon(theImage);
} }
} }
private void openFile() throws VisioException { private void openFile() throws VisioException {
try { try {
getVisio().editDiagram(selectedFile); getVisio().editDiagram(selectedFile);
showSelectedFilePreview(); showSelectedFilePreview();
} catch (VisioException ve) { } catch (VisioException ve) {
System.out.println("ailed to openFile()"); System.out.println("ailed to openFile()");
ve.printStackTrace(); ve.printStackTrace();
} }
} }
public void windowActivated(WindowEvent e) { public void windowActivated(WindowEvent e) {
} }
public void windowClosed(WindowEvent e) { public void windowClosed(WindowEvent e) {
System.out.println("WINDOW CLOSED"); System.out.println("WINDOW CLOSED");
if (visioProxy != null) { if (visioProxy != null) {
visioProxy.quit(); visioProxy.quit();
} }
} }
public void windowClosing(WindowEvent e) { public void windowClosing(WindowEvent e) {
} }
public void windowDeactivated(WindowEvent e) { public void windowDeactivated(WindowEvent e) {
} }
public void windowDeiconified(WindowEvent e) { public void windowDeiconified(WindowEvent e) {
} }
public void windowIconified(WindowEvent e) { public void windowIconified(WindowEvent e) {
System.out.println("Fooboo"); System.out.println("Fooboo");
} }
public void windowOpened(WindowEvent e) { public void windowOpened(WindowEvent e) {
} }
} }

View File

@@ -13,56 +13,56 @@ import com.jacob.com.Variant;
*/ */
public class VisioEventAdapter implements VisioEventListener { public class VisioEventAdapter implements VisioEventListener {
VisioApp app = null; VisioApp app = null;
public VisioEventAdapter(VisioApp pApp) { public VisioEventAdapter(VisioApp pApp) {
app = pApp; app = pApp;
System.out.println("Event listener constructed"); System.out.println("Event listener constructed");
} }
public void BeforeQuit(Variant[] args) { public void BeforeQuit(Variant[] args) {
} }
public void DocumentChanged(Variant[] args) { public void DocumentChanged(Variant[] args) {
System.out.println("documentChanged()"); System.out.println("documentChanged()");
} }
public void DocumentCloseCanceled(Variant[] args) { public void DocumentCloseCanceled(Variant[] args) {
} }
public void DocumentCreated(Variant[] args) { public void DocumentCreated(Variant[] args) {
} }
public void DocumentOpened(Variant[] args) { public void DocumentOpened(Variant[] args) {
System.out.println("DocumentOpened()"); System.out.println("DocumentOpened()");
} }
public void DocumentSaved(Variant[] args) { public void DocumentSaved(Variant[] args) {
} }
public void DocumentSavedAs(Variant[] args) { public void DocumentSavedAs(Variant[] args) {
} }
public Variant QueryCancelDocumentClose(Variant[] args) { public Variant QueryCancelDocumentClose(Variant[] args) {
System.out.println("QueryCancelDocumentClose()"); System.out.println("QueryCancelDocumentClose()");
return new Variant(false); return new Variant(false);
} }
/** /**
* we don't actually let it quit. We block it so that we don't have to * we don't actually let it quit. We block it so that we don't have to
* relaunch when we look at a new document * relaunch when we look at a new document
*/ */
public Variant QueryCancelQuit(Variant[] args) { public Variant QueryCancelQuit(Variant[] args) {
// these may throw VisioException // these may throw VisioException
System.out System.out
.println("Saving document, hiding and telling visio not to quit"); .println("Saving document, hiding and telling visio not to quit");
try { try {
app.save(); app.save();
app.setVisible(false); app.setVisible(false);
} catch (VisioException ve) { } catch (VisioException ve) {
System.out.println("ailed to openFile()"); System.out.println("ailed to openFile()");
ve.printStackTrace(); ve.printStackTrace();
} }
return new Variant(true); return new Variant(true);
} }
} }

View File

@@ -15,19 +15,19 @@ import com.jacob.com.Variant;
*/ */
public interface VisioEventListener { public interface VisioEventListener {
public void BeforeQuit(Variant[] args); public void BeforeQuit(Variant[] args);
public void DocumentChanged(Variant[] args); public void DocumentChanged(Variant[] args);
public void DocumentCloseCanceled(Variant[] args); public void DocumentCloseCanceled(Variant[] args);
public void DocumentCreated(Variant[] args); public void DocumentCreated(Variant[] args);
public void DocumentOpened(Variant[] args); public void DocumentOpened(Variant[] args);
public void DocumentSaved(Variant[] args); public void DocumentSaved(Variant[] args);
public void DocumentSavedAs(Variant[] args); public void DocumentSavedAs(Variant[] args);
public Variant QueryCancelQuit(Variant[] args); public Variant QueryCancelQuit(Variant[] args);
} }

View File

@@ -10,16 +10,16 @@ package com.jacob.samples.visio;
* blocks everywhere * blocks everywhere
*/ */
public class VisioException extends Exception { public class VisioException extends Exception {
/** /**
* Totally dummy value to make Eclipse quit complaining * Totally dummy value to make Eclipse quit complaining
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public VisioException(String msg) { public VisioException(String msg) {
super(msg); super(msg);
} }
public VisioException(Throwable cause) { public VisioException(Throwable cause) {
super(cause); super(cause);
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -51,105 +51,105 @@ import com.jacob.test.BaseTestCase;
*/ */
public class ActiveXComponentFactoryTest extends BaseTestCase { public class ActiveXComponentFactoryTest extends BaseTestCase {
/** /**
* This test is supposed to verify we get multiple instances when we mean * 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 * too. Unfortunately, it requires that the runner of the test verify via
* the "Windows Task Manager" * the "Windows Task Manager"
*/ */
public void testMultipleInstances() { public void testMultipleInstances() {
ComThread.InitMTA(); ComThread.InitMTA();
String mApplicationId = "Word.Application"; String mApplicationId = "Word.Application";
ActiveXComponent instance1 = ActiveXComponent ActiveXComponent instance1 = ActiveXComponent
.createNewInstance(mApplicationId); .createNewInstance(mApplicationId);
ActiveXComponent instance2 = ActiveXComponent ActiveXComponent instance2 = ActiveXComponent
.createNewInstance(mApplicationId); .createNewInstance(mApplicationId);
try { try {
Thread.sleep(10000); Thread.sleep(10000);
} catch (InterruptedException ie) { } catch (InterruptedException ie) {
} }
instance1.invoke("Quit", new Variant[] {}); instance1.invoke("Quit", new Variant[] {});
instance2.invoke("Quit", new Variant[] {}); instance2.invoke("Quit", new Variant[] {});
ComThread.Release(); ComThread.Release();
} }
/** /**
* This test is supposed to verify we can force multiple items through a * This test is supposed to verify we can force multiple items through a
* single running instance. It requires that a user physically watch the * single running instance. It requires that a user physically watch the
* "Windows Task Manager" to verify only one copy of MS Word is executing * "Windows Task Manager" to verify only one copy of MS Word is executing
*/ */
public void testOnlyOneInstance() { public void testOnlyOneInstance() {
ComThread.InitMTA(); ComThread.InitMTA();
String mApplicationId = "Word.Application"; String mApplicationId = "Word.Application";
ActiveXComponent instance1 = new ActiveXComponent(mApplicationId); ActiveXComponent instance1 = new ActiveXComponent(mApplicationId);
ActiveXComponent instance2 = ActiveXComponent ActiveXComponent instance2 = ActiveXComponent
.connectToActiveInstance(mApplicationId); .connectToActiveInstance(mApplicationId);
assertNotNull(instance2); assertNotNull(instance2);
try { try {
Thread.sleep(10000); Thread.sleep(10000);
} catch (InterruptedException ie) { } catch (InterruptedException ie) {
} }
instance1.invoke("Quit", new Variant[] {}); instance1.invoke("Quit", new Variant[] {});
ComThread.Release(); ComThread.Release();
} }
/** /**
* Test that verifies function of the ActiveXComponentFactory * Test that verifies function of the ActiveXComponentFactory
*/ */
public void testActiveXComponentFactory() { public void testActiveXComponentFactory() {
ComThread.InitSTA(true); ComThread.InitSTA(true);
try { try {
System.out System.out
.println("This test only works if MS Word is NOT already running"); .println("This test only works if MS Word is NOT already running");
String mApplicationId = "Word.Application"; String mApplicationId = "Word.Application";
ActiveXComponent mTryConnectingFirst = ActiveXComponent ActiveXComponent mTryConnectingFirst = ActiveXComponent
.connectToActiveInstance(mApplicationId); .connectToActiveInstance(mApplicationId);
if (mTryConnectingFirst != null) { if (mTryConnectingFirst != null) {
mTryConnectingFirst.invoke("Quit", new Variant[] {}); mTryConnectingFirst.invoke("Quit", new Variant[] {});
System.out System.out
.println("Was able to connect to MSWord when hadn't started it"); .println("Was able to connect to MSWord when hadn't started it");
} else { } else {
System.out System.out
.println("Correctly could not connect to running MSWord"); .println("Correctly could not connect to running MSWord");
} }
System.out.println(" Word Starting"); System.out.println(" Word Starting");
ActiveXComponent mTryStartingSecond = ActiveXComponent ActiveXComponent mTryStartingSecond = ActiveXComponent
.createNewInstance(mApplicationId); .createNewInstance(mApplicationId);
if (mTryStartingSecond == null) { if (mTryStartingSecond == null) {
System.out.println("was unable to start up MSWord "); System.out.println("was unable to start up MSWord ");
} else { } else {
System.out.println("Correctly could start MSWord"); System.out.println("Correctly could start MSWord");
} }
ActiveXComponent mTryConnectingThird = ActiveXComponent ActiveXComponent mTryConnectingThird = ActiveXComponent
.connectToActiveInstance(mApplicationId); .connectToActiveInstance(mApplicationId);
if (mTryConnectingThird == null) { if (mTryConnectingThird == null) {
fail("Was unable able to connect to MSWord after previous startup"); fail("Was unable able to connect to MSWord after previous startup");
} else { } else {
System.out.println("Stopping MSWord"); System.out.println("Stopping MSWord");
// stop it so we can fail trying to connect to a running // stop it so we can fail trying to connect to a running
mTryConnectingThird.invoke("Quit", new Variant[] {}); mTryConnectingThird.invoke("Quit", new Variant[] {});
} }
Thread.sleep(2000); Thread.sleep(2000);
ActiveXComponent mTryConnectingFourth = ActiveXComponent ActiveXComponent mTryConnectingFourth = ActiveXComponent
.connectToActiveInstance(mApplicationId); .connectToActiveInstance(mApplicationId);
if (mTryConnectingFourth != null) { if (mTryConnectingFourth != null) {
mTryConnectingFourth.invoke("Quit", new Variant[] {}); mTryConnectingFourth.invoke("Quit", new Variant[] {});
fail("Was able to connect to MSWord that was stopped"); fail("Was able to connect to MSWord that was stopped");
} else { } else {
System.out System.out
.println("Correctly could not connect to running MSWord"); .println("Correctly could not connect to running MSWord");
} }
} catch (InterruptedException ie) { } catch (InterruptedException ie) {
} catch (ComException e) { } catch (ComException e) {
e.printStackTrace(); e.printStackTrace();
fail("Caught COM exception"); fail("Caught COM exception");
} finally { } finally {
// System.out.println("About to sleep for 2 seconds so we can bask // System.out.println("About to sleep for 2 seconds so we can bask
// in the glory of this success"); // in the glory of this success");
// Thread.sleep(2000); // Thread.sleep(2000);
ComThread.Release(); ComThread.Release();
ComThread.quitMainSTA(); ComThread.quitMainSTA();
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -53,39 +53,39 @@ import junit.framework.TestCase;
public class DateUtilitiesTest extends TestCase { public class DateUtilitiesTest extends TestCase {
/** /**
* verify date conversion to and from java * verify date conversion to and from java
*/ */
public void testDateUtilities() { public void testDateUtilities() {
Date now = new Date(); Date now = new Date();
double comTimeForNow = DateUtilities.convertDateToWindowsTime(now); double comTimeForNow = DateUtilities.convertDateToWindowsTime(now);
Date retrievedNow = DateUtilities Date retrievedNow = DateUtilities
.convertWindowsTimeToDate(comTimeForNow); .convertWindowsTimeToDate(comTimeForNow);
if (!now.equals(retrievedNow)) { if (!now.equals(retrievedNow)) {
fail("DateUtilities Date Test failed " + now + " != " fail("DateUtilities Date Test failed " + now + " != "
+ retrievedNow); + retrievedNow);
} else { } else {
System.out.println("DateUtilities Date Test passed"); System.out.println("DateUtilities Date Test passed");
} }
} }
/** /**
* Verify that the start of time is when we think it is. * Verify that the start of time is when we think it is.
*/ */
public void testBeginningOfWindowsTime() { public void testBeginningOfWindowsTime() {
// this is a magic time in the windows world // this is a magic time in the windows world
Date beginningOfWindowsTime = new GregorianCalendar(1899, Date beginningOfWindowsTime = new GregorianCalendar(1899,
Calendar.DECEMBER, 30).getTime(); Calendar.DECEMBER, 30).getTime();
double comTimeForBeginningOfWindowsTime = DateUtilities double comTimeForBeginningOfWindowsTime = DateUtilities
.convertDateToWindowsTime(beginningOfWindowsTime); .convertDateToWindowsTime(beginningOfWindowsTime);
if (comTimeForBeginningOfWindowsTime > 0) { if (comTimeForBeginningOfWindowsTime > 0) {
fail("Beginning of windows time test failed " fail("Beginning of windows time test failed "
+ comTimeForBeginningOfWindowsTime); + comTimeForBeginningOfWindowsTime);
} else { } else {
System.out.println("Beginning of windows time test passed"); System.out.println("Beginning of windows time test passed");
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -51,25 +51,25 @@ import com.jacob.test.BaseTestCase;
*/ */
public class DispatchNullProgramId extends BaseTestCase { public class DispatchNullProgramId extends BaseTestCase {
/** /**
* Verify that dispatch constructors are protected from null program ids. * Verify that dispatch constructors are protected from null program ids.
*/ */
public void testNullProgramId() { public void testNullProgramId() {
try { try {
String nullParam = null; String nullParam = null;
new Dispatch(nullParam); new Dispatch(nullParam);
fail("the dispatch failed to protect itself from null program ids"); fail("the dispatch failed to protect itself from null program ids");
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
System.out System.out
.println("the dispatch protected itself from null program ids"); .println("the dispatch protected itself from null program ids");
} }
try { try {
String nullParam = ""; String nullParam = "";
new Dispatch(nullParam); new Dispatch(nullParam);
fail("the dispatch failed to protect itself from empty string program ids"); fail("the dispatch failed to protect itself from empty string program ids");
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
System.out System.out
.println("the dispatch protected itself from empty string program ids"); .println("the dispatch protected itself from empty string program ids");
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -50,22 +50,22 @@ import com.jacob.test.BaseTestCase;
*/ */
public class DispatchTest extends BaseTestCase { public class DispatchTest extends BaseTestCase {
/** /**
* Verify this detects word's exit * Verify this detects word's exit
*/ */
public void testDispatchHasExited() { public void testDispatchHasExited() {
String pid = "Word.Application"; String pid = "Word.Application";
ActiveXComponent axc = new ActiveXComponent(pid); ActiveXComponent axc = new ActiveXComponent(pid);
assertEquals(0, Dispatch.hasExited(axc)); assertEquals(0, Dispatch.hasExited(axc));
axc.invoke("Quit", new Variant[] {}); axc.invoke("Quit", new Variant[] {});
// should take some amount of time for Word to Quit so should = !exited // should take some amount of time for Word to Quit so should = !exited
assertEquals(0, Dispatch.hasExited(axc)); assertEquals(0, Dispatch.hasExited(axc));
try { try {
// sleep some reasonable amount of time waiting for it to quit // sleep some reasonable amount of time waiting for it to quit
Thread.sleep(2000); Thread.sleep(2000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
fail("should not have been interrupted"); fail("should not have been interrupted");
} }
assertEquals(1, Dispatch.hasExited(axc)); assertEquals(1, Dispatch.hasExited(axc));
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -49,31 +49,31 @@ import com.jacob.test.BaseTestCase;
*/ */
public class DispatchValidDispatchTest extends BaseTestCase { public class DispatchValidDispatchTest extends BaseTestCase {
/** /**
* force an IllegalArgumentException to verify the utility method throws * force an IllegalArgumentException to verify the utility method throws
* correctly. * correctly.
*/ */
public void testThrowIllegalArgumentException() { public void testThrowIllegalArgumentException() {
try { try {
Dispatch.call(null, 0); Dispatch.call(null, 0);
fail("Failed to throw IllegalArgumentException"); fail("Failed to throw IllegalArgumentException");
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
System.out.println("Caught correct IllegalArgumentException: " System.out.println("Caught correct IllegalArgumentException: "
+ iae); + iae);
} }
} }
/** /**
* force an IllegalStateException to verify the utility method throws * force an IllegalStateException to verify the utility method throws
* correctly. * correctly.
*/ */
public void testThrowIllegalStateException() { public void testThrowIllegalStateException() {
try { try {
Dispatch foo = new Dispatch(); Dispatch foo = new Dispatch();
Dispatch.call(foo, 0); Dispatch.call(foo, 0);
fail("Failed to throw IllegalStateException"); fail("Failed to throw IllegalStateException");
} catch (IllegalStateException ise) { } catch (IllegalStateException ise) {
System.out.println("Caught correct IllegalStateException " + ise); System.out.println("Caught correct IllegalStateException " + ise);
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -60,99 +60,99 @@ import com.jacob.test.BaseTestCase;
* *
*/ */
public class JacobDeadlockTest extends BaseTestCase { public class JacobDeadlockTest extends BaseTestCase {
private static final long TIMEOUT = 5000l; private static final long TIMEOUT = 5000l;
/** Thread component */ /** Thread component */
public static class TestThread extends Thread { public static class TestThread extends Thread {
private final int id; private final int id;
private final boolean initCOM; private final boolean initCOM;
private final boolean writeOutput; private final boolean writeOutput;
/** /**
* constructor for ThestThread * constructor for ThestThread
* *
* @param id * @param id
* @param initCOM * @param initCOM
* @param writeOutput * @param writeOutput
* *
*/ */
public TestThread(int id, boolean initCOM, boolean writeOutput) { public TestThread(int id, boolean initCOM, boolean writeOutput) {
this.id = id; this.id = id;
this.initCOM = initCOM; this.initCOM = initCOM;
this.writeOutput = writeOutput; this.writeOutput = writeOutput;
} }
@Override @Override
public void run() { public void run() {
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
log("iteration " + i); log("iteration " + i);
if (initCOM) { if (initCOM) {
log("Initializing COM thread"); log("Initializing COM thread");
ComThread.InitMTA(false); ComThread.InitMTA(false);
} }
log("Creating JacobObject"); log("Creating JacobObject");
new JacobObject(); new JacobObject();
log("Releasing COM thread"); log("Releasing COM thread");
ComThread.Release(); ComThread.Release();
} }
log("Exiting Java Thread"); log("Exiting Java Thread");
} }
private void log(String message) { private void log(String message) {
if (writeOutput) { if (writeOutput) {
System.out.println(Thread.currentThread().getName() System.out.println(Thread.currentThread().getName()
+ ": TestThread[" + id + "] " + " " + " - " + message); + ": TestThread[" + id + "] " + " " + " - " + message);
} }
} }
} }
/** /**
* This test shows that if ComThread.Init() is called explicitly, no problem * This test shows that if ComThread.Init() is called explicitly, no problem
* occurs. * occurs.
* *
* @throws InterruptedException * @throws InterruptedException
*/ */
public void testShowNoProblemIfCOMIsInitialized() public void testShowNoProblemIfCOMIsInitialized()
throws InterruptedException { throws InterruptedException {
runTest(2, true, false); runTest(2, true, false);
runTest(100, true, false); runTest(100, true, false);
} }
/** /**
* This test shows that if only one thread is creating COM objects, no * This test shows that if only one thread is creating COM objects, no
* problem occurs. * problem occurs.
* *
* @throws InterruptedException * @throws InterruptedException
*/ */
public void testShowNoProblemIfSingleThreaded() throws InterruptedException { public void testShowNoProblemIfSingleThreaded() throws InterruptedException {
runTest(1, false, false); runTest(1, false, false);
runTest(1, true, false); runTest(1, true, false);
} }
/** /**
* Runs the test with two threads, which don't initialize the COM thread. * Runs the test with two threads, which don't initialize the COM thread.
* *
* This test will always fail. * This test will always fail.
* *
* @throws InterruptedException * @throws InterruptedException
*/ */
public void testShowDeadlockProblem() throws InterruptedException { public void testShowDeadlockProblem() throws InterruptedException {
runTest(2, false, true); runTest(2, false, true);
} }
private void runTest(int numberOfThreads, boolean initCOM, private void runTest(int numberOfThreads, boolean initCOM,
boolean writeOutput) throws InterruptedException { boolean writeOutput) throws InterruptedException {
Thread[] threads = new Thread[numberOfThreads]; Thread[] threads = new Thread[numberOfThreads];
for (int i = 0; i < threads.length; i++) { for (int i = 0; i < threads.length; i++) {
threads[i] = new TestThread(i, initCOM, writeOutput); threads[i] = new TestThread(i, initCOM, writeOutput);
threads[i].start(); threads[i].start();
} }
for (int i = 0; i < threads.length; i++) { for (int i = 0; i < threads.length; i++) {
threads[i].join(TIMEOUT); threads[i].join(TIMEOUT);
if (threads[i].isAlive()) { if (threads[i].isAlive()) {
fail("thread " + i + " failed to finish in " + TIMEOUT fail("thread " + i + " failed to finish in " + TIMEOUT
+ " milliseconds"); + " milliseconds");
} }
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -49,12 +49,12 @@ import com.jacob.test.BaseTestCase;
*/ */
public class JacobObjectTest extends BaseTestCase { public class JacobObjectTest extends BaseTestCase {
/** /**
* verify the build version and date functions work correctly * verify the build version and date functions work correctly
*/ */
public void testBuildVersion() { public void testBuildVersion() {
System.out.println("build version is " + JacobReleaseInfo.getBuildVersion()); System.out.println("build version is " + JacobReleaseInfo.getBuildVersion());
System.out.println("build date is " + JacobReleaseInfo.getBuildDate()); System.out.println("build date is " + JacobReleaseInfo.getBuildDate());
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -52,109 +52,109 @@ import com.jacob.test.BaseTestCase;
*/ */
public class ROT2Test extends BaseTestCase { public class ROT2Test extends BaseTestCase {
/** /**
* runs a multi-threaded test * runs a multi-threaded test
*/ */
public void testDoesNotBlowUp() { public void testDoesNotBlowUp() {
ROT2TestThread threads[] = new ROT2TestThread[4]; ROT2TestThread threads[] = new ROT2TestThread[4];
for (int i = 0; i < threads.length; i++) { for (int i = 0; i < threads.length; i++) {
threads[i] = new ROT2TestThread("thread-" + i, 3000); threads[i] = new ROT2TestThread("thread-" + i, 3000);
} }
for (int i = 0; i < threads.length; i++) { for (int i = 0; i < threads.length; i++) {
threads[i].start(); threads[i].start();
} }
} }
/** /**
* This will try and exercise the thread support in the ROT * This will try and exercise the thread support in the ROT
*/ */
public class ROT2TestThread extends Thread { public class ROT2TestThread extends Thread {
private java.util.List<Variant> ThreadObjects; private java.util.List<Variant> ThreadObjects;
private int initialRunSize = 0; private int initialRunSize = 0;
/** /**
* @param arg0 * @param arg0
* @param iStartCount * @param iStartCount
* the initial number of threads * the initial number of threads
*/ */
public ROT2TestThread(String arg0, int iStartCount) { public ROT2TestThread(String arg0, int iStartCount) {
super(arg0); super(arg0);
initialRunSize = iStartCount; initialRunSize = iStartCount;
} }
/** /**
* A semi-complex series of steps to put the ROT under stress. 1) * A semi-complex series of steps to put the ROT under stress. 1)
* discard half the objects we've created 2) if size is greater than 1 * 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. * but not a even number, add 1 new object 3) stop when size is 1.
* *
* @see java.lang.Runnable#run() * @see java.lang.Runnable#run()
*/ */
public void run() { public void run() {
// something that keeps object references around // something that keeps object references around
// so the gc can't collect them // so the gc can't collect them
// we need to create these in the thread so they end up in the right // we need to create these in the thread so they end up in the right
// ROT table // ROT table
ThreadObjects = new java.util.ArrayList<Variant>(initialRunSize); ThreadObjects = new java.util.ArrayList<Variant>(initialRunSize);
for (int i = 0; i < initialRunSize; i++) { for (int i = 0; i < initialRunSize; i++) {
// create the object // create the object
Variant aNewVariant = new Variant(getName() + "_" + i); Variant aNewVariant = new Variant(getName() + "_" + i);
// create a hard reference to it // create a hard reference to it
ThreadObjects.add(aNewVariant); ThreadObjects.add(aNewVariant);
} }
while (ThreadObjects.size() > 1) { while (ThreadObjects.size() > 1) {
String message = ""; String message = "";
message = getName() + " Workingset=" + ThreadObjects.size() message = getName() + " Workingset=" + ThreadObjects.size()
+ " ROT: "; + " ROT: ";
message += "(before additions and gc " message += "(before additions and gc "
+ ROT.getThreadObjects(false).size() + ")"; + ROT.getThreadObjects(false).size() + ")";
// if there is an odd number of objects greater than 2 // if there is an odd number of objects greater than 2
if (ThreadObjects.size() > 2 && ThreadObjects.size() % 2 != 0) { if (ThreadObjects.size() > 2 && ThreadObjects.size() % 2 != 0) {
// add a new object // add a new object
Variant aNewVariant = new Variant(getName() + "_*" Variant aNewVariant = new Variant(getName() + "_*"
+ ThreadObjects.size()); + ThreadObjects.size());
ThreadObjects.add(aNewVariant); ThreadObjects.add(aNewVariant);
} }
// now iterate across all the objects in our list // now iterate across all the objects in our list
for (int i = ThreadObjects.size(); i > 0; i--) { for (int i = ThreadObjects.size(); i > 0; i--) {
// removing every other one? // removing every other one?
if (i % 2 == 0) { if (i % 2 == 0) {
// remove the reference so gc can get it // remove the reference so gc can get it
ThreadObjects.remove(i - 1); ThreadObjects.remove(i - 1);
} }
} }
try { try {
// simulate the system under load and run the GC // simulate the system under load and run the GC
// should end up with weak references with no objects // should end up with weak references with no objects
// attached // attached
Thread.sleep(9); Thread.sleep(9);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// the VM doesn't want us to sleep anymore, // the VM doesn't want us to sleep anymore,
// so get back to work // so get back to work
} }
message += " (before gc, after additions " message += " (before gc, after additions "
+ ROT.getThreadObjects(false).size() + ")"; + ROT.getThreadObjects(false).size() + ")";
System.gc(); System.gc();
message += " (after System.gc " message += " (after System.gc "
+ ROT.getThreadObjects(false).size() + ")"; + ROT.getThreadObjects(false).size() + ")";
System.out.println(message); System.out.println(message);
} }
} }
/** /**
* Another test would be to override this to always return the same * Another test would be to override this to always return the same
* name. That would really screw the ROT! * name. That would really screw the ROT!
* *
* @see java.lang.Object#toString() * @see java.lang.Object#toString()
*/ */
public String toString() { public String toString() {
return super.toString(); return super.toString();
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -54,126 +54,126 @@ import com.jacob.test.BaseTestCase;
*/ */
public class ROT3Test extends BaseTestCase { public class ROT3Test extends BaseTestCase {
/** /**
* runs a multi-threaded test * runs a multi-threaded test
*/ */
public void testROTVersion3() { public void testROTVersion3() {
ROT3TestThread threads[] = new ROT3TestThread[4]; ROT3TestThread threads[] = new ROT3TestThread[4];
for (int i = 0; i < threads.length; i++) { for (int i = 0; i < threads.length; i++) {
threads[i] = new ROT3TestThread("thread-" + i, 3000 + i * 10); threads[i] = new ROT3TestThread("thread-" + i, 3000 + i * 10);
} }
for (int i = 0; i < threads.length; i++) { for (int i = 0; i < threads.length; i++) {
threads[i].start(); threads[i].start();
} }
} }
/** /**
* This will try and exercise the thread support in the ROT * This will try and exercise the thread support in the ROT
*/ */
public class ROT3TestThread extends Thread { public class ROT3TestThread extends Thread {
private java.util.List<Variant> variansCreatedInThisThread; private java.util.List<Variant> variansCreatedInThisThread;
private int initialRunSize = 0; private int initialRunSize = 0;
/** /**
* @param arg0 * @param arg0
* @param iStartCount * @param iStartCount
* the number of initial threads * the number of initial threads
*/ */
public ROT3TestThread(String arg0, int iStartCount) { public ROT3TestThread(String arg0, int iStartCount) {
super(arg0); super(arg0);
initialRunSize = iStartCount; initialRunSize = iStartCount;
} }
/** /**
* A semi-complex series of steps to put the ROT under stress. 1) * A semi-complex series of steps to put the ROT under stress. 1)
* discard half the objects we've created 2) if size is greater than 1 * 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. * but not a even number, add 1 new object 3) stop when size is 1.
* *
* @see java.lang.Runnable#run() * @see java.lang.Runnable#run()
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void run() { public void run() {
// something that keeps object references around // something that keeps object references around
// so the gc can't collect them // so the gc can't collect them
// we need to create these in the thread so they end up in the right // we need to create these in the thread so they end up in the right
// ROT table // ROT table
variansCreatedInThisThread = new java.util.ArrayList<Variant>( variansCreatedInThisThread = new java.util.ArrayList<Variant>(
initialRunSize); initialRunSize);
for (int i = 0; i < initialRunSize; i++) { for (int i = 0; i < initialRunSize; i++) {
// create the object // create the object
Variant aNewVariant = new Variant(getName() + "_" + i); Variant aNewVariant = new Variant(getName() + "_" + i);
// create a hard reference to it // create a hard reference to it
variansCreatedInThisThread.add(aNewVariant); variansCreatedInThisThread.add(aNewVariant);
} }
while (variansCreatedInThisThread.size() > 1) { while (variansCreatedInThisThread.size() > 1) {
String message = ""; String message = "";
message = getName() + " Workingset=" message = getName() + " Workingset="
+ variansCreatedInThisThread.size() + variansCreatedInThisThread.size()
+ " ROT threadObject hashCode: " + " ROT threadObject hashCode: "
+ ROT.getThreadObjects(true).hashCode(); + ROT.getThreadObjects(true).hashCode();
message += " size before mods and gc " message += " size before mods and gc "
+ ROT.getThreadObjects(true).size() + ")"; + ROT.getThreadObjects(true).size() + ")";
// If there are more than 10 objects in our cache then add 1/4 // If there are more than 10 objects in our cache then add 1/4
// of that again // of that again
if (variansCreatedInThisThread.size() > 10) { if (variansCreatedInThisThread.size() > 10) {
message += " (adding) "; message += " (adding) ";
// add an additional 1/4 of our current number // add an additional 1/4 of our current number
for (int i = 0; i < variansCreatedInThisThread.size() / 4; i++) { for (int i = 0; i < variansCreatedInThisThread.size() / 4; i++) {
// add a new object // add a new object
Variant aNewVariant = new Variant(getName() + "_*" Variant aNewVariant = new Variant(getName() + "_*"
+ variansCreatedInThisThread.size()); + variansCreatedInThisThread.size());
variansCreatedInThisThread.add(aNewVariant); variansCreatedInThisThread.add(aNewVariant);
} }
} }
// now iterate across 1/2 the objects in our list // now iterate across 1/2 the objects in our list
message += " (removing) "; message += " (removing) ";
for (int i = variansCreatedInThisThread.size(); i > 0; i--) { for (int i = variansCreatedInThisThread.size(); i > 0; i--) {
// removing every other one? // removing every other one?
if (i % 2 == 0) { if (i % 2 == 0) {
// remove the reference so gc can get it // remove the reference so gc can get it
if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) { if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) {
// uses deprecated API to set up a special situation // uses deprecated API to set up a special situation
// because this is an ROT test // because this is an ROT test
ROT.removeObject(variansCreatedInThisThread ROT.removeObject(variansCreatedInThisThread
.get(i - 1)); .get(i - 1));
} }
variansCreatedInThisThread.remove(i - 1); variansCreatedInThisThread.remove(i - 1);
} }
} }
message += " (after mods " + ROT.getThreadObjects(true).size() message += " (after mods " + ROT.getThreadObjects(true).size()
+ ")"; + ")";
// comm // comm
if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) { if (!ROT.USE_AUTOMATIC_GARBAGE_COLLECTION) {
ROT.clearObjects(); ROT.clearObjects();
} }
System.gc(); System.gc();
try { try {
// vain attempt at letting the gc run // vain attempt at letting the gc run
Thread.sleep(200); Thread.sleep(200);
} catch (InterruptedException ie) { } catch (InterruptedException ie) {
} }
message += " (after gc " + ROT.getThreadObjects(true).size() message += " (after gc " + ROT.getThreadObjects(true).size()
+ ")"; + ")";
message += " Should see GC if debug turned on..."; message += " Should see GC if debug turned on...";
System.out.println(message); System.out.println(message);
} }
} }
/** /**
* Another test would be to overide this to always return the same name. * Another test would be to overide this to always return the same name.
* That would really screw the ROT! * That would really screw the ROT!
* *
* @see java.lang.Object#toString() * @see java.lang.Object#toString()
*/ */
public String toString() { public String toString() {
return super.toString(); return super.toString();
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -51,121 +51,121 @@ import com.jacob.test.BaseTestCase;
*/ */
public class ROTTest extends BaseTestCase { public class ROTTest extends BaseTestCase {
/** /**
* verify the SystemProperty (classname).PutInROT functions as expected. A * 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 * value of false means instances of the class are not put in the ROT Any o
* ther value means they are * ther value means they are
*/ */
public void testDontFillROTSystemProperty() { public void testDontFillROTSystemProperty() {
debug("testDontFillROTSystemProperty: started"); debug("testDontFillROTSystemProperty: started");
// Make sure the class is loaded before running any of the tests // 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 // class to load and any pre-defined Variants (FALSE and TRUE) to be
// created immediately // created immediately
VariantViaEvent.class.getName(); VariantViaEvent.class.getName();
if (ROT.getThreadObjects(true).entrySet().size() < 1) { if (ROT.getThreadObjects(true).entrySet().size() < 1) {
debug("Failure: ROT should have objects in it as soon as Variant class loaded."); debug("Failure: ROT should have objects in it as soon as Variant class loaded.");
} }
System.setProperty(VariantViaEvent.class.getName() System.setProperty(VariantViaEvent.class.getName()
+ ROT.PUT_IN_ROT_SUFFIX, "false"); + ROT.PUT_IN_ROT_SUFFIX, "false");
int countPriorToTest = ROT.getThreadObjects(true).entrySet().size(); int countPriorToTest = ROT.getThreadObjects(true).entrySet().size();
new VariantViaEvent(); new VariantViaEvent();
int countAfterAddWithoutROT = ROT.getThreadObjects(true).entrySet() int countAfterAddWithoutROT = ROT.getThreadObjects(true).entrySet()
.size(); .size();
if (countAfterAddWithoutROT != countPriorToTest) { if (countAfterAddWithoutROT != countPriorToTest) {
debug("Failure: count prior: " + countPriorToTest debug("Failure: count prior: " + countPriorToTest
+ " and count after without ROT was: " + " and count after without ROT was: "
+ countAfterAddWithoutROT); + countAfterAddWithoutROT);
} }
System.setProperty(VariantViaEvent.class.getName() System.setProperty(VariantViaEvent.class.getName()
+ ROT.PUT_IN_ROT_SUFFIX, "true"); + ROT.PUT_IN_ROT_SUFFIX, "true");
new VariantViaEvent(); new VariantViaEvent();
int countAfterAddWithROT = ROT.getThreadObjects(true).entrySet().size(); int countAfterAddWithROT = ROT.getThreadObjects(true).entrySet().size();
if (countAfterAddWithROT != (countPriorToTest + 1)) { if (countAfterAddWithROT != (countPriorToTest + 1)) {
debug("Failure: count prior: " + countPriorToTest debug("Failure: count prior: " + countPriorToTest
+ " and count after with ROT was: " + countAfterAddWithROT); + " and count after with ROT was: " + countAfterAddWithROT);
} }
debug("testDontFillROTSystemProperty: completed"); debug("testDontFillROTSystemProperty: completed");
} }
/** /**
* Needs documentation. This test looks broken * Needs documentation. This test looks broken
* *
*/ */
public void testGCBehavior() { public void testGCBehavior() {
int sizeBeforeBuild = 0; int sizeBeforeBuild = 0;
int sizeAfterBuild = 0; int sizeAfterBuild = 0;
int sizeBeforeGC = 0; int sizeBeforeGC = 0;
int sizeAfterGC = 0; int sizeAfterGC = 0;
int loopSize = 10000; int loopSize = 10000;
int sizeExpectedAfterBuild = 0; int sizeExpectedAfterBuild = 0;
debug("testGCBehavior: started"); debug("testGCBehavior: started");
debug("creating 10,000 object sets"); debug("creating 10,000 object sets");
// cause classes to get loaded and any static instances to be created // cause classes to get loaded and any static instances to be created
SafeArray.class.getName(); SafeArray.class.getName();
Variant.class.getName(); Variant.class.getName();
sizeBeforeBuild = ROT.getThreadObjects(false).size(); sizeBeforeBuild = ROT.getThreadObjects(false).size();
sizeExpectedAfterBuild = ((loopSize * 3) + sizeBeforeBuild); sizeExpectedAfterBuild = ((loopSize * 3) + sizeBeforeBuild);
for (int i = 0; i < loopSize; i++) { for (int i = 0; i < loopSize; i++) {
SafeArray a1 = new SafeArray(Variant.VariantVariant, 2); SafeArray a1 = new SafeArray(Variant.VariantVariant, 2);
a1.setVariant(0, new Variant("foo")); a1.setVariant(0, new Variant("foo"));
a1.setVariant(1, new Variant("bar")); a1.setVariant(1, new Variant("bar"));
} }
sizeAfterBuild = ROT.getThreadObjects(false).size(); sizeAfterBuild = ROT.getThreadObjects(false).size();
if (sizeAfterBuild < sizeExpectedAfterBuild) { if (sizeAfterBuild < sizeExpectedAfterBuild) {
debug("Something got GC'd: " + sizeAfterBuild); debug("Something got GC'd: " + sizeAfterBuild);
} else if (sizeAfterBuild > sizeExpectedAfterBuild) { } else if (sizeAfterBuild > sizeExpectedAfterBuild) {
debug("More: " + sizeAfterBuild + " than expected: " debug("More: " + sizeAfterBuild + " than expected: "
+ sizeExpectedAfterBuild); + sizeExpectedAfterBuild);
} else { } else {
debug("They're all there"); debug("They're all there");
} }
// add more to the VM // add more to the VM
debug("Flooding Memory to force GC"); debug("Flooding Memory to force GC");
for (int i = 0; i <= loopSize * 2; i++) { for (int i = 0; i <= loopSize * 2; i++) {
new String("this is just some text to see if we can force gc " + 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 // storage will hold weak references until the next JacobObject is
// created // created
System.gc(); System.gc();
sizeBeforeGC = ROT.getThreadObjects(false).size(); sizeBeforeGC = ROT.getThreadObjects(false).size();
debug("Objects left after flood and gc but before adding a new object that clean's up weak references: " debug("Objects left after flood and gc but before adding a new object that clean's up weak references: "
+ sizeBeforeGC); + sizeBeforeGC);
debug("Creating single object. This adds one and causes ROT to clean up GC'd"); debug("Creating single object. This adds one and causes ROT to clean up GC'd");
new JacobObject(); new JacobObject();
sizeAfterGC = ROT.getThreadObjects(false).size(); sizeAfterGC = ROT.getThreadObjects(false).size();
debug("Objects left after adding one (caused weak ref objects to be removed): " debug("Objects left after adding one (caused weak ref objects to be removed): "
+ sizeAfterGC); + sizeAfterGC);
new JacobObject(); new JacobObject();
if (ROT.getThreadObjects(false).size() != sizeAfterGC + 1) { if (ROT.getThreadObjects(false).size() != sizeAfterGC + 1) {
debug("Unexpected number of objects after adding only one more " debug("Unexpected number of objects after adding only one more "
+ ROT.getThreadObjects(false).size()); + ROT.getThreadObjects(false).size());
} else { } else {
debug("Found number expected after adding one more " debug("Found number expected after adding one more "
+ (sizeAfterGC + 1)); + (sizeAfterGC + 1));
} }
ROT.clearObjects(); ROT.clearObjects();
if (ROT.getThreadObjects(false) == null) { if (ROT.getThreadObjects(false) == null) {
debug("ROT pool was destroyed as expected after clearObjects called."); debug("ROT pool was destroyed as expected after clearObjects called.");
} else { } else {
debug("ROT pool for thread still exists when it shouldn't"); debug("ROT pool for thread still exists when it shouldn't");
} }
// ========= part two ================================ // ========= part two ================================
debug("Verifying doesn't blow up with double release"); debug("Verifying doesn't blow up with double release");
for (int i = 0; i <= 10000; i++) { for (int i = 0; i <= 10000; i++) {
new JacobObject(); new JacobObject();
} }
// force safeRelease call on all objects // force safeRelease call on all objects
ROT.clearObjects(); ROT.clearObjects();
// now force the gc to go collect them, running safeRelease again // now force the gc to go collect them, running safeRelease again
System.gc(); System.gc();
debug("testGCBehavior: finished"); debug("testGCBehavior: finished");
} }
private static void debug(String message) { private static void debug(String message) {
System.out.println(Thread.currentThread().getName() + " " + message); System.out.println(Thread.currentThread().getName() + " " + message);
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -51,58 +51,58 @@ import com.jacob.test.BaseTestCase;
*/ */
public class VariantDateTest extends BaseTestCase { public class VariantDateTest extends BaseTestCase {
/** /**
* verify the conversion of Variants into java dates * verify the conversion of Variants into java dates
*/ */
public void testVariantDate() { public void testVariantDate() {
Date now = new Date(); Date now = new Date();
Variant holder = new Variant(); Variant holder = new Variant();
holder.putDate(now); holder.putDate(now);
Date retrievedNow = holder.getJavaDate(); Date retrievedNow = holder.getJavaDate();
if (!now.equals(retrievedNow)) { if (!now.equals(retrievedNow)) {
fail("Variant Date Test failed " + now + " != " + retrievedNow); fail("Variant Date Test failed " + now + " != " + retrievedNow);
} else { } else {
System.out.println("Variant Date Test passed"); System.out.println("Variant Date Test passed");
} }
} }
/** /**
* verify that the Variant constructor accepts Java dates and converts them * verify that the Variant constructor accepts Java dates and converts them
* correctly * correctly
*/ */
public void testVariantDateToJavaObject() { public void testVariantDateToJavaObject() {
Date now = new Date(); Date now = new Date();
Variant holder = new Variant(now); Variant holder = new Variant(now);
for (int i = 0; i < 30000; i++) { for (int i = 0; i < 30000; i++) {
Variant dateVariant = new Variant(now); Variant dateVariant = new Variant(now);
Date retrievedNow = holder.getJavaDate(); Date retrievedNow = holder.getJavaDate();
retrievedNow = dateVariant.getJavaDate(); retrievedNow = dateVariant.getJavaDate();
if (!now.equals(retrievedNow)) { if (!now.equals(retrievedNow)) {
fail("Variant Date Test (1) failed " + now + " != " fail("Variant Date Test (1) failed " + now + " != "
+ retrievedNow); + retrievedNow);
} else { } else {
// System.out.println("Variant Date Test (1) passed"); // System.out.println("Variant Date Test (1) passed");
} }
// verify auto typecasting works // verify auto typecasting works
retrievedNow = (Date) dateVariant.toJavaObject(); retrievedNow = (Date) dateVariant.toJavaObject();
if (!now.equals(retrievedNow)) { if (!now.equals(retrievedNow)) {
fail("Variant Date Test (2) failed " + now + " != " fail("Variant Date Test (2) failed " + now + " != "
+ retrievedNow); + retrievedNow);
} else { } else {
// System.out.println("Variant Date Test (2) passed // System.out.println("Variant Date Test (2) passed
// "+retrievedNow); // "+retrievedNow);
} }
Variant intVariant = new Variant(4); Variant intVariant = new Variant(4);
Object variantReturn = intVariant.toJavaObject(); Object variantReturn = intVariant.toJavaObject();
// degenerate test to make sure date isn't always returned // degenerate test to make sure date isn't always returned
if (variantReturn instanceof Date) { if (variantReturn instanceof Date) {
System.out.println("int variant returned date"); System.out.println("int variant returned date");
} }
} }
System.out.print("Test finished. All tests passed."); System.out.print("Test finished. All tests passed.");
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.com; package com.jacob.com;
@@ -49,122 +49,122 @@ import com.jacob.test.BaseTestCase;
*/ */
public class VariantUtilitiesTest extends BaseTestCase { public class VariantUtilitiesTest extends BaseTestCase {
/** /**
* verifies our unpacking stuff * verifies our unpacking stuff
*/ */
public void testObjectsToVariants() { public void testObjectsToVariants() {
Object testArray[] = new Object[] { Integer.valueOf(1), Object testArray[] = new Object[] { Integer.valueOf(1),
Integer.valueOf(2) }; Integer.valueOf(2) };
Variant resultArray[] = VariantUtilities.objectsToVariants(testArray); Variant resultArray[] = VariantUtilities.objectsToVariants(testArray);
assertEquals(2, resultArray.length); assertEquals(2, resultArray.length);
Variant resultArray2[] = VariantUtilities Variant resultArray2[] = VariantUtilities
.objectsToVariants(resultArray); .objectsToVariants(resultArray);
assertEquals(2, resultArray2.length); assertEquals(2, resultArray2.length);
assertSame(resultArray[0], resultArray2[0]); assertSame(resultArray[0], resultArray2[0]);
assertSame(resultArray[1], resultArray2[1]); assertSame(resultArray[1], resultArray2[1]);
} }
/** /**
* test nested arrays * test nested arrays
*/ */
public void testObjectsToVariantNestedArray() { public void testObjectsToVariantNestedArray() {
Object testArray[] = new Object[] { Integer.valueOf(1), Object testArray[] = new Object[] { Integer.valueOf(1),
Integer.valueOf(2) }; Integer.valueOf(2) };
Object testArrayOuter[] = new Object[] { testArray }; Object testArrayOuter[] = new Object[] { testArray };
Variant resultArray[] = VariantUtilities Variant resultArray[] = VariantUtilities
.objectsToVariants(testArrayOuter); .objectsToVariants(testArrayOuter);
// should be a SafeArray // should be a SafeArray
assertEquals(1, resultArray.length); assertEquals(1, resultArray.length);
} }
/** /**
* verify that dispatch can convert from object to variant and that the * verify that dispatch can convert from object to variant and that the
* variant holds the right value * variant holds the right value
*/ */
public void testConverters() { public void testConverters() {
Date testDate = new Date(); Date testDate = new Date();
Variant fromDate = VariantUtilities.objectToVariant(testDate); Variant fromDate = VariantUtilities.objectToVariant(testDate);
Date returnedDate = fromDate.getJavaDate(); Date returnedDate = fromDate.getJavaDate();
// System.out.println("test date is "+testDate); // System.out.println("test date is "+testDate);
// System.out.println("VariantDate is "+fromDate.getJavaDate()); // System.out.println("VariantDate is "+fromDate.getJavaDate());
assertTrue("Could not call obj2variant(Date) and get it to work", assertTrue("Could not call obj2variant(Date) and get it to work",
testDate.equals(returnedDate)); testDate.equals(returnedDate));
Currency someMoney = new Currency(12349876L); Currency someMoney = new Currency(12349876L);
Variant fromMoney = VariantUtilities.objectToVariant(someMoney); Variant fromMoney = VariantUtilities.objectToVariant(someMoney);
Currency someMoneyConverted = fromMoney.getCurrency(); Currency someMoneyConverted = fromMoney.getCurrency();
assertTrue("Could not call obj2variant(Long) and get it to work", assertTrue("Could not call obj2variant(Long) and get it to work",
someMoney.equals(someMoneyConverted)); someMoney.equals(someMoneyConverted));
System.out.println("currency returned was: " + someMoneyConverted); System.out.println("currency returned was: " + someMoneyConverted);
} }
public void testPrimitiveByteArray() { public void testPrimitiveByteArray() {
byte[] arr = new byte[] { 1, 2, 3 }; byte[] arr = new byte[] { 1, 2, 3 };
Variant arrVar = VariantUtilities.objectToVariant(arr); Variant arrVar = VariantUtilities.objectToVariant(arr);
assertNotNull(arrVar); assertNotNull(arrVar);
SafeArray sa = arrVar.toSafeArray(); SafeArray sa = arrVar.toSafeArray();
assertNotNull(sa); assertNotNull(sa);
assertEquals(Variant.VariantByte, sa.getvt()); assertEquals(Variant.VariantByte, sa.getvt());
assertEquals(0, sa.getLBound()); assertEquals(0, sa.getLBound());
assertEquals(2, sa.getUBound()); assertEquals(2, sa.getUBound());
byte[] bytes = sa.toByteArray(); byte[] bytes = sa.toByteArray();
assertTrue(Arrays.equals(bytes, arr)); assertTrue(Arrays.equals(bytes, arr));
} }
public void testPrimitiveIntArray() { public void testPrimitiveIntArray() {
int[] arr = new int[] { 1000, 2000, 3 }; int[] arr = new int[] { 1000, 2000, 3 };
Variant arrVar = VariantUtilities.objectToVariant(arr); Variant arrVar = VariantUtilities.objectToVariant(arr);
assertNotNull(arrVar); assertNotNull(arrVar);
SafeArray sa = arrVar.toSafeArray(); SafeArray sa = arrVar.toSafeArray();
assertNotNull(sa); assertNotNull(sa);
assertEquals(Variant.VariantInt, sa.getvt()); assertEquals(Variant.VariantInt, sa.getvt());
assertEquals(0, sa.getLBound()); assertEquals(0, sa.getLBound());
assertEquals(2, sa.getUBound()); assertEquals(2, sa.getUBound());
int[] ints = sa.toIntArray(); int[] ints = sa.toIntArray();
assertTrue(Arrays.equals(ints, arr)); assertTrue(Arrays.equals(ints, arr));
} }
public void testPrimitiveDoubleArray() { public void testPrimitiveDoubleArray() {
double[] arr = new double[] { 1000, 2000, 3 }; double[] arr = new double[] { 1000, 2000, 3 };
Variant arrVar = VariantUtilities.objectToVariant(arr); Variant arrVar = VariantUtilities.objectToVariant(arr);
assertNotNull(arrVar); assertNotNull(arrVar);
SafeArray sa = arrVar.toSafeArray(); SafeArray sa = arrVar.toSafeArray();
assertNotNull(sa); assertNotNull(sa);
assertEquals(Variant.VariantDouble, sa.getvt()); assertEquals(Variant.VariantDouble, sa.getvt());
assertEquals(0, sa.getLBound()); assertEquals(0, sa.getLBound());
assertEquals(2, sa.getUBound()); assertEquals(2, sa.getUBound());
double[] doubles = sa.toDoubleArray(); double[] doubles = sa.toDoubleArray();
assertTrue(Arrays.equals(doubles, arr)); assertTrue(Arrays.equals(doubles, arr));
} }
public void testPrimitiveLongArray() { public void testPrimitiveLongArray() {
long[] arr = new long[] { 0xcafebabecafebabeL, 42, 0xbabecafebabeL }; long[] arr = new long[] { 0xcafebabecafebabeL, 42, 0xbabecafebabeL };
Variant arrVar = VariantUtilities.objectToVariant(arr); Variant arrVar = VariantUtilities.objectToVariant(arr);
assertNotNull(arrVar); assertNotNull(arrVar);
SafeArray sa = arrVar.toSafeArray(); SafeArray sa = arrVar.toSafeArray();
assertNotNull(sa); assertNotNull(sa);
assertEquals(Variant.VariantLongInt, sa.getvt()); assertEquals(Variant.VariantLongInt, sa.getvt());
assertEquals(0, sa.getLBound()); assertEquals(0, sa.getLBound());
assertEquals(2, sa.getUBound()); assertEquals(2, sa.getUBound());
long[] longs = sa.toLongArray(); long[] longs = sa.toLongArray();
assertTrue(Arrays.equals(longs, arr)); assertTrue(Arrays.equals(longs, arr));
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test; package com.jacob.test;
@@ -61,152 +61,152 @@ import com.jacob.com.JacobObject;
*/ */
public class BaseTestCase extends TestCase { public class BaseTestCase extends TestCase {
protected void setUp() { protected void setUp() {
// verify we have run with the dll in the lib path // verify we have run with the dll in the lib path
try { try {
JacobObject foo = new JacobObject(); JacobObject foo = new JacobObject();
if (foo == null) { if (foo == null) {
fail("Failed basic sanity test: Can't create JacobObject (-D<java.library.path=xxx>)"); fail("Failed basic sanity test: Can't create JacobObject (-D<java.library.path=xxx>)");
} }
} catch (UnsatisfiedLinkError ule) { } catch (UnsatisfiedLinkError ule) {
fail("Did you remember to run with the jacob.dll in the libpath ?"); fail("Did you remember to run with the jacob.dll in the libpath ?");
} }
} }
/** /**
* this test exists just to test the setup. * this test exists just to test the setup.
*/ */
public void testSetup() { public void testSetup() {
JacobObject foo = new JacobObject(); JacobObject foo = new JacobObject();
assertNotNull(foo); assertNotNull(foo);
} }
/** /**
* *
* @return a simple VB script that generates the result "3" * @return a simple VB script that generates the result "3"
*/ */
public String getSampleVPScriptForEval() { public String getSampleVPScriptForEval() {
return "1+(2*4)-3"; return "1+(2*4)-3";
} }
/** /**
* Converts the class name into a path and appends the resource name. Used * 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 * to derive the path to a resource in the file system where the resource is
* co-located with the referenced class. * co-located with the referenced class.
* *
* @param resourceName * @param resourceName
* @param classInSamePackageAsResource * @param classInSamePackageAsResource
* @return a class loader compatible fully qualified file system path to a * @return a class loader compatible fully qualified file system path to a
* resource * resource
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private String getJavaFilePathToPackageResource(String resourceName, private String getJavaFilePathToPackageResource(String resourceName,
Class classInSamePackageAsResource) { Class classInSamePackageAsResource) {
String classPackageName = classInSamePackageAsResource.getName(); String classPackageName = classInSamePackageAsResource.getName();
int i = classPackageName.lastIndexOf('.'); int i = classPackageName.lastIndexOf('.');
if (i == -1) { if (i == -1) {
classPackageName = ""; classPackageName = "";
} else { } else {
classPackageName = classPackageName.substring(0, i); classPackageName = classPackageName.substring(0, i);
} }
// change all "." to ^ for later conversion to "/" so we can append // change all "." to ^ for later conversion to "/" so we can append
// resource names with "." // resource names with "."
classPackageName = classPackageName.replace('.', '^'); classPackageName = classPackageName.replace('.', '^');
System.out.println("classPackageName: " + classPackageName); System.out.println("classPackageName: " + classPackageName);
String fullPathToResource; String fullPathToResource;
if (classPackageName.length() > 0) { if (classPackageName.length() > 0) {
fullPathToResource = classPackageName + "^" + resourceName; fullPathToResource = classPackageName + "^" + resourceName;
} else { } else {
fullPathToResource = resourceName; fullPathToResource = resourceName;
} }
fullPathToResource = fullPathToResource.replace('^', '/'); fullPathToResource = fullPathToResource.replace('^', '/');
System.out.println("fullPathToResource: " + fullPathToResource); System.out.println("fullPathToResource: " + fullPathToResource);
URL urlToLibrary = classInSamePackageAsResource.getClassLoader() URL urlToLibrary = classInSamePackageAsResource.getClassLoader()
.getResource(fullPathToResource); .getResource(fullPathToResource);
assertNotNull("URL to resource " + resourceName assertNotNull("URL to resource " + resourceName
+ " should not be null." + " should not be null."
+ " You probably need to add 'unittest' to the" + " You probably need to add 'unittest' to the"
+ " classpath so the tests can find resources", urlToLibrary); + " classpath so the tests can find resources", urlToLibrary);
String fullPathToResourceAsFile = urlToLibrary.getFile(); String fullPathToResourceAsFile = urlToLibrary.getFile();
System.out.println("url to library: " + urlToLibrary); System.out.println("url to library: " + urlToLibrary);
System.out.println("fullPathToResourceAsFile: " System.out.println("fullPathToResourceAsFile: "
+ fullPathToResourceAsFile); + fullPathToResourceAsFile);
return fullPathToResourceAsFile; return fullPathToResourceAsFile;
} }
/** /**
* Converts the class name into a path and appends the resource name. Used * 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 * to derive the path to a resource in the file system where the resource is
* co-located with the referenced class. * co-located with the referenced class.
* *
* @param resourceName * @param resourceName
* @param classInSamePackageAsResource * @param classInSamePackageAsResource
* @return returns the path in the file system of the requested resource in * @return returns the path in the file system of the requested resource in
* windows c compatible format * windows c compatible format
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public String getWindowsFilePathToPackageResource(String resourceName, public String getWindowsFilePathToPackageResource(String resourceName,
Class classInSamePackageAsResource) { Class classInSamePackageAsResource) {
String javaFilePath = getJavaFilePathToPackageResource(resourceName, String javaFilePath = getJavaFilePathToPackageResource(resourceName,
classInSamePackageAsResource); classInSamePackageAsResource);
javaFilePath = javaFilePath.replace('/', '\\'); javaFilePath = javaFilePath.replace('/', '\\');
return javaFilePath.substring(1); return javaFilePath.substring(1);
} }
/** /**
* *
* @param resourceName * @param resourceName
* @param classInSamePackageAsResource * @param classInSamePackageAsResource
* @return a resource located in the same package as the passed in class * @return a resource located in the same package as the passed in class
*/ */
@SuppressWarnings( { "unused", "unchecked" }) @SuppressWarnings( { "unused", "unchecked" })
private Object getPackageResource(String resourceName, private Object getPackageResource(String resourceName,
Class classInSamePackageAsResource) { Class classInSamePackageAsResource) {
String fullPathToResource = getJavaFilePathToPackageResource( String fullPathToResource = getJavaFilePathToPackageResource(
resourceName, classInSamePackageAsResource); resourceName, classInSamePackageAsResource);
ClassLoader localClassLoader = classInSamePackageAsResource ClassLoader localClassLoader = classInSamePackageAsResource
.getClassLoader(); .getClassLoader();
if (null == localClassLoader) { if (null == localClassLoader) {
return ClassLoader.getSystemResource(fullPathToResource); return ClassLoader.getSystemResource(fullPathToResource);
} else { } else {
return localClassLoader.getResource(fullPathToResource); return localClassLoader.getResource(fullPathToResource);
} }
} }
/** /**
* load a library from same place in the file system that the class was * load a library from same place in the file system that the class was
* loaded from. * loaded from.
* <p> * <p>
* This is an attempt to let unit tests run without having to run regsvr32. * This is an attempt to let unit tests run without having to run regsvr32.
* *
* @param libraryName * @param libraryName
* @param classInSamePackageAsResource * @param classInSamePackageAsResource
*/ */
@SuppressWarnings( { "unchecked", "unused" }) @SuppressWarnings( { "unchecked", "unused" })
private void loadLibraryFromClassPackage(String libraryName, private void loadLibraryFromClassPackage(String libraryName,
Class classInSamePackageAsResource) { Class classInSamePackageAsResource) {
String libraryNameWithSuffix = ""; String libraryNameWithSuffix = "";
String fullLibraryNameWithPath = ""; String fullLibraryNameWithPath = "";
if (libraryName != null && libraryName.endsWith("dll")) { if (libraryName != null && libraryName.endsWith("dll")) {
libraryNameWithSuffix = libraryName; libraryNameWithSuffix = libraryName;
} else if (libraryName != null) { } else if (libraryName != null) {
libraryNameWithSuffix = libraryName + ".dll"; libraryNameWithSuffix = libraryName + ".dll";
} else { } else {
fail("can't create full library name " + libraryName); fail("can't create full library name " + libraryName);
} }
// generate the path the classloader would use to find this on the // generate the path the classloader would use to find this on the
// classpath // classpath
fullLibraryNameWithPath = getJavaFilePathToPackageResource( fullLibraryNameWithPath = getJavaFilePathToPackageResource(
libraryNameWithSuffix, classInSamePackageAsResource); libraryNameWithSuffix, classInSamePackageAsResource);
System.load(fullLibraryNameWithPath); System.load(fullLibraryNameWithPath);
// requires that the dll be on the library path // requires that the dll be on the library path
// System.loadLibrary(fullLibraryNameWithPath); // System.loadLibrary(fullLibraryNameWithPath);
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.errors; package com.jacob.test.errors;
@@ -51,22 +51,22 @@ import com.jacob.com.ComException;
*/ */
public class UnicodeErrorTest extends BaseTestCase { public class UnicodeErrorTest extends BaseTestCase {
/** /**
* verifies that messages can now have unicode in them like when the file * verifies that messages can now have unicode in them like when the file
* names have unicode characters * names have unicode characters
*/ */
public void testUnicodeCharactersInErrorMessage() { public void testUnicodeCharactersInErrorMessage() {
ActiveXComponent application = new ActiveXComponent("Word.Application"); ActiveXComponent application = new ActiveXComponent("Word.Application");
ActiveXComponent documents = application ActiveXComponent documents = application
.getPropertyAsComponent("Documents"); .getPropertyAsComponent("Documents");
String fileName = "abc\u0411\u0412\u0413\u0414def"; String fileName = "abc\u0411\u0412\u0413\u0414def";
try { try {
documents.invoke("Open", fileName); documents.invoke("Open", fileName);
fail("Should have thrown an exception"); fail("Should have thrown an exception");
} catch (ComException e) { } catch (ComException e) {
assertTrue("Error message should contain file name with unicode " assertTrue("Error message should contain file name with unicode "
+ "characters in it. " + e.getMessage(), e.getMessage() + "characters in it. " + e.getMessage(), e.getMessage()
.indexOf(fileName) > 0); .indexOf(fileName) > 0);
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.events; package com.jacob.test.events;
@@ -59,132 +59,132 @@ import com.jacob.test.BaseTestCase;
*/ */
public class ExcelEventTest extends BaseTestCase { public class ExcelEventTest extends BaseTestCase {
/** /**
* load up excel, register for events and make stuff happen * load up excel, register for events and make stuff happen
* *
* @param args * @param args
*/ */
public void testExcelWithInvocationProxy() { public void testExcelWithInvocationProxy() {
ComThread.InitSTA(); ComThread.InitSTA();
// we are going to listen to events on Application. // we are going to listen to events on Application.
// You can probably also listen Excel.Sheet and Excel.Chart // You can probably also listen Excel.Sheet and Excel.Chart
String excelApplicationProgramId = "Excel.Application"; String excelApplicationProgramId = "Excel.Application";
String excelSheetProgramId = "Excel.Sheet"; String excelSheetProgramId = "Excel.Sheet";
String typeLibLocation; String typeLibLocation;
// office 2003 // office 2003
typeLibLocation = "C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE"; typeLibLocation = "C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE";
// office 2007 // office 2007
typeLibLocation = "C:\\Program Files\\Microsoft Office\\OFFICE12\\EXCEL.EXE"; typeLibLocation = "C:\\Program Files\\Microsoft Office\\OFFICE12\\EXCEL.EXE";
// office 2013 322 bit // office 2013 322 bit
typeLibLocation = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\EXCEL.EXE"; typeLibLocation = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\EXCEL.EXE";
// Grab The Component. // Grab The Component.
ActiveXComponent axc = new ActiveXComponent(excelApplicationProgramId); ActiveXComponent axc = new ActiveXComponent(excelApplicationProgramId);
hookupListener(axc, excelApplicationProgramId, typeLibLocation); hookupListener(axc, excelApplicationProgramId, typeLibLocation);
try { try {
System.out.println("version=" + axc.getProperty("Version")); System.out.println("version=" + axc.getProperty("Version"));
System.out.println("version=" + Dispatch.get(axc, "Version")); System.out.println("version=" + Dispatch.get(axc, "Version"));
axc.setProperty("Visible", true); axc.setProperty("Visible", true);
Dispatch workbooks = axc.getPropertyAsComponent("Workbooks"); Dispatch workbooks = axc.getPropertyAsComponent("Workbooks");
Dispatch workbook = Dispatch.get(workbooks, "Add").toDispatch(); Dispatch workbook = Dispatch.get(workbooks, "Add").toDispatch();
Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch(); Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
System.out.println("Workbook: " + workbook); System.out.println("Workbook: " + workbook);
System.out.println("Sheet: " + sheet); System.out.println("Sheet: " + sheet);
if (typeLibLocation.contains("OFFICE11")) { if (typeLibLocation.contains("OFFICE11")) {
// office 2007 throws crashes the VM // office 2007 throws crashes the VM
System.out.println("Hooking up sheet listener"); System.out.println("Hooking up sheet listener");
hookupListener(sheet, excelSheetProgramId, typeLibLocation); hookupListener(sheet, excelSheetProgramId, typeLibLocation);
} }
System.out.println("Retrieving cells"); System.out.println("Retrieving cells");
Dispatch a1 = Dispatch.invoke(sheet, "Range", Dispatch.Get, Dispatch a1 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { "A1" }, new int[1]).toDispatch(); new Object[] { "A1" }, new int[1]).toDispatch();
Dispatch a2 = Dispatch.invoke(sheet, "Range", Dispatch.Get, Dispatch a2 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { "A2" }, new int[1]).toDispatch(); new Object[] { "A2" }, new int[1]).toDispatch();
System.out.println("Inserting value into A1"); System.out.println("Inserting value into A1");
System.out.println("Inserting calculation 2xA1 into A2"); System.out.println("Inserting calculation 2xA1 into A2");
Dispatch.put(a1, "Value", "123.456"); Dispatch.put(a1, "Value", "123.456");
Dispatch.put(a2, "Formula", "=A1*2"); Dispatch.put(a2, "Formula", "=A1*2");
System.out.println("Retrieved a1 from excel:" System.out.println("Retrieved a1 from excel:"
+ Dispatch.get(a1, "Value")); + Dispatch.get(a1, "Value"));
System.out.println("Retrieved a2 from excel:" System.out.println("Retrieved a2 from excel:"
+ Dispatch.get(a2, "Value")); + Dispatch.get(a2, "Value"));
Variant f = new Variant(false); Variant f = new Variant(false);
Dispatch.call(workbook, "Close", f); Dispatch.call(workbook, "Close", f);
axc.invoke("Quit", new Variant[] {}); axc.invoke("Quit", new Variant[] {});
} catch (ComException cfe) { } catch (ComException cfe) {
cfe.printStackTrace(); cfe.printStackTrace();
fail("Failed to attach to " + excelApplicationProgramId + ": " fail("Failed to attach to " + excelApplicationProgramId + ": "
+ cfe.getMessage()); + cfe.getMessage());
} }
try { try {
// the sleep is required to let everything clear out after the quit // the sleep is required to let everything clear out after the quit
Thread.sleep(2000); Thread.sleep(2000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
ComThread.Release(); ComThread.Release();
} }
/** /**
* extracted the listener hookup so we could try multiple listeners. * extracted the listener hookup so we could try multiple listeners.
* *
* @param axc * @param axc
* @param programId * @param programId
* @param typeLibLocation * @param typeLibLocation
*/ */
private void hookupListener(Dispatch axc, String programId, private void hookupListener(Dispatch axc, String programId,
String typeLibLocation) { String typeLibLocation) {
// Add a listener (doesn't matter what it is). // Add a listener (doesn't matter what it is).
DispatchEvents applicationEvents; DispatchEvents applicationEvents;
if (typeLibLocation == null) { if (typeLibLocation == null) {
applicationEvents = new DispatchEvents(axc, new ExcelEvents( applicationEvents = new DispatchEvents(axc, new ExcelEvents(
programId)); programId));
} else { } else {
applicationEvents = new DispatchEvents(axc, new ExcelEvents( applicationEvents = new DispatchEvents(axc, new ExcelEvents(
programId), programId, typeLibLocation); programId), programId, typeLibLocation);
} }
if (applicationEvents == null) { if (applicationEvents == null) {
System.out System.out
.println("No exception thrown but no dispatch returned for Excel events"); .println("No exception thrown but no dispatch returned for Excel events");
} else { } else {
// Yea! // Yea!
System.out System.out
.println("Successfully attached listener to " + programId); .println("Successfully attached listener to " + programId);
} }
} }
/** /**
* Proxy class to verify we receive expected events * Proxy class to verify we receive expected events
*/ */
public class ExcelEvents extends InvocationProxy { public class ExcelEvents extends InvocationProxy {
private String listenerPrefix = "-"; private String listenerPrefix = "-";
/** /**
* Constructor so we can create an instance that implements invoke() * Constructor so we can create an instance that implements invoke()
* *
* @param interfaceIdentifier * @param interfaceIdentifier
* a string that identifies which listener is speaking * a string that identifies which listener is speaking
*/ */
public ExcelEvents(String interfaceIdentifier) { public ExcelEvents(String interfaceIdentifier) {
listenerPrefix = interfaceIdentifier; listenerPrefix = interfaceIdentifier;
} }
/** /**
* Override the invoke method to log all the events so that we don't * Override the invoke method to log all the events so that we don't
* have to implement all of the specific events. * have to implement all of the specific events.
*/ */
@Override @Override
public Variant invoke(String methodName, Variant targetParameter[]) { public Variant invoke(String methodName, Variant targetParameter[]) {
System.out.println("Received event from " + listenerPrefix + ": " System.out.println("Received event from " + listenerPrefix + ": "
+ methodName); + methodName);
return null; return null;
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.events; package com.jacob.test.events;
@@ -60,418 +60,418 @@ import com.jacob.test.BaseTestCase;
public class IETest extends BaseTestCase { public class IETest extends BaseTestCase {
/** /**
* well known address we can navigate to * well known address we can navigate to
*/ */
private final String testUrls[] = { private final String testUrls[] = {
"http://sourceforge.net/projects/jacob-project", "http://sourceforge.net/projects/jacob-project",
"http://www.google.com" }; "http://www.google.com" };
/** /**
* runs the IE test and feeds it commands * runs the IE test and feeds it commands
*/ */
public void testRunIECleanly() { public void testRunIECleanly() {
runTheTest(true, testUrls); runTheTest(true, testUrls);
} }
/** /**
* runs the IE test and feeds it commands * runs the IE test and feeds it commands
*/ */
public void testRunIETerminateWithoutWait() { public void testRunIETerminateWithoutWait() {
runTheTest(false, testUrls); runTheTest(false, testUrls);
} }
/** /**
* The actual work of running the test. * The actual work of running the test.
* *
* @param waitForQuit * @param waitForQuit
* @param urls * @param urls
*/ */
private void runTheTest(boolean waitForQuit, String[] urls) { private void runTheTest(boolean waitForQuit, String[] urls) {
// this line starts the pump but it runs fine without it // this line starts the pump but it runs fine without it
ComThread.startMainSTA(); ComThread.startMainSTA();
// Run the test in a thread. Lets us test running out of "main" thread // Run the test in a thread. Lets us test running out of "main" thread
IETestThread aThread = new IETestThread(waitForQuit, urls); IETestThread aThread = new IETestThread(waitForQuit, urls);
aThread.start(); aThread.start();
while (aThread.isAlive()) { while (aThread.isAlive()) {
try { try {
Thread.sleep(250); Thread.sleep(250);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// done with the sleep // done with the sleep
} }
} }
System.out.println("Main: Thread quit, about to quitMainSTA in thread " System.out.println("Main: Thread quit, about to quitMainSTA in thread "
+ Thread.currentThread().getName()); + Thread.currentThread().getName());
// this line only does something if startMainSTA() was called // this line only does something if startMainSTA() was called
ComThread.quitMainSTA(); ComThread.quitMainSTA();
System.out.println("Main: did quit main sta in thread " System.out.println("Main: did quit main sta in thread "
+ Thread.currentThread().getName()); + Thread.currentThread().getName());
if (aThread.threadFailedWithException != null) { if (aThread.threadFailedWithException != null) {
aThread.threadFailedWithException.printStackTrace(); aThread.threadFailedWithException.printStackTrace();
fail("caught an unexpected exception " fail("caught an unexpected exception "
+ aThread.threadFailedWithException); + aThread.threadFailedWithException);
} }
} }
} }
class IETestThread extends Thread { class IETestThread extends Thread {
/** flag that says we got a quit message from IE */ /** flag that says we got a quit message from IE */
public static boolean quitHandled = false; public static boolean quitHandled = false;
/** /**
* determines if we wait until last quit call back received before * determines if we wait until last quit call back received before
* terminating * terminating
*/ */
private static boolean waitUntilReceivedQuitCallback = true; private static boolean waitUntilReceivedQuitCallback = true;
/** /**
* the places we should navigate to * the places we should navigate to
*/ */
private static String[] targets = null; private static String[] targets = null;
/** /**
* holds any caught exception so the main/test case can see them * holds any caught exception so the main/test case can see them
*/ */
public Throwable threadFailedWithException = null; public Throwable threadFailedWithException = null;
/** /**
* constructor for the test thread * constructor for the test thread
* *
* @param beNeat * @param beNeat
* should we wait until quit received * should we wait until quit received
* @param urls * @param urls
* the web pages we will navigate to * the web pages we will navigate to
*/ */
public IETestThread(boolean beNeat, String urls[]) { public IETestThread(boolean beNeat, String urls[]) {
super(); super();
waitUntilReceivedQuitCallback = beNeat; waitUntilReceivedQuitCallback = beNeat;
targets = urls; targets = urls;
} }
/** /**
* Run through the addresses passed in via the constructor * Run through the addresses passed in via the constructor
*/ */
@Override @Override
public void run() { public void run() {
// pick a time that lets sourceforge respond (in msec) // pick a time that lets sourceforge respond (in msec)
int delay = 3000; int delay = 3000;
// pre-1.14 paired with statement below that blows up // pre-1.14 paired with statement below that blows up
ComThread.InitMTA(); ComThread.InitMTA();
ActiveXComponent ie = new ActiveXComponent( ActiveXComponent ie = new ActiveXComponent(
"InternetExplorer.Application"); "InternetExplorer.Application");
try { try {
Dispatch.put(ie, "Visible", new Variant(true)); Dispatch.put(ie, "Visible", new Variant(true));
Dispatch.put(ie, "AddressBar", new Variant(true)); Dispatch.put(ie, "AddressBar", new Variant(true));
System.out.println("IETestThread: " + Dispatch.get(ie, "Path")); System.out.println("IETestThread: " + Dispatch.get(ie, "Path"));
// Some version of IE broke this. Not sure which one // Some version of IE broke this. Not sure which one
// Dispatch.put(ie, "StatusText", new Variant("My Status Text")); // Dispatch.put(ie, "StatusText", new Variant("My Status Text"));
System.out.println("IETestThread: About to hookup event listener"); System.out.println("IETestThread: About to hookup event listener");
IEEvents ieE = new IEEvents(); IEEvents ieE = new IEEvents();
new DispatchEvents(ie, ieE, "InternetExplorer.Application.1"); new DispatchEvents(ie, ieE, "InternetExplorer.Application.1");
System.out.println("IETestThread: Did hookup event listener"); System.out.println("IETestThread: Did hookup event listener");
for (String url : targets) { for (String url : targets) {
System.out.println("IETestThread: About to call navigate to " System.out.println("IETestThread: About to call navigate to "
+ url); + url);
Dispatch.call(ie, "Navigate", new Variant(url)); Dispatch.call(ie, "Navigate", new Variant(url));
System.out.println("IETestThread: Did call navigate to " + url); System.out.println("IETestThread: Did call navigate to " + url);
try { try {
Thread.sleep(delay); Thread.sleep(delay);
} catch (Exception e) { } catch (Exception e) {
} }
} }
} catch (Exception e) { } catch (Exception e) {
threadFailedWithException = e; threadFailedWithException = e;
e.printStackTrace(); e.printStackTrace();
} catch (Throwable re) { } catch (Throwable re) {
threadFailedWithException = re; threadFailedWithException = re;
re.printStackTrace(); re.printStackTrace();
} finally { } finally {
System.out.println("IETestThread: About to send Quit"); System.out.println("IETestThread: About to send Quit");
ie.invoke("Quit", new Variant[] {}); ie.invoke("Quit", new Variant[] {});
System.out.println("IETestThread: Did send Quit"); System.out.println("IETestThread: Did send Quit");
} }
// a value is set to false if we try to crash VM by leaving before // a value is set to false if we try to crash VM by leaving before
// callbacks all received // callbacks all received
if (waitUntilReceivedQuitCallback) { if (waitUntilReceivedQuitCallback) {
System.out System.out
.println("IETestThread: Waiting until we've received quit callback"); .println("IETestThread: Waiting until we've received quit callback");
// wait a little while for it to end // wait a little while for it to end
while (!quitHandled) { while (!quitHandled) {
try { try {
Thread.sleep(delay / 10); Thread.sleep(delay / 10);
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
} }
System.out.println("IETestThread: Received the OnQuit callback"); System.out.println("IETestThread: Received the OnQuit callback");
} else { } else {
System.out.println("IETestThread: Not waiting for OnQuit callback"); System.out.println("IETestThread: Not waiting for OnQuit callback");
} }
System.out.println("IETestThread: Calling ComThread.Release in thread " System.out.println("IETestThread: Calling ComThread.Release in thread "
+ Thread.currentThread().getName()); + Thread.currentThread().getName());
ComThread.Release(); ComThread.Release();
} }
/** /**
* The events class must be publicly accessible for reflection to work. The * The events class must be publicly accessible for reflection to work. The
* list of available events is located at * list of available events is located at
* http://msdn2.microsoft.com/en-us/library/aa768280.aspx * http://msdn2.microsoft.com/en-us/library/aa768280.aspx
*/ */
public class IEEvents { public class IEEvents {
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void BeforeNavigate2(Variant[] args) { public void BeforeNavigate2(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): BeforeNavigate2 " + Thread.currentThread().getName() + "): BeforeNavigate2 "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void CommandStateChange(Variant[] args) { public void CommandStateChange(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + Thread.currentThread().getName()
+ "): CommandStateChange " + args.length + " parameters"); + "): CommandStateChange " + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void DocumentComplete(Variant[] args) { public void DocumentComplete(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): DocumentComplete " + Thread.currentThread().getName() + "): DocumentComplete "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void DownloadBegin(Variant[] args) { public void DownloadBegin(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): DownloadBegin " + Thread.currentThread().getName() + "): DownloadBegin "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void DownloadComplete(Variant[] args) { public void DownloadComplete(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): DownloadComplete " + Thread.currentThread().getName() + "): DownloadComplete "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void NavigateError(Variant[] args) { public void NavigateError(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): NavigateError " + Thread.currentThread().getName() + "): NavigateError "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void NavigateComplete2(Variant[] args) { public void NavigateComplete2(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): NavigateComplete " + Thread.currentThread().getName() + "): NavigateComplete "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void NewWindow2(Variant[] args) { public void NewWindow2(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): NewWindow2 " + Thread.currentThread().getName() + "): NewWindow2 "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void OnFullScreen(Variant[] args) { public void OnFullScreen(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnFullScreen " + Thread.currentThread().getName() + "): OnFullScreen "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void OnMenuBar(Variant[] args) { public void OnMenuBar(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnMenuBar " + Thread.currentThread().getName() + "): OnMenuBar "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void OnQuit(Variant[] args) { public void OnQuit(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnQuit " + Thread.currentThread().getName() + "): OnQuit "
+ args.length + " parameters"); + args.length + " parameters");
IETestThread.quitHandled = true; IETestThread.quitHandled = true;
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void OnStatusBar(Variant[] args) { public void OnStatusBar(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnStatusBar " + Thread.currentThread().getName() + "): OnStatusBar "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void OnTheaterMode(Variant[] args) { public void OnTheaterMode(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnTheaterMode " + Thread.currentThread().getName() + "): OnTheaterMode "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void OnToolBar(Variant[] args) { public void OnToolBar(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnToolBar " + Thread.currentThread().getName() + "): OnToolBar "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void OnVisible(Variant[] args) { public void OnVisible(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): OnVisible " + Thread.currentThread().getName() + "): OnVisible "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void ProgressChange(Variant[] args) { public void ProgressChange(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): ProgressChange " + Thread.currentThread().getName() + "): ProgressChange "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void PropertyChange(Variant[] args) { public void PropertyChange(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): PropertyChange " + Thread.currentThread().getName() + "): PropertyChange "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void SetSecureLockIcon(Variant[] args) { public void SetSecureLockIcon(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + Thread.currentThread().getName()
+ "): setSecureLockIcon " + args.length + " parameters"); + "): setSecureLockIcon " + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void StatusTextChange(Variant[] args) { public void StatusTextChange(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): StatusTextChange " + Thread.currentThread().getName() + "): StatusTextChange "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void TitleChange(Variant[] args) { public void TitleChange(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): TitleChange " + Thread.currentThread().getName() + "): TitleChange "
+ args.length + " parameters"); + args.length + " parameters");
} }
/** /**
* Internet explorer event this proxy can receive * Internet explorer event this proxy can receive
* *
* @param args * @param args
* the COM Variant objects that this event passes in. * the COM Variant objects that this event passes in.
*/ */
public void WindowClosing(Variant[] args) { public void WindowClosing(Variant[] args) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): WindowClosing " + Thread.currentThread().getName() + "): WindowClosing "
+ args.length + " parameters"); + args.length + " parameters");
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.events; package com.jacob.test.events;
@@ -60,268 +60,268 @@ import com.jacob.test.BaseTestCase;
public class IETestActiveXProxy extends BaseTestCase { public class IETestActiveXProxy extends BaseTestCase {
/** /**
* the main test method that builds up the connection and runs the test * the main test method that builds up the connection and runs the test
*/ */
public void testIEActiveProxyCallback() { public void testIEActiveProxyCallback() {
// this line starts the pump but it runs fine without it // this line starts the pump but it runs fine without it
ComThread.startMainSTA(); ComThread.startMainSTA();
// remove this line and it dies // remove this line and it dies
// /ComThread.InitMTA(true); // /ComThread.InitMTA(true);
IETestActiveProxyThread aThread = new IETestActiveProxyThread(); IETestActiveProxyThread aThread = new IETestActiveProxyThread();
aThread.start(); aThread.start();
while (aThread.isAlive()) { while (aThread.isAlive()) {
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// doen with the sleep // doen with the sleep
// e.printStackTrace(); // e.printStackTrace();
} }
} }
System.out System.out
.println("Main: Thread quit, about to quit main sta in thread " .println("Main: Thread quit, about to quit main sta in thread "
+ Thread.currentThread().getName()); + Thread.currentThread().getName());
// this line only does someting if startMainSTA() was called // this line only does someting if startMainSTA() was called
ComThread.quitMainSTA(); ComThread.quitMainSTA();
System.out.println("Main: did quit main sta in thread " System.out.println("Main: did quit main sta in thread "
+ Thread.currentThread().getName()); + Thread.currentThread().getName());
if (aThread.threadFailedWithException != null) { if (aThread.threadFailedWithException != null) {
fail("caught an unexpected exception " fail("caught an unexpected exception "
+ aThread.threadFailedWithException); + aThread.threadFailedWithException);
} }
} }
} }
class IETestActiveProxyThread extends Thread { class IETestActiveProxyThread extends Thread {
/** says that the quit message has been received from the target application */ /** says that the quit message has been received from the target application */
public static boolean quitHandled = false; public static boolean quitHandled = false;
/** /**
* holds any caught exception so the main/test case can see them * holds any caught exception so the main/test case can see them
*/ */
public Throwable threadFailedWithException = null; public Throwable threadFailedWithException = null;
/** the thread's constructor */ /** the thread's constructor */
public IETestActiveProxyThread() { public IETestActiveProxyThread() {
super(); super();
} }
public void run() { public void run() {
// this used to be 5 seconds but sourceforge is slow // this used to be 5 seconds but sourceforge is slow
int delay = 5000; // msec int delay = 5000; // msec
// paired with statement below that blows up // paired with statement below that blows up
ComThread.InitMTA(); ComThread.InitMTA();
ActiveXComponent ie = new ActiveXComponent( ActiveXComponent ie = new ActiveXComponent(
"InternetExplorer.Application"); "InternetExplorer.Application");
try { try {
Dispatch.put(ie, "Visible", new Variant(true)); Dispatch.put(ie, "Visible", new Variant(true));
Dispatch.put(ie, "AddressBar", new Variant(true)); Dispatch.put(ie, "AddressBar", new Variant(true));
System.out.println("IETestActiveProxyThread: " System.out.println("IETestActiveProxyThread: "
+ Dispatch.get(ie, "Path")); + Dispatch.get(ie, "Path"));
Dispatch.put(ie, "StatusText", new Variant("My Status Text")); Dispatch.put(ie, "StatusText", new Variant("My Status Text"));
System.out System.out
.println("IETestActiveProxyThread: About to hookup event listener"); .println("IETestActiveProxyThread: About to hookup event listener");
IEEventsActiveProxy ieE = new IEEventsActiveProxy(); IEEventsActiveProxy ieE = new IEEventsActiveProxy();
new ActiveXDispatchEvents(ie, ieE, "InternetExplorer.Application.1"); new ActiveXDispatchEvents(ie, ieE, "InternetExplorer.Application.1");
System.out System.out
.println("IETestActiveProxyThread: Did hookup event listener"); .println("IETestActiveProxyThread: Did hookup event listener");
// / why is this here? Was there some other code here in the past? // / why is this here? Was there some other code here in the past?
Variant optional = new Variant(); Variant optional = new Variant();
optional.putNoParam(); optional.putNoParam();
System.out System.out
.println("IETestActiveProxyThread: About to call navigate to sourceforge"); .println("IETestActiveProxyThread: About to call navigate to sourceforge");
Dispatch.call(ie, "Navigate", new Variant( Dispatch.call(ie, "Navigate", new Variant(
"http://sourceforge.net/projects/jacob-project")); "http://sourceforge.net/projects/jacob-project"));
System.out System.out
.println("IETestActiveProxyThread: Did call navigate to sourceforge"); .println("IETestActiveProxyThread: Did call navigate to sourceforge");
try { try {
Thread.sleep(delay); Thread.sleep(delay);
} catch (Exception e) { } catch (Exception e) {
} }
System.out System.out
.println("IETestActiveProxyThread: About to call navigate to yahoo"); .println("IETestActiveProxyThread: About to call navigate to yahoo");
Dispatch.call(ie, "Navigate", new Variant( Dispatch.call(ie, "Navigate", new Variant(
"http://groups.yahoo.com/group/jacob-project")); "http://groups.yahoo.com/group/jacob-project"));
System.out System.out
.println("IETestActiveProxyThread: Did call navigate to yahoo"); .println("IETestActiveProxyThread: Did call navigate to yahoo");
try { try {
Thread.sleep(delay); Thread.sleep(delay);
} catch (Exception e) { } catch (Exception e) {
} }
} catch (Exception e) { } catch (Exception e) {
threadFailedWithException = e; threadFailedWithException = e;
e.printStackTrace(); e.printStackTrace();
} catch (Throwable re) { } catch (Throwable re) {
threadFailedWithException = re; threadFailedWithException = re;
re.printStackTrace(); re.printStackTrace();
} finally { } finally {
System.out.println("IETestActiveProxyThread: About to send Quit"); System.out.println("IETestActiveProxyThread: About to send Quit");
ie.invoke("Quit", new Variant[] {}); ie.invoke("Quit", new Variant[] {});
System.out.println("IETestActiveProxyThread: Did send Quit"); System.out.println("IETestActiveProxyThread: Did send Quit");
} }
// this blows up when it tries to release a DispatchEvents object // 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 // 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 // "OnQuit" that will came after we have released the thread pool
// this is probably messed up because DispatchEvent object will have // this is probably messed up because DispatchEvent object will have
// been // been
// freed before the callback // freed before the callback
// commenting out ie.invoke(quit...) causes this to work without error // commenting out ie.invoke(quit...) causes this to work without error
// this code tries to wait until the quit has been handled but that // this code tries to wait until the quit has been handled but that
// doesn't work // doesn't work
System.out System.out
.println("IETestActiveProxyThread: Waiting until we've received the quit callback"); .println("IETestActiveProxyThread: Waiting until we've received the quit callback");
while (!quitHandled) { while (!quitHandled) {
try { try {
Thread.sleep(delay / 5); Thread.sleep(delay / 5);
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
} }
System.out System.out
.println("IETestActiveProxyThread: Received the quit callback"); .println("IETestActiveProxyThread: Received the quit callback");
// wait a little while for it to end // wait a little while for it to end
// try {Thread.sleep(delay); } catch (InterruptedException e) {} // try {Thread.sleep(delay); } catch (InterruptedException e) {}
System.out System.out
.println("IETestActiveProxyThread: about to call ComThread.Release in thread " .println("IETestActiveProxyThread: about to call ComThread.Release in thread "
+ Thread.currentThread().getName()); + Thread.currentThread().getName());
ComThread.Release(); ComThread.Release();
} }
/** /**
* The events class must be publicly accessable for reflection to work. The * The events class must be publicly accessable for reflection to work. The
* list of available events is located at * list of available events is located at
* http://msdn2.microsoft.com/en-us/library/aa768280.aspx * http://msdn2.microsoft.com/en-us/library/aa768280.aspx
*/ */
public class IEEventsActiveProxy { public class IEEventsActiveProxy {
public void BeforeNavigate2(Dispatch pDisp, String url, Integer flags, public void BeforeNavigate2(Dispatch pDisp, String url, Integer flags,
String targetFrameName, Variant postData, String headers, String targetFrameName, Variant postData, String headers,
Boolean cancel) { Boolean cancel) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): BeforeNavigate2 " + Thread.currentThread().getName() + "): BeforeNavigate2 "
+ url); + url);
} }
public void CommandStateChange(Integer command, Boolean enable) { public void CommandStateChange(Integer command, Boolean enable) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + Thread.currentThread().getName()
+ "): CommandStateChange " + command); + "): CommandStateChange " + command);
} }
public void DocumentComplete(Dispatch pDisp, String url) { public void DocumentComplete(Dispatch pDisp, String url) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): DocumentComplete " + Thread.currentThread().getName() + "): DocumentComplete "
+ url); + url);
} }
public void DownloadBegin() { public void DownloadBegin() {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): DownloadBegin "); + Thread.currentThread().getName() + "): DownloadBegin ");
} }
public void DownloadComplete() { public void DownloadComplete() {
System.out System.out
.println("IEEventsActiveProxy Received (" .println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + Thread.currentThread().getName()
+ "): DownloadComplete "); + "): DownloadComplete ");
} }
public void NavigateComplete2(Dispatch pDisp, String url) { public void NavigateComplete2(Dispatch pDisp, String url) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): NavigateComplete " + Thread.currentThread().getName() + "): NavigateComplete "
+ url); + url);
} }
public void NavigateError(Dispatch pDispatch, String url, public void NavigateError(Dispatch pDispatch, String url,
String targetFrameName, Integer statusCode, Boolean Cancel) { String targetFrameName, Integer statusCode, Boolean Cancel) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): NavigateError " + Thread.currentThread().getName() + "): NavigateError "
+ statusCode); + statusCode);
} }
public void NewWindow2(Dispatch pDisp, Boolean cancel) { public void NewWindow2(Dispatch pDisp, Boolean cancel) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): NewWindow2 " + Thread.currentThread().getName() + "): NewWindow2 "
+ pDisp); + pDisp);
} }
public void OnFullScreen(Boolean fullScreen) { public void OnFullScreen(Boolean fullScreen) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnFullScreen " + Thread.currentThread().getName() + "): OnFullScreen "
+ fullScreen); + fullScreen);
} }
public void OnMenuBar(Boolean menuBar) { public void OnMenuBar(Boolean menuBar) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnMenuBar " + Thread.currentThread().getName() + "): OnMenuBar "
+ menuBar); + menuBar);
} }
public void OnQuit() { public void OnQuit() {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnQuit "); + Thread.currentThread().getName() + "): OnQuit ");
IETestActiveProxyThread.quitHandled = true; IETestActiveProxyThread.quitHandled = true;
} }
public void OnStatusBar(Boolean statusBar) { public void OnStatusBar(Boolean statusBar) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnStatusBar " + Thread.currentThread().getName() + "): OnStatusBar "
+ statusBar); + statusBar);
} }
public void OnTheaterMode(Boolean theaterMode) { public void OnTheaterMode(Boolean theaterMode) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnTheaterMode " + Thread.currentThread().getName() + "): OnTheaterMode "
+ theaterMode); + theaterMode);
} }
public void OnToolBar(Boolean onToolBar) { public void OnToolBar(Boolean onToolBar) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): OnToolBar " + Thread.currentThread().getName() + "): OnToolBar "
+ onToolBar); + onToolBar);
} }
public void OnVisible(Boolean onVisible) { public void OnVisible(Boolean onVisible) {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): onVisible " + Thread.currentThread().getName() + "): onVisible "
+ onVisible); + onVisible);
} }
public void ProgressChange() { public void ProgressChange() {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): ProgressChange "); + Thread.currentThread().getName() + "): ProgressChange ");
} }
public void PropertyChange() { public void PropertyChange() {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): PropertyChange "); + Thread.currentThread().getName() + "): PropertyChange ");
} }
public void SetSecureLockIcon(Integer secureLockIcon) { public void SetSecureLockIcon(Integer secureLockIcon) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + Thread.currentThread().getName()
+ "): setSecureLockIcon " + secureLockIcon); + "): setSecureLockIcon " + secureLockIcon);
} }
public void StatusTextChange() { public void StatusTextChange() {
System.out System.out
.println("IEEventsActiveProxy Received (" .println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + Thread.currentThread().getName()
+ "): StatusTextChange "); + "): StatusTextChange ");
} }
public void TitleChange() { public void TitleChange() {
System.out.println("IEEventsActiveProxy Received (" System.out.println("IEEventsActiveProxy Received ("
+ Thread.currentThread().getName() + "): TitleChange "); + Thread.currentThread().getName() + "): TitleChange ");
} }
public void WindowClosing(Boolean isChildWindow) { public void WindowClosing(Boolean isChildWindow) {
System.out.println("IEEvents Received (" System.out.println("IEEvents Received ("
+ Thread.currentThread().getName() + "): WindowClosing " + Thread.currentThread().getName() + "): WindowClosing "
+ isChildWindow); + isChildWindow);
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.events; package com.jacob.test.events;
@@ -58,74 +58,74 @@ import com.jacob.test.BaseTestCase;
*/ */
public class WordEventTest extends BaseTestCase { public class WordEventTest extends BaseTestCase {
/** /**
* load up word, register for events and make stuff happen * load up word, register for events and make stuff happen
* *
* @param args * @param args
*/ */
public void testCaptureWordEvents() { public void testCaptureWordEvents() {
String pid = "Word.Application"; String pid = "Word.Application";
String typeLibLocation = null; String typeLibLocation = null;
// Grab The Component. // Grab The Component.
ActiveXComponent axc = new ActiveXComponent(pid); ActiveXComponent axc = new ActiveXComponent(pid);
try { try {
// Add a listener (doesn't matter what it is). // Add a listener (doesn't matter what it is).
DispatchEvents de; DispatchEvents de;
if (typeLibLocation == null) { if (typeLibLocation == null) {
de = new DispatchEvents(axc, new WordEventTest()); de = new DispatchEvents(axc, new WordEventTest());
} else { } else {
de = new DispatchEvents(axc, new WordEventTest(), pid, de = new DispatchEvents(axc, new WordEventTest(), pid,
typeLibLocation); typeLibLocation);
} }
if (de == null) { if (de == null) {
fail("No exception thrown but no dispatch returned for Word events"); fail("No exception thrown but no dispatch returned for Word events");
} else { } else {
// Yea! // Yea!
System.out.println("Successfully attached to " + pid); System.out.println("Successfully attached to " + pid);
} }
// this is different from the ExcelEventTest because it uses // this is different from the ExcelEventTest because it uses
// the jacob active X api instead of the Dispatch api // the jacob active X api instead of the Dispatch api
System.out.println("version=" + axc.getPropertyAsString("Version")); System.out.println("version=" + axc.getPropertyAsString("Version"));
axc.setProperty("Visible", true); axc.setProperty("Visible", true);
ActiveXComponent documents = axc ActiveXComponent documents = axc
.getPropertyAsComponent("Documents"); .getPropertyAsComponent("Documents");
if (documents == null) { if (documents == null) {
fail("unable to get documents"); fail("unable to get documents");
} }
axc.invoke("Quit", new Variant[] {}); axc.invoke("Quit", new Variant[] {});
} catch (ComException cfe) { } catch (ComException cfe) {
cfe.printStackTrace(); cfe.printStackTrace();
fail("Failed to attach to " + pid + ": " + cfe.getMessage()); fail("Failed to attach to " + pid + ": " + cfe.getMessage());
} }
System.out System.out
.println("Someone needs to add some MSWord commands to this to " .println("Someone needs to add some MSWord commands to this to "
+ "make some on screen stuff happens so the tester " + "make some on screen stuff happens so the tester "
+ "thinks we tested something"); + "thinks we tested something");
} }
/** /**
* a class that receives messages from word * a class that receives messages from word
*/ */
public class WordEvents extends InvocationProxy { public class WordEvents extends InvocationProxy {
/** /**
* Constructor so we can create an instance that implements invoke() * Constructor so we can create an instance that implements invoke()
*/ */
public WordEvents() { public WordEvents() {
} }
/** /**
* override the invoke() method to log all the events without writing a * override the invoke() method to log all the events without writing a
* bunch of code * bunch of code
*/ */
public Variant invoke(String methodName, Variant targetParameter[]) { public Variant invoke(String methodName, Variant targetParameter[]) {
System.out.println("Received event from Windows program" System.out.println("Received event from Windows program"
+ methodName); + methodName);
return null; return null;
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.excel; package com.jacob.test.excel;
@@ -56,219 +56,219 @@ import com.jacob.test.BaseTestCase;
*/ */
public class ControllerTest extends BaseTestCase { public class ControllerTest extends BaseTestCase {
private Controller controller; private Controller controller;
protected void setUp() { protected void setUp() {
controller = new Controller(); controller = new Controller();
} }
public void testGetColumnA() { public void testGetColumnA() {
List<String> list = controller.getColumnA(super List<String> list = controller.getColumnA(super
.getWindowsFilePathToPackageResource("teste.xls", this .getWindowsFilePathToPackageResource("teste.xls", this
.getClass())); .getClass()));
assertEquals(50, list.size()); assertEquals(50, list.size());
} }
public void testGetColumnB() { public void testGetColumnB() {
List<String> list = controller.getColumnB(super List<String> list = controller.getColumnB(super
.getWindowsFilePathToPackageResource("teste.xls", this .getWindowsFilePathToPackageResource("teste.xls", this
.getClass())); .getClass()));
assertEquals(40, list.size()); assertEquals(40, list.size());
} }
/** /**
* This class looks bad because it is a compressed version that was * 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 * 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 * want to simplify it because it might no longer demonstrate the problem we
* were trying to fix * were trying to fix
*/ */
public class Controller { public class Controller {
private List<String> columnA; private List<String> columnA;
private List<String> columnB; private List<String> columnB;
public List<String> getColumnA(String pathToTest) { public List<String> getColumnA(String pathToTest) {
load(pathToTest); load(pathToTest);
return columnA; return columnA;
} }
public List<String> getColumnB(String pathToTest) { public List<String> getColumnB(String pathToTest) {
load(pathToTest); load(pathToTest);
return columnB; return columnB;
} }
public void load(String pathToTest) { public void load(String pathToTest) {
if (columnA == null || columnB == null) { if (columnA == null || columnB == null) {
File excelFile = new File(pathToTest); File excelFile = new File(pathToTest);
executaExcelCallBack(excelFile.getAbsolutePath(), "password"); executaExcelCallBack(excelFile.getAbsolutePath(), "password");
} }
} }
public void executaExcelCallBack(String path, String password) { public void executaExcelCallBack(String path, String password) {
// ComThread.InitSTA(); // ComThread.InitSTA();
ComThread.InitMTA(); ComThread.InitMTA();
ActiveXComponent excel = new ActiveXComponent("Excel.Application"); ActiveXComponent excel = new ActiveXComponent("Excel.Application");
try { try {
excel.setProperty("Visible", false); excel.setProperty("Visible", false);
Dispatch workbooks = excel.getProperty("Workbooks") Dispatch workbooks = excel.getProperty("Workbooks")
.toDispatch(); .toDispatch();
Dispatch workbook = Dispatch.call(workbooks, "Open", path, // FileName Dispatch workbook = Dispatch.call(workbooks, "Open", path, // FileName
3, // UpdateLinks 3, // UpdateLinks
false, // Readonly false, // Readonly
5, // Format 5, // Format
password // Password password // Password
).toDispatch(); ).toDispatch();
Dispatch sheets = Dispatch.call(workbook, "Worksheets") Dispatch sheets = Dispatch.call(workbook, "Worksheets")
.toDispatch(); .toDispatch();
System.out.println("Before executa"); System.out.println("Before executa");
executa(excel, sheets); executa(excel, sheets);
System.out.println("After executa"); System.out.println("After executa");
Dispatch.call(workbook, "Close", new Variant(false)); Dispatch.call(workbook, "Close", new Variant(false));
Dispatch.call(workbooks, "Close"); Dispatch.call(workbooks, "Close");
System.out.println("After Close"); System.out.println("After Close");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
System.out.println("Before Quit"); System.out.println("Before Quit");
excel.invoke("Quit", new Variant[] {}); excel.invoke("Quit", new Variant[] {});
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
System.out.println("After Quit, Before Release()"); System.out.println("After Quit, Before Release()");
ComThread.Release(); ComThread.Release();
System.out.println("After Release()"); System.out.println("After Release()");
} }
} }
/** /**
* Constante para configurar a planilha em modo "Calculation" autom<6F>tico * Constante para configurar a planilha em modo "Calculation" autom<6F>tico
*/ */
public static final int CALC_AUTOMATICO = -4105; public static final int CALC_AUTOMATICO = -4105;
/** /**
* Constante para configurar a planilha em modo "Calculation" manual * Constante para configurar a planilha em modo "Calculation" manual
*/ */
public static final int CALC_MANUAL = -4135; public static final int CALC_MANUAL = -4135;
/** /**
* Escreve um determinado valor em uma c<>lula da pasta em quest<73>o. O * 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 * valor <20> escrito configurando a propriedade Value da c<>lula
* *
* @param celula - * @param celula -
* c<>lula para escrever novo valor * c<>lula para escrever novo valor
* @param sheet - * @param sheet -
* pasta da planilha em quest<73>o * pasta da planilha em quest<73>o
* @param valor - * @param valor -
* valor a ser escrito na celula * valor a ser escrito na celula
*/ */
public void informarValorCelula(String celula, Dispatch sheet, public void informarValorCelula(String celula, Dispatch sheet,
String valor) { String valor) {
System.out.println("Entered informarValorCelula"); System.out.println("Entered informarValorCelula");
Dispatch cel = obterCelula(celula, sheet); Dispatch cel = obterCelula(celula, sheet);
Dispatch.put(cel, "Value", valor); Dispatch.put(cel, "Value", valor);
System.out.println("Exiting informarValorCelula"); System.out.println("Exiting informarValorCelula");
} }
/** /**
* Obtem o valor de contido em uma c<>lula. O valor representa o conte<74>do * Obtem o valor de contido em uma c<>lula. O valor representa o conte<74>do
* da propriedade Value da c<>lula * da propriedade Value da c<>lula
* *
* @param celula - * @param celula -
* c<>lula a ser lida * c<>lula a ser lida
* @param sheet - * @param sheet -
* pasta da planilha que cont<6E>m a c<>lula * pasta da planilha que cont<6E>m a c<>lula
* @return - conte<74>do da propriedade Value * @return - conte<74>do da propriedade Value
*/ */
public Variant obterValorCelula(String celula, Dispatch sheet) { public Variant obterValorCelula(String celula, Dispatch sheet) {
System.out.println("Entered obterValorCelula"); System.out.println("Entered obterValorCelula");
Dispatch d = obterCelula(celula, sheet); Dispatch d = obterCelula(celula, sheet);
Variant returnedValue = Dispatch.get(d, "Value"); Variant returnedValue = Dispatch.get(d, "Value");
System.out.println("Exiting obterValorCelula"); System.out.println("Exiting obterValorCelula");
return returnedValue; return returnedValue;
} }
/** /**
* Obtem refer<65>ncia para a c<>lua ou conjunto de c<>lulas especificado no * Obtem refer<65>ncia para a c<>lua ou conjunto de c<>lulas especificado no
* parametro * parametro
* *
* @param celula - * @param celula -
* Refer<65>ncia para c<>lula ou conjunto de c<>lulas. A String * 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" * "A1" referencia a coluna A e linha 1. A Sting "A1:A10"
* referencia as c<>lulas compreendidas no intervalo entre a * referencia as c<>lulas compreendidas no intervalo entre a
* c<>lua A1 e a c<>lula A10 * c<>lua A1 e a c<>lula A10
* @param sheet - * @param sheet -
* pasta da planilha qye cont<6E>m as c<>lulas * pasta da planilha qye cont<6E>m as c<>lulas
* @return - referencia para um c<>lula ou conjunto de c<>lulas, * @return - referencia para um c<>lula ou conjunto de c<>lulas,
* dependendo do par<61>metro passado * dependendo do par<61>metro passado
*/ */
public Dispatch obterCelula(String celula, Dispatch sheet) { public Dispatch obterCelula(String celula, Dispatch sheet) {
System.out.println("Entered obterCelula"); System.out.println("Entered obterCelula");
Dispatch d = Dispatch.invoke(sheet, "Range", Dispatch.Get, Dispatch d = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { celula }, new int[1]).toDispatch(); new Object[] { celula }, new int[1]).toDispatch();
System.out.println("Exiting obterCelula"); System.out.println("Exiting obterCelula");
return d; return d;
} }
/** /**
* Obtem os valores de um conjunto de c<>lulas * Obtem os valores de um conjunto de c<>lulas
* *
* @param celulas - * @param celulas -
* Refer<65>ncia para conjunto de c<>lulas * Refer<65>ncia para conjunto de c<>lulas
* @param sheet - * @param sheet -
* Pasta que cont<6E>m as c<>lulas referenciadas * Pasta que cont<6E>m as c<>lulas referenciadas
* @return - Lista onde cada elemento <20> o valor de uma c<>lula * @return - Lista onde cada elemento <20> o valor de uma c<>lula
* referenciada na conjunto * referenciada na conjunto
*/ */
public List<String> obterValoresRange(String celulas, Dispatch sheet) { public List<String> obterValoresRange(String celulas, Dispatch sheet) {
List<String> valores = new LinkedList<String>(); List<String> valores = new LinkedList<String>();
// obtem valor das celulas como um Variant // obtem valor das celulas como um Variant
Variant var = obterValorCelula(celulas, sheet); Variant var = obterValorCelula(celulas, sheet);
// toString da Variant <20> interpretado por um StringTokenizer e os // toString da Variant <20> interpretado por um StringTokenizer e os
// tokens // tokens
// inseridos na lista de retorno // inseridos na lista de retorno
String arrayAsString = null; String arrayAsString = null;
System.out System.out
.println("Calling toString() on the Variant that is an array will blow up " .println("Calling toString() on the Variant that is an array will blow up "
+ var.getvt() + " --> " + arrayAsString); + var.getvt() + " --> " + arrayAsString);
arrayAsString = var.toString(); arrayAsString = var.toString();
StringTokenizer st = new StringTokenizer(arrayAsString, "\n"); StringTokenizer st = new StringTokenizer(arrayAsString, "\n");
while (st.hasMoreTokens()) { while (st.hasMoreTokens()) {
valores.add(st.nextToken().trim()); valores.add(st.nextToken().trim());
} }
return valores; return valores;
} }
/** /**
* M<>todo para execu<63><75>o de a<><61>o a ser executada em planilha excel. * M<>todo para execu<63><75>o de a<><61>o a ser executada em planilha excel.
* *
* @param xl - * @param xl -
* Referencia para aplica<63><61>o excel * Referencia para aplica<63><61>o excel
* @param sheets - * @param sheets -
* Referencia para conjunto de pastas da planilha * Referencia para conjunto de pastas da planilha
*/ */
public void executa(ActiveXComponent xl, Dispatch sheets) { public void executa(ActiveXComponent xl, Dispatch sheets) {
System.out.println("Entered private ExcellCallBack executa()"); System.out.println("Entered private ExcellCallBack executa()");
Dispatch sheet = Dispatch.call(sheets, "Item", "Plan1") Dispatch sheet = Dispatch.call(sheets, "Item", "Plan1")
.toDispatch(); .toDispatch();
columnA = obterValoresRange("A1:A50", sheet); columnA = obterValoresRange("A1:A50", sheet);
columnB = obterValoresRange("B1:B40", sheet); columnB = obterValoresRange("B1:B40", sheet);
System.out.println("Exiting private ExcellCallBack executa()"); System.out.println("Exiting private ExcellCallBack executa()");
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.powerpoint; package com.jacob.test.powerpoint;
@@ -69,131 +69,131 @@ import com.jacob.test.BaseTestCase;
* options. * options.
*/ */
public class PowerpointTest extends BaseTestCase { public class PowerpointTest extends BaseTestCase {
private static final int NUM_THREADS = 5; private static final int NUM_THREADS = 5;
protected static final int NUM_ITERATIONS = 50; protected static final int NUM_ITERATIONS = 50;
/** /**
* main program that lets us run this as a test * main program that lets us run this as a test
* *
* @param args * @param args
*/ */
public void testPowerpoint() { public void testPowerpoint() {
ComThread.InitMTA(); ComThread.InitMTA();
ActiveXComponent component = new ActiveXComponent( ActiveXComponent component = new ActiveXComponent(
"Powerpoint.Application"); "Powerpoint.Application");
Dispatch comPowerpoint = component.getObject(); Dispatch comPowerpoint = component.getObject();
try { try {
PowerpointTestThread[] threads = new PowerpointTestThread[NUM_THREADS]; PowerpointTestThread[] threads = new PowerpointTestThread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) { for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new PowerpointTestThread(i + 1, comPowerpoint); threads[i] = new PowerpointTestThread(i + 1, comPowerpoint);
threads[i].start(); threads[i].start();
} }
boolean allThreadsFinished = false; boolean allThreadsFinished = false;
while (!allThreadsFinished) { while (!allThreadsFinished) {
allThreadsFinished = true; allThreadsFinished = true;
for (int i = 0; i < NUM_THREADS; i++) { for (int i = 0; i < NUM_THREADS; i++) {
if (threads[i].isAlive()) { if (threads[i].isAlive()) {
allThreadsFinished = false; allThreadsFinished = false;
break; break;
} }
} }
if (!allThreadsFinished) { if (!allThreadsFinished) {
try { try {
Thread.sleep(100); Thread.sleep(100);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// no op // no op
} }
} }
} }
Dispatch.call(comPowerpoint, "Quit"); Dispatch.call(comPowerpoint, "Quit");
for (int i = 0; i < NUM_THREADS; i++) { for (int i = 0; i < NUM_THREADS; i++) {
if (threads[i].threadFailedWithException != null) { if (threads[i].threadFailedWithException != null) {
fail("caught unexpected exception in thread " fail("caught unexpected exception in thread "
+ threads[i].threadFailedWithException); + threads[i].threadFailedWithException);
} }
} }
} finally { } finally {
ComThread.Release(); ComThread.Release();
} }
} }
/** /**
* the thread class that runs power point * the thread class that runs power point
*/ */
public class PowerpointTestThread extends Thread { public class PowerpointTestThread extends Thread {
/** /**
* holds any caught exception so the main/test case can see them * holds any caught exception so the main/test case can see them
*/ */
public Throwable threadFailedWithException = null; public Throwable threadFailedWithException = null;
private int threadID; private int threadID;
private Dispatch comPowerpoint; private Dispatch comPowerpoint;
/** /**
* thread constructor * thread constructor
* *
* @param threadID * @param threadID
* @param comPowerpoint * @param comPowerpoint
*/ */
public PowerpointTestThread(int threadID, Dispatch comPowerpoint) { public PowerpointTestThread(int threadID, Dispatch comPowerpoint) {
super("TestThread " + threadID); super("TestThread " + threadID);
this.threadID = threadID; this.threadID = threadID;
this.comPowerpoint = comPowerpoint; this.comPowerpoint = comPowerpoint;
} }
public void run() { public void run() {
System.out.println("Thread \"" + Thread.currentThread().getName() System.out.println("Thread \"" + Thread.currentThread().getName()
+ "\" started"); + "\" started");
System.out.flush(); System.out.flush();
ComThread.InitMTA(); ComThread.InitMTA();
try { try {
for (int i = 0; i < NUM_ITERATIONS; i++) { for (int i = 0; i < NUM_ITERATIONS; i++) {
if (i % 10 == 0) { if (i % 10 == 0) {
System.out.println(Thread.currentThread().getName() System.out.println(Thread.currentThread().getName()
+ ": Iteration " + i); + ": Iteration " + i);
System.out.flush(); System.out.flush();
} }
// office 2003 seems to have been able to handle more // office 2003 seems to have been able to handle more
// multi-threaded requests than office 2007 // multi-threaded requests than office 2007
// office 2003 could handle 5 threads @ 50 iterations // office 2003 could handle 5 threads @ 50 iterations
// office 2007 can only handle 1 thread at a time // office 2007 can only handle 1 thread at a time
synchronized(comPowerpoint){ synchronized(comPowerpoint){
Dispatch comPresentations = Dispatch.get(comPowerpoint, Dispatch comPresentations = Dispatch.get(comPowerpoint,
"Presentations").toDispatch(); "Presentations").toDispatch();
Dispatch comPresentation = Dispatch.call( Dispatch comPresentation = Dispatch.call(
comPresentations, comPresentations,
"Open", "Open",
getWindowsFilePathToPackageResource("test" getWindowsFilePathToPackageResource("test"
+ threadID + ".ppt", this.getClass()), + threadID + ".ppt", this.getClass()),
new Integer(0), new Integer(0), new Integer(0)) new Integer(0), new Integer(0), new Integer(0))
.toDispatch(); .toDispatch();
Dispatch.call(comPresentation, "Close"); Dispatch.call(comPresentation, "Close");
} }
} }
} catch (ComFailException cfe) { } catch (ComFailException cfe) {
threadFailedWithException = cfe; threadFailedWithException = cfe;
System.err.println(Thread.currentThread().getName() System.err.println(Thread.currentThread().getName()
+ "\" while working on: " + "\" while working on: "
+ getWindowsFilePathToPackageResource("test" + threadID + getWindowsFilePathToPackageResource("test" + threadID
+ ".ppt", this.getClass())); + ".ppt", this.getClass()));
cfe.printStackTrace(); cfe.printStackTrace();
} catch (Exception e) { } catch (Exception e) {
threadFailedWithException = e; threadFailedWithException = e;
System.err.println("Error in Thread \"" System.err.println("Error in Thread \""
+ Thread.currentThread().getName() + "\":"); + Thread.currentThread().getName() + "\":");
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
ComThread.Release(); ComThread.Release();
System.out.println("Thread \"" System.out.println("Thread \""
+ Thread.currentThread().getName() + "\" finished"); + Thread.currentThread().getName() + "\" finished");
System.out.flush(); System.out.flush();
} }
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.safearray; package com.jacob.test.safearray;
@@ -57,297 +57,297 @@ import com.jacob.test.BaseTestCase;
*/ */
public class SafeArrayBasicTest extends BaseTestCase { public class SafeArrayBasicTest extends BaseTestCase {
/** /**
* *
*/ */
public void testShortSafeArray() { public void testShortSafeArray() {
short sourceData[] = new short[] { 1, 2, 3 }; short sourceData[] = new short[] { 1, 2, 3 };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3); SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromShortArray(sourceData); saUnderTest.fromShortArray(sourceData);
short[] extractedFromSafeArray = saUnderTest.toShortArray(); short[] extractedFromSafeArray = saUnderTest.toShortArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]); assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
} }
assertEquals("single get failed: ", sourceData[2], saUnderTest assertEquals("single get failed: ", sourceData[2], saUnderTest
.getShort(2)); .getShort(2));
// test conversion // test conversion
int[] extractedFromSafeArrayInt = saUnderTest.toIntArray(); int[] extractedFromSafeArrayInt = saUnderTest.toIntArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArrayInt[i]); assertEquals("" + i, sourceData[i], extractedFromSafeArrayInt[i]);
} }
// test conversion // test conversion
double[] extractedFromSafeArrayDouble = saUnderTest.toDoubleArray(); double[] extractedFromSafeArrayDouble = saUnderTest.toDoubleArray();
for (int i = 0; i < extractedFromSafeArrayDouble.length; i++) { for (int i = 0; i < extractedFromSafeArrayDouble.length; i++) {
assertEquals("" + i, new Double(sourceData[i]).doubleValue(), assertEquals("" + i, new Double(sourceData[i]).doubleValue(),
extractedFromSafeArrayDouble[i]); extractedFromSafeArrayDouble[i]);
} }
// test conversion // test conversion
Variant extractedFromSafeArrayVariant[] = saUnderTest.toVariantArray(); Variant extractedFromSafeArrayVariant[] = saUnderTest.toVariantArray();
for (int i = 0; i < extractedFromSafeArrayVariant.length; i++) { for (int i = 0; i < extractedFromSafeArrayVariant.length; i++) {
assertEquals("" + i, sourceData[i], assertEquals("" + i, sourceData[i],
extractedFromSafeArrayVariant[i].getShort()); extractedFromSafeArrayVariant[i].getShort());
} }
} }
/** /**
* *
*/ */
public void testIntSafeArray() { public void testIntSafeArray() {
int sourceData[] = new int[] { 100000, 200000, 300000 }; int sourceData[] = new int[] { 100000, 200000, 300000 };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3); SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromIntArray(sourceData); saUnderTest.fromIntArray(sourceData);
int[] extractedFromSafeArray = saUnderTest.toIntArray(); int[] extractedFromSafeArray = saUnderTest.toIntArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]); assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
} }
assertEquals("single get failed: ", sourceData[2], saUnderTest assertEquals("single get failed: ", sourceData[2], saUnderTest
.getInt(2)); .getInt(2));
} }
/** /**
* *
*/ */
public void testLongSafeArrayVariantVariant() { public void testLongSafeArrayVariantVariant() {
long sourceData[] = new long[] { 2L << 40, 3L << 41, 4L << 42 }; long sourceData[] = new long[] { 2L << 40, 3L << 41, 4L << 42 };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, SafeArray saUnderTest = new SafeArray(Variant.VariantVariant,
sourceData.length); sourceData.length);
saUnderTest.fromLongArray(sourceData); saUnderTest.fromLongArray(sourceData);
long[] extractedFromSafeArray = saUnderTest.toLongArray(); long[] extractedFromSafeArray = saUnderTest.toLongArray();
assertEquals(sourceData.length, extractedFromSafeArray.length); assertEquals(sourceData.length, extractedFromSafeArray.length);
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("failed on index " + i, sourceData[i], assertEquals("failed on index " + i, sourceData[i],
extractedFromSafeArray[i]); extractedFromSafeArray[i]);
} }
assertEquals("single get failed: ", sourceData[2], saUnderTest assertEquals("single get failed: ", sourceData[2], saUnderTest
.getLong(2)); .getLong(2));
} }
/** /**
* *
*/ */
public void testLongSafeArrayVariantLongInt() { public void testLongSafeArrayVariantLongInt() {
long sourceData[] = new long[] { 2L << 40, 3L << 41, 4L << 42 }; long sourceData[] = new long[] { 2L << 40, 3L << 41, 4L << 42 };
SafeArray saUnderTest = new SafeArray(Variant.VariantLongInt, SafeArray saUnderTest = new SafeArray(Variant.VariantLongInt,
sourceData.length); sourceData.length);
saUnderTest.fromLongArray(sourceData); saUnderTest.fromLongArray(sourceData);
long[] extractedFromSafeArray = saUnderTest.toLongArray(); long[] extractedFromSafeArray = saUnderTest.toLongArray();
assertEquals(sourceData.length, extractedFromSafeArray.length); assertEquals(sourceData.length, extractedFromSafeArray.length);
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("failed on index " + i, sourceData[i], assertEquals("failed on index " + i, sourceData[i],
extractedFromSafeArray[i]); extractedFromSafeArray[i]);
} }
assertEquals("single get failed: ", sourceData[2], saUnderTest assertEquals("single get failed: ", sourceData[2], saUnderTest
.getLong(2)); .getLong(2));
} }
/** /**
* *
*/ */
public void testDoubleSafeArrayVariantVariant() { public void testDoubleSafeArrayVariantVariant() {
double sourceData[] = new double[] { 1.5, 2.5, 3.5 }; double sourceData[] = new double[] { 1.5, 2.5, 3.5 };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, SafeArray saUnderTest = new SafeArray(Variant.VariantVariant,
sourceData.length); sourceData.length);
saUnderTest.fromDoubleArray(sourceData); saUnderTest.fromDoubleArray(sourceData);
double[] extractedFromSafeArray = saUnderTest.toDoubleArray(); double[] extractedFromSafeArray = saUnderTest.toDoubleArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]); assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
} }
assertEquals("single get failed: ", sourceData[2], saUnderTest assertEquals("single get failed: ", sourceData[2], saUnderTest
.getDouble(2)); .getDouble(2));
} }
/** /**
* *
*/ */
public void testDoubleSafeArrayVariantDouble() { public void testDoubleSafeArrayVariantDouble() {
double sourceData[] = new double[] { 1.5, 2.5, 3.5 }; double sourceData[] = new double[] { 1.5, 2.5, 3.5 };
SafeArray saUnderTest = new SafeArray(Variant.VariantDouble, SafeArray saUnderTest = new SafeArray(Variant.VariantDouble,
sourceData.length); sourceData.length);
saUnderTest.fromDoubleArray(sourceData); saUnderTest.fromDoubleArray(sourceData);
double[] extractedFromSafeArray = saUnderTest.toDoubleArray(); double[] extractedFromSafeArray = saUnderTest.toDoubleArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]); assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
} }
assertEquals("single get failed: ", sourceData[2], saUnderTest assertEquals("single get failed: ", sourceData[2], saUnderTest
.getDouble(2)); .getDouble(2));
} }
/** /**
* *
*/ */
public void testFloatSafeArray() { public void testFloatSafeArray() {
float sourceData[] = new float[] { 1.5F, 2.5F, 3.5F }; float sourceData[] = new float[] { 1.5F, 2.5F, 3.5F };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3); SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromFloatArray(sourceData); saUnderTest.fromFloatArray(sourceData);
float[] extractedFromSafeArray = saUnderTest.toFloatArray(); float[] extractedFromSafeArray = saUnderTest.toFloatArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]); assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
} }
} }
/** /**
* *
*/ */
public void testBooleanSafeArray() { public void testBooleanSafeArray() {
boolean sourceData[] = new boolean[] { true, false, true, false }; boolean sourceData[] = new boolean[] { true, false, true, false };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3); SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromBooleanArray(sourceData); saUnderTest.fromBooleanArray(sourceData);
boolean[] extractedFromSafeArray = saUnderTest.toBooleanArray(); boolean[] extractedFromSafeArray = saUnderTest.toBooleanArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]); assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
} }
assertEquals("single get failed: ", sourceData[2], saUnderTest assertEquals("single get failed: ", sourceData[2], saUnderTest
.getBoolean(2)); .getBoolean(2));
// test conversion // test conversion
Variant extractedFromSafeArrayVariant[] = saUnderTest.toVariantArray(); Variant extractedFromSafeArrayVariant[] = saUnderTest.toVariantArray();
for (int i = 0; i < extractedFromSafeArrayVariant.length; i++) { for (int i = 0; i < extractedFromSafeArrayVariant.length; i++) {
assertEquals("" + i, sourceData[i], assertEquals("" + i, sourceData[i],
extractedFromSafeArrayVariant[i].getBoolean()); extractedFromSafeArrayVariant[i].getBoolean());
} }
} }
/** /**
* *
*/ */
public void testCharSafeArray() { public void testCharSafeArray() {
char sourceData[] = new char[] { 'a', 'b', 'c', 'd' }; char sourceData[] = new char[] { 'a', 'b', 'c', 'd' };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3); SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromCharArray(sourceData); saUnderTest.fromCharArray(sourceData);
char[] extractedFromSafeArray = saUnderTest.toCharArray(); char[] extractedFromSafeArray = saUnderTest.toCharArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]); assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
} }
assertEquals("single get failed: ", sourceData[2], saUnderTest assertEquals("single get failed: ", sourceData[2], saUnderTest
.getChar(2)); .getChar(2));
} }
/** /**
* *
*/ */
public void testStringSafeArray() { public void testStringSafeArray() {
String sourceData[] = new String[] { "hello", "from", "java", "com" }; String sourceData[] = new String[] { "hello", "from", "java", "com" };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3); SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromStringArray(sourceData); saUnderTest.fromStringArray(sourceData);
String[] extractedFromSafeArray = saUnderTest.toStringArray(); String[] extractedFromSafeArray = saUnderTest.toStringArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]); assertEquals("" + i, sourceData[i], extractedFromSafeArray[i]);
} }
assertEquals("single get failed: ", sourceData[2], saUnderTest assertEquals("single get failed: ", sourceData[2], saUnderTest
.getString(2)); .getString(2));
// test conversion // test conversion
Variant extractedFromSafeArrayVariant[] = saUnderTest.toVariantArray(); Variant extractedFromSafeArrayVariant[] = saUnderTest.toVariantArray();
for (int i = 0; i < extractedFromSafeArrayVariant.length; i++) { for (int i = 0; i < extractedFromSafeArrayVariant.length; i++) {
assertEquals("" + i, sourceData[i], assertEquals("" + i, sourceData[i],
extractedFromSafeArrayVariant[i].getString()); extractedFromSafeArrayVariant[i].getString());
} }
} }
/** /**
* Verify we get expected unicode this test forces this file to UTF-16 :-( * Verify we get expected unicode this test forces this file to UTF-16 :-(
* SF 2847577 * SF 2847577
* *
* <pre> * <pre>
* The console output will be the following without unicode support: * The console output will be the following without unicode support:
* Russian: <20>? уÑ<C692><>?<3F><>?¸<> * Russian: <20>? уÑ<C692><>?<3F><>?¸<>
* *
* Expected: * Expected:
* Russian: Ру<D0A0>?<3F>?кий * Russian: Ру<D0A0>?<3F>?кий
*</pre> *</pre>
*/ */
public void testStringUnicode() { public void testStringUnicode() {
SafeArray sa = new SafeArray(Variant.VariantString, 1); SafeArray sa = new SafeArray(Variant.VariantString, 1);
sa.setString(0, "Russian: \u0420\u0443\u0441\u0441\u043A\u0438\u0439"); sa.setString(0, "Russian: \u0420\u0443\u0441\u0441\u043A\u0438\u0439");
String result = sa.getString(0); String result = sa.getString(0);
Assert.assertEquals("Russian: Ру<D0A0>?<3F>?кий", result); Assert.assertEquals("Russian: Ру<D0A0>?<3F>?кий", result);
// System.out.println(sa.getString(0)); // System.out.println(sa.getString(0));
} }
/** /**
* *
*/ */
public void testVariantSafeArray() { public void testVariantSafeArray() {
Variant sourceData[] = new Variant[] { new Variant(1), Variant sourceData[] = new Variant[] { new Variant(1),
new Variant(2.3), new Variant("hi") }; new Variant(2.3), new Variant("hi") };
SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3); SafeArray saUnderTest = new SafeArray(Variant.VariantVariant, 3);
saUnderTest.fromVariantArray(sourceData); saUnderTest.fromVariantArray(sourceData);
Variant[] extractedFromSafeArray = saUnderTest.toVariantArray(); Variant[] extractedFromSafeArray = saUnderTest.toVariantArray();
for (int i = 0; i < extractedFromSafeArray.length; i++) { for (int i = 0; i < extractedFromSafeArray.length; i++) {
assertEquals("" + i, sourceData[i].toString(), assertEquals("" + i, sourceData[i].toString(),
extractedFromSafeArray[i].toString()); extractedFromSafeArray[i].toString());
} }
assertEquals("single get failed: ", sourceData[2].toString(), assertEquals("single get failed: ", sourceData[2].toString(),
saUnderTest.getVariant(2).toString()); saUnderTest.getVariant(2).toString());
} }
/** /**
* test method that verifies setting of bounds in multi-dimensional arrays * test method that verifies setting of bounds in multi-dimensional arrays
*/ */
public void testSafeArrayNumDimensions() { public void testSafeArrayNumDimensions() {
int[] lowerBounds = new int[] { 0, 0, 0 }; int[] lowerBounds = new int[] { 0, 0, 0 };
int[] dimensionSizes = new int[] { 3, 3, 3 }; int[] dimensionSizes = new int[] { 3, 3, 3 };
SafeArray sa3x3 = new SafeArray(Variant.VariantVariant, lowerBounds, SafeArray sa3x3 = new SafeArray(Variant.VariantVariant, lowerBounds,
dimensionSizes); dimensionSizes);
Assert.assertEquals(3, sa3x3.getNumDim()); Assert.assertEquals(3, sa3x3.getNumDim());
// System.out.println("Num Dimensions = " + sa3x3.getNumDim()); // System.out.println("Num Dimensions = " + sa3x3.getNumDim());
for (int safeArrayDimension = 1; safeArrayDimension <= sa3x3 for (int safeArrayDimension = 1; safeArrayDimension <= sa3x3
.getNumDim(); safeArrayDimension++) { .getNumDim(); safeArrayDimension++) {
int configArrayIndex = safeArrayDimension - 1; int configArrayIndex = safeArrayDimension - 1;
assertEquals("unexpected lower bound value ", assertEquals("unexpected lower bound value ",
lowerBounds[configArrayIndex], sa3x3 lowerBounds[configArrayIndex], sa3x3
.getLBound(safeArrayDimension)); .getLBound(safeArrayDimension));
assertEquals("unexpeced upper bound value ", assertEquals("unexpeced upper bound value ",
(dimensionSizes[configArrayIndex] - 1) (dimensionSizes[configArrayIndex] - 1)
+ lowerBounds[configArrayIndex], sa3x3 + lowerBounds[configArrayIndex], sa3x3
.getUBound(safeArrayDimension)); .getUBound(safeArrayDimension));
} }
} }
/** /**
* test the set and get method on multi-dimensional arrays * test the set and get method on multi-dimensional arrays
*/ */
public void testSafeArrayMultiDimension() { public void testSafeArrayMultiDimension() {
int[] lowerBounds = new int[] { 0, 0, 0 }; int[] lowerBounds = new int[] { 0, 0, 0 };
int[] dimensionSizes = new int[] { 3, 3, 3 }; int[] dimensionSizes = new int[] { 3, 3, 3 };
SafeArray sa3x3 = new SafeArray(Variant.VariantVariant, lowerBounds, SafeArray sa3x3 = new SafeArray(Variant.VariantVariant, lowerBounds,
dimensionSizes); dimensionSizes);
int[] indices = new int[] { 0, 0, 0 }; int[] indices = new int[] { 0, 0, 0 };
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
indices[0] = i; indices[0] = i;
for (int j = 0; j < 3; j++) { for (int j = 0; j < 3; j++) {
indices[1] = j; indices[1] = j;
for (int k = 0; k < 3; k++) { for (int k = 0; k < 3; k++) {
indices[2] = k; indices[2] = k;
int fill = 0; int fill = 0;
fill = i * 100 + j * 10 + k; fill = i * 100 + j * 10 + k;
sa3x3.setInt(indices, fill); sa3x3.setInt(indices, fill);
assertEquals(fill, sa3x3.getInt(indices)); assertEquals(fill, sa3x3.getInt(indices));
long fillLong = 0L; long fillLong = 0L;
// Pick a number bigger than 2^31 // Pick a number bigger than 2^31
fillLong = 100000000000000L * fill; fillLong = 100000000000000L * fill;
sa3x3.setLong(indices, fillLong); sa3x3.setLong(indices, fillLong);
assertEquals(fillLong, sa3x3.getLong(indices)); assertEquals(fillLong, sa3x3.getLong(indices));
} }
} }
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.safearray; package com.jacob.test.safearray;
@@ -53,259 +53,259 @@ import com.jacob.test.BaseTestCase;
*/ */
public class SafeArrayContents extends BaseTestCase { public class SafeArrayContents extends BaseTestCase {
public static void printArray(boolean a[]) { public static void printArray(boolean a[]) {
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
} }
System.out.println("]"); System.out.println("]");
} }
public static void printArray(int a[]) { public static void printArray(int a[]) {
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
} }
System.out.println("]"); System.out.println("]");
} }
public static void printArray(short a[]) { public static void printArray(short a[]) {
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
} }
System.out.println("]"); System.out.println("]");
} }
public static void printArray(byte a[]) { public static void printArray(byte a[]) {
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
} }
System.out.println("]"); System.out.println("]");
} }
public static void printArray(double a[]) { public static void printArray(double a[]) {
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
} }
System.out.println("]"); System.out.println("]");
} }
public static void printArray(float a[]) { public static void printArray(float a[]) {
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
} }
System.out.println("]"); System.out.println("]");
} }
public static void printArray(String a[]) { public static void printArray(String a[]) {
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
} }
System.out.println("]"); System.out.println("]");
} }
public static void printArray(Variant a[]) { public static void printArray(Variant a[]) {
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
} }
System.out.println("]"); System.out.println("]");
} }
public static void printArray(char a[]) { public static void printArray(char a[]) {
System.out.print("["); System.out.print("[");
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i] + " "); System.out.print(" " + a[i] + " ");
} }
System.out.println("]"); System.out.println("]");
} }
public void testSafeArrayContents() { public void testSafeArrayContents() {
// int // int
System.out.println("Int"); System.out.println("Int");
SafeArray ia = new SafeArray(Variant.VariantInt, 4); SafeArray ia = new SafeArray(Variant.VariantInt, 4);
System.out.println("elem size:" + ia.getElemSize()); System.out.println("elem size:" + ia.getElemSize());
int iack[] = new int[] { 100000, 200000, 300000, 400000 }; int iack[] = new int[] { 100000, 200000, 300000, 400000 };
printArray(iack); printArray(iack);
ia.fromIntArray(iack); ia.fromIntArray(iack);
iack = ia.toIntArray(); iack = ia.toIntArray();
printArray(iack); printArray(iack);
int i4[] = new int[4]; int i4[] = new int[4];
ia.getInts(0, 4, i4, 0); ia.getInts(0, 4, i4, 0);
printArray(i4); printArray(i4);
SafeArray ia2 = new SafeArray(Variant.VariantInt, 4); SafeArray ia2 = new SafeArray(Variant.VariantInt, 4);
ia2.setInts(0, 4, i4, 0); ia2.setInts(0, 4, i4, 0);
iack = ia2.toIntArray(); iack = ia2.toIntArray();
printArray(iack); printArray(iack);
// double // double
System.out.println("Double"); System.out.println("Double");
SafeArray da = new SafeArray(Variant.VariantDouble, 4); SafeArray da = new SafeArray(Variant.VariantDouble, 4);
System.out.println("elem size:" + da.getElemSize()); System.out.println("elem size:" + da.getElemSize());
double dack[] = new double[] { 123.456, 456.123, 1234567.89, 12.3456789 }; double dack[] = new double[] { 123.456, 456.123, 1234567.89, 12.3456789 };
printArray(dack); printArray(dack);
da.fromDoubleArray(dack); da.fromDoubleArray(dack);
dack = da.toDoubleArray(); dack = da.toDoubleArray();
printArray(dack); printArray(dack);
double d4[] = new double[4]; double d4[] = new double[4];
da.getDoubles(0, 4, d4, 0); da.getDoubles(0, 4, d4, 0);
printArray(d4); printArray(d4);
SafeArray da2 = new SafeArray(Variant.VariantDouble, 4); SafeArray da2 = new SafeArray(Variant.VariantDouble, 4);
da2.setDoubles(0, 4, d4, 0); da2.setDoubles(0, 4, d4, 0);
dack = da2.toDoubleArray(); dack = da2.toDoubleArray();
printArray(dack); printArray(dack);
// float // float
System.out.println("Float"); System.out.println("Float");
SafeArray fa = new SafeArray(Variant.VariantFloat, 4); SafeArray fa = new SafeArray(Variant.VariantFloat, 4);
System.out.println("elem size:" + fa.getElemSize()); System.out.println("elem size:" + fa.getElemSize());
float fack[] = new float[] { 123.456F, 456.123F, 1234567.89F, float fack[] = new float[] { 123.456F, 456.123F, 1234567.89F,
12.3456789F }; 12.3456789F };
printArray(fack); printArray(fack);
fa.fromFloatArray(fack); fa.fromFloatArray(fack);
fack = fa.toFloatArray(); fack = fa.toFloatArray();
printArray(fack); printArray(fack);
float f4[] = new float[4]; float f4[] = new float[4];
fa.getFloats(0, 4, f4, 0); fa.getFloats(0, 4, f4, 0);
printArray(f4); printArray(f4);
SafeArray fa2 = new SafeArray(Variant.VariantFloat, 4); SafeArray fa2 = new SafeArray(Variant.VariantFloat, 4);
fa2.setFloats(0, 4, f4, 0); fa2.setFloats(0, 4, f4, 0);
fack = fa2.toFloatArray(); fack = fa2.toFloatArray();
printArray(fack); printArray(fack);
// boolean // boolean
System.out.println("Boolean"); System.out.println("Boolean");
SafeArray ba = new SafeArray(Variant.VariantBoolean, 4); SafeArray ba = new SafeArray(Variant.VariantBoolean, 4);
System.out.println("elem size:" + ba.getElemSize()); System.out.println("elem size:" + ba.getElemSize());
boolean back[] = new boolean[] { true, false, true, false }; boolean back[] = new boolean[] { true, false, true, false };
printArray(back); printArray(back);
ba.fromBooleanArray(back); ba.fromBooleanArray(back);
back = ba.toBooleanArray(); back = ba.toBooleanArray();
printArray(back); printArray(back);
boolean b4[] = new boolean[4]; boolean b4[] = new boolean[4];
ba.getBooleans(0, 4, b4, 0); ba.getBooleans(0, 4, b4, 0);
printArray(b4); printArray(b4);
SafeArray ba2 = new SafeArray(Variant.VariantBoolean, 4); SafeArray ba2 = new SafeArray(Variant.VariantBoolean, 4);
ba2.setBooleans(0, 4, b4, 0); ba2.setBooleans(0, 4, b4, 0);
back = ba2.toBooleanArray(); back = ba2.toBooleanArray();
printArray(back); printArray(back);
// char // char
System.out.println("Char"); System.out.println("Char");
SafeArray ca = new SafeArray(Variant.VariantShort, 4); SafeArray ca = new SafeArray(Variant.VariantShort, 4);
System.out.println("elem size:" + ca.getElemSize()); System.out.println("elem size:" + ca.getElemSize());
char cack[] = new char[] { 'a', 'b', 'c', 'd' }; char cack[] = new char[] { 'a', 'b', 'c', 'd' };
printArray(cack); printArray(cack);
ca.fromCharArray(cack); ca.fromCharArray(cack);
cack = ca.toCharArray(); cack = ca.toCharArray();
printArray(cack); printArray(cack);
char c4[] = new char[4]; char c4[] = new char[4];
ca.getChars(0, 4, c4, 0); ca.getChars(0, 4, c4, 0);
printArray(c4); printArray(c4);
SafeArray ca2 = new SafeArray(Variant.VariantShort, 4); SafeArray ca2 = new SafeArray(Variant.VariantShort, 4);
ca2.setChars(0, 4, c4, 0); ca2.setChars(0, 4, c4, 0);
cack = ca2.toCharArray(); cack = ca2.toCharArray();
printArray(cack); printArray(cack);
// short // short
System.out.println("Short"); System.out.println("Short");
SafeArray sha = new SafeArray(Variant.VariantShort, 4); SafeArray sha = new SafeArray(Variant.VariantShort, 4);
System.out.println("elem size:" + sha.getElemSize()); System.out.println("elem size:" + sha.getElemSize());
short shack[] = new short[] { 1000, 2000, 3000, 4000 }; short shack[] = new short[] { 1000, 2000, 3000, 4000 };
printArray(shack); printArray(shack);
sha.fromShortArray(shack); sha.fromShortArray(shack);
shack = sha.toShortArray(); shack = sha.toShortArray();
printArray(shack); printArray(shack);
short sh4[] = new short[4]; short sh4[] = new short[4];
sha.getShorts(0, 4, sh4, 0); sha.getShorts(0, 4, sh4, 0);
printArray(sh4); printArray(sh4);
SafeArray sha2 = new SafeArray(Variant.VariantShort, 4); SafeArray sha2 = new SafeArray(Variant.VariantShort, 4);
sha2.setShorts(0, 4, sh4, 0); sha2.setShorts(0, 4, sh4, 0);
shack = sha2.toShortArray(); shack = sha2.toShortArray();
printArray(shack); printArray(shack);
// string // string
System.out.println("String"); System.out.println("String");
SafeArray sa = new SafeArray(Variant.VariantString, 4); SafeArray sa = new SafeArray(Variant.VariantString, 4);
System.out.println("elem size:" + sa.getElemSize()); System.out.println("elem size:" + sa.getElemSize());
String sack[] = new String[] { "aa", "bb", "cc", "dd" }; String sack[] = new String[] { "aa", "bb", "cc", "dd" };
printArray(sack); printArray(sack);
sa.fromStringArray(sack); sa.fromStringArray(sack);
sack = sa.toStringArray(); sack = sa.toStringArray();
printArray(sack); printArray(sack);
String s4[] = new String[4]; String s4[] = new String[4];
sa.getStrings(0, 4, s4, 0); sa.getStrings(0, 4, s4, 0);
printArray(s4); printArray(s4);
SafeArray sa2 = new SafeArray(Variant.VariantString, 4); SafeArray sa2 = new SafeArray(Variant.VariantString, 4);
sa2.setStrings(0, 4, s4, 0); sa2.setStrings(0, 4, s4, 0);
sack = sa2.toStringArray(); sack = sa2.toStringArray();
printArray(sack); printArray(sack);
// variant // variant
System.out.println("Variant"); System.out.println("Variant");
SafeArray va = new SafeArray(Variant.VariantVariant, 4); SafeArray va = new SafeArray(Variant.VariantVariant, 4);
System.out.println("elem size:" + va.getElemSize()); System.out.println("elem size:" + va.getElemSize());
Variant vack[] = new Variant[] { new Variant(1), new Variant(2.3), Variant vack[] = new Variant[] { new Variant(1), new Variant(2.3),
new Variant(true), new Variant("four"), }; new Variant(true), new Variant("four"), };
printArray(vack); printArray(vack);
va.fromVariantArray(vack); va.fromVariantArray(vack);
vack = va.toVariantArray(); vack = va.toVariantArray();
printArray(vack); printArray(vack);
Variant v4[] = new Variant[4]; Variant v4[] = new Variant[4];
va.getVariants(0, 4, v4, 0); va.getVariants(0, 4, v4, 0);
printArray(v4); printArray(v4);
SafeArray va2 = new SafeArray(Variant.VariantVariant, 4); SafeArray va2 = new SafeArray(Variant.VariantVariant, 4);
va2.setVariants(0, 4, v4, 0); va2.setVariants(0, 4, v4, 0);
vack = va2.toVariantArray(); vack = va2.toVariantArray();
printArray(vack); printArray(vack);
// byte // byte
System.out.println("Byte"); System.out.println("Byte");
SafeArray bba = new SafeArray(Variant.VariantByte, 4); SafeArray bba = new SafeArray(Variant.VariantByte, 4);
System.out.println("elem size:" + bba.getElemSize()); System.out.println("elem size:" + bba.getElemSize());
byte bback[] = new byte[] { 0x1, 0x2, 0x3, 0x4 }; byte bback[] = new byte[] { 0x1, 0x2, 0x3, 0x4 };
printArray(bback); printArray(bback);
bba.fromByteArray(bback); bba.fromByteArray(bback);
bback = bba.toByteArray(); bback = bba.toByteArray();
printArray(bback); printArray(bback);
byte bb4[] = new byte[4]; byte bb4[] = new byte[4];
bba.getBytes(0, 4, bb4, 0); bba.getBytes(0, 4, bb4, 0);
printArray(bb4); printArray(bb4);
SafeArray bba2 = new SafeArray(Variant.VariantByte, 4); SafeArray bba2 = new SafeArray(Variant.VariantByte, 4);
bba2.setBytes(0, 4, bb4, 0); bba2.setBytes(0, 4, bb4, 0);
bback = bba2.toByteArray(); bback = bba2.toByteArray();
printArray(bback); printArray(bback);
try { try {
// this should throw ComException // this should throw ComException
bba2.fromCharArray(new char[] { 'a' }); bba2.fromCharArray(new char[] { 'a' });
fail("Failed to catch expected exception"); fail("Failed to catch expected exception");
} catch (ComFailException cfe) { } catch (ComFailException cfe) {
// do nothing // do nothing
// cfe.printStackTrace(); // cfe.printStackTrace();
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.safearray; package com.jacob.test.safearray;
@@ -49,35 +49,35 @@ import com.jacob.test.BaseTestCase;
* Test class to verify dispatch with SafeArray * Test class to verify dispatch with SafeArray
*/ */
public class SafeArrayDispatchTest extends BaseTestCase { public class SafeArrayDispatchTest extends BaseTestCase {
public void testDispatchWithSafeArray() { public void testDispatchWithSafeArray() {
try { try {
String scriptCommand = "1+(2*4)-3"; String scriptCommand = "1+(2*4)-3";
String lang = "VBScript"; String lang = "VBScript";
ActiveXComponent sControl = new ActiveXComponent("ScriptControl"); ActiveXComponent sControl = new ActiveXComponent("ScriptControl");
Dispatch.put(sControl, "Language", lang); Dispatch.put(sControl, "Language", lang);
Variant result = Dispatch.call(sControl, "Eval", scriptCommand); Variant result = Dispatch.call(sControl, "Eval", scriptCommand);
assertTrue(result.toString().equals("6")); assertTrue(result.toString().equals("6"));
// wrap the script control in a variant // wrap the script control in a variant
Variant v = new Variant(sControl); Variant v = new Variant(sControl);
// create a safe array of type dispatch // create a safe array of type dispatch
SafeArray sa = new SafeArray(Variant.VariantDispatch, 1); SafeArray sa = new SafeArray(Variant.VariantDispatch, 1);
// put the variant in the array // put the variant in the array
sa.setVariant(0, v); sa.setVariant(0, v);
// take it back out // take it back out
Variant v2 = sa.getVariant(0); Variant v2 = sa.getVariant(0);
Dispatch d = v2.toDispatch(); Dispatch d = v2.toDispatch();
// make sure you can call eval on it // make sure you can call eval on it
result = Dispatch.call(d, "Eval", scriptCommand); result = Dispatch.call(d, "Eval", scriptCommand);
assertTrue(result.toString().equals("6")); assertTrue(result.toString().equals("6"));
} catch (ComException e) { } catch (ComException e) {
e.printStackTrace(); e.printStackTrace();
fail("script failure " + e); fail("script failure " + e);
} }
} }
} }

View File

@@ -18,23 +18,23 @@
* *
* This file incorporates work covered by the following copyright and * This file incorporates work covered by the following copyright and
* permission notice: * permission notice:
* Copyright (c) 1999-2004 Sourceforge JACOB Project. * Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com). * All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project * Get more information about JACOB at http://sourceforge.net/projects/jacob-project
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either * License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version. * version 2.1 of the License, or (at your option) any later version.
* *
* This library is distributed in the hope that it will be useful, * This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. * Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.jacob.test.safearray; package com.jacob.test.safearray;
@@ -59,157 +59,157 @@ import com.jacob.test.BaseTestCase;
*/ */
public class SafeArrayLeak extends BaseTestCase { public class SafeArrayLeak extends BaseTestCase {
/** /**
* ---------------------------------------------------------------------------------------------------------------------------- * ----------------------------------------------------------------------------------------------------------------------------
* *
* ---------------------------------------------------------------------------------------------------------------------------- * ----------------------------------------------------------------------------------------------------------------------------
*/ */
public void testLeakWithSetString() { public void testLeakWithSetString() {
ActiveXComponent xl = null; ActiveXComponent xl = null;
Dispatch workbooks = null; Dispatch workbooks = null;
Dispatch workbook = null; Dispatch workbook = null;
Dispatch workSheets = null; Dispatch workSheets = null;
Dispatch sheet = null; Dispatch sheet = null;
Dispatch tabCells = null; Dispatch tabCells = null;
SafeArray sa = null; SafeArray sa = null;
// -Dcom.jacob.autogc=true // -Dcom.jacob.autogc=true
System.out.println("Jacob version: " + JacobReleaseInfo.getBuildVersion()); System.out.println("Jacob version: " + JacobReleaseInfo.getBuildVersion());
for (int t = 0; t < 10; t++) { for (int t = 0; t < 10; t++) {
// look at a large range of cells // look at a large range of cells
String position = "A7:DM8934"; String position = "A7:DM8934";
try { try {
xl = new ActiveXComponent("Excel.Application"); xl = new ActiveXComponent("Excel.Application");
System.out System.out
.println("Excel version=" + xl.getProperty("Version")); .println("Excel version=" + xl.getProperty("Version"));
xl.setProperty("Visible", new Variant(false)); xl.setProperty("Visible", new Variant(false));
workbooks = xl.getProperty("Workbooks").toDispatch(); workbooks = xl.getProperty("Workbooks").toDispatch();
workbook = Dispatch.get(workbooks, "Add").toDispatch(); workbook = Dispatch.get(workbooks, "Add").toDispatch();
workSheets = Dispatch.get(workbook, "Worksheets").toDispatch(); workSheets = Dispatch.get(workbook, "Worksheets").toDispatch();
sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch(); sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
// grab the whole range specified above. // grab the whole range specified above.
tabCells = Dispatch.invoke(sheet, "Range", Dispatch.Get, tabCells = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] { position }, new int[1]).toDispatch(); new Object[] { position }, new int[1]).toDispatch();
sa = Dispatch.get(tabCells, "Value").toSafeArray(true); sa = Dispatch.get(tabCells, "Value").toSafeArray(true);
System.out.println("Ub0=" + sa.getUBound(1)); // nbCol System.out.println("Ub0=" + sa.getUBound(1)); // nbCol
System.out.println("Ub1=" + sa.getUBound(2)); // nbLgn System.out.println("Ub1=" + sa.getUBound(2)); // nbLgn
// number of rows // number of rows
int nbLgn = sa.getUBound(2); int nbLgn = sa.getUBound(2);
// number of columns // number of columns
int nbCol = sa.getUBound(1); int nbCol = sa.getUBound(1);
int[] colLgn = new int[] { 0, 0 }; int[] colLgn = new int[] { 0, 0 };
// now set a value on every cell in the range we retrieved // now set a value on every cell in the range we retrieved
for (int i = 1; i <= nbLgn; i++) { for (int i = 1; i <= nbLgn; i++) {
colLgn[1] = i; colLgn[1] = i;
for (int j = 1; j <= nbCol; j++) { for (int j = 1; j <= nbCol; j++) {
colLgn[0] = j; colLgn[0] = j;
// this one works with out a leak 1.13-M3 // this one works with out a leak 1.13-M3
// sa.setString(j, i, "test"); // sa.setString(j, i, "test");
// This one leaks with 1.13-M3 and earlier // This one leaks with 1.13-M3 and earlier
sa.setString(colLgn, "test"); sa.setString(colLgn, "test");
} }
} }
Dispatch.put(tabCells, "Value", sa); Dispatch.put(tabCells, "Value", sa);
Variant f = new Variant(false); Variant f = new Variant(false);
Dispatch.call(workbook, "Close", f); Dispatch.call(workbook, "Close", f);
System.out.println("Close"); System.out.println("Close");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (sa != null) { if (sa != null) {
try { try {
sa.safeRelease(); sa.safeRelease();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
sa = null; sa = null;
} }
} }
if (tabCells != null) { if (tabCells != null) {
try { try {
tabCells.safeRelease(); tabCells.safeRelease();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
tabCells = null; tabCells = null;
} }
} }
if (sheet != null) { if (sheet != null) {
try { try {
sheet.safeRelease(); sheet.safeRelease();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
sheet = null; sheet = null;
} }
} }
if (workSheets != null) { if (workSheets != null) {
try { try {
workSheets.safeRelease(); workSheets.safeRelease();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
workSheets = null; workSheets = null;
} }
} }
if (workbook != null) { if (workbook != null) {
try { try {
workbook.safeRelease(); workbook.safeRelease();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
workbook = null; workbook = null;
} }
} }
if (workbooks != null) { if (workbooks != null) {
try { try {
workbooks.safeRelease(); workbooks.safeRelease();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
workbooks = null; workbooks = null;
} }
} }
if (xl != null) { if (xl != null) {
try { try {
xl.invoke("Quit", new Variant[] {}); xl.invoke("Quit", new Variant[] {});
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
try { try {
xl.safeRelease(); xl.safeRelease();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
xl = null; xl = null;
} }
} }
ComThread.Release(); ComThread.Release();
} }
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show More