use of com.sun.jna.platform.win32.COM.COMException in project jna by java-native-access.
the class SAFEARRAYTest method testADODB.
/**
* Test assumption: The windows search provider is present and holds at least
* five entries. If this assumption is not met, this test fails.
*/
@Test
public void testADODB() {
ObjectFactory fact = new ObjectFactory();
// Open a record set with a sample search (basicly get the first five
// entries from the search index
Connection conn = fact.createObject(Connection.class);
conn.Open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';", "", "", -1);
Recordset recordset = fact.createObject(Recordset.class);
recordset.Open("SELECT TOP 5 System.ItemPathDisplay, System.ItemName, System.ItemUrl, System.DateCreated FROM SYSTEMINDEX ORDER BY System.ItemUrl", conn, CursorTypeEnum.adOpenUnspecified, LockTypeEnum.adLockUnspecified, -1);
// Save complete list for comparison with subscript list
List<String> urls = new ArrayList<String>(5);
List<String> names = new ArrayList<String>(5);
while (!recordset.getEOF()) {
WinNT.HRESULT hr;
// Fetch (all) five rows and extract SAFEARRAY
SAFEARRAY sa = recordset.GetRows(5);
assertThat(sa.getDimensionCount(), is(2));
// Test getting bounds via automation functions SafeArrayGetLBound
// and SafeArrayGetUBound
// 5 rows (dimension 1) and 4 (dimension 2) columns should be
// returned, the indices are zero-based, the lower bounds are
// always zero
//
// Dimensions are inverted between SafeArray and java, so
// in this case row dimension 2 retrieves row count,
// dimension 1 retrieves column count
WinDef.LONGByReference res = new WinDef.LONGByReference();
hr = OleAuto.INSTANCE.SafeArrayGetLBound(sa, new UINT(2), res);
assert COMUtils.SUCCEEDED(hr);
assertThat(res.getValue().intValue(), is(0));
hr = OleAuto.INSTANCE.SafeArrayGetUBound(sa, new UINT(2), res);
assert COMUtils.SUCCEEDED(hr);
assertThat(res.getValue().intValue(), is(4));
hr = OleAuto.INSTANCE.SafeArrayGetLBound(sa, new UINT(1), res);
assert COMUtils.SUCCEEDED(hr);
assertThat(res.getValue().intValue(), is(0));
hr = OleAuto.INSTANCE.SafeArrayGetUBound(sa, new UINT(1), res);
assert COMUtils.SUCCEEDED(hr);
assertThat(res.getValue().intValue(), is(3));
// Get dimensions directly from structure
// lLbound contains lowerBound (first index)
// cElements contains count of elements
int row_lower = sa.rgsabound[0].lLbound.intValue();
int row_count = sa.rgsabound[0].cElements.intValue();
int column_lower = sa.rgsabound[1].lLbound.intValue();
int column_count = sa.rgsabound[1].cElements.intValue();
assertThat(row_lower, is(0));
assertThat(row_count, is(5));
assertThat(column_lower, is(0));
assertThat(column_count, is(4));
// Use Wrapper methods
assertThat(sa.getLBound(0), is(0));
assertThat(sa.getUBound(0), is(4));
assertThat(sa.getLBound(1), is(0));
assertThat(sa.getUBound(1), is(3));
// Columns 1 - 3 return Strings, Column 4 returns a date
for (int rowIdx = row_lower; rowIdx < row_lower + row_count; rowIdx++) {
for (int colIdx = column_lower; colIdx < column_lower + column_count; colIdx++) {
VARIANT result = (VARIANT) sa.getElement(rowIdx, colIdx);
Pointer pv = sa.ptrOfIndex(rowIdx, colIdx);
VARIANT result2 = new VARIANT(pv);
COMUtils.checkRC(hr);
if (colIdx == 3) {
assert (result.getVarType().intValue() & Variant.VT_DATE) > 0;
assert (result2.getVarType().intValue() & Variant.VT_DATE) > 0;
} else {
assert (result.getVarType().intValue() & Variant.VT_BSTR) > 0;
assert (result2.getVarType().intValue() & Variant.VT_BSTR) > 0;
}
// Only clear result, as SafeArrayGetElement creates a copy
// result2 is a view into the SafeArray
OleAuto.INSTANCE.VariantClear(result);
}
}
// Access SafeArray directly
sa.lock();
try {
// Map the returned array to java
VARIANT[] variantArray = (VARIANT[]) (new VARIANT(sa.pvData.getPointer()).toArray(row_count * column_count));
for (int rowIdx = 0; rowIdx < row_count; rowIdx++) {
for (int colIdx = 0; colIdx < column_count; colIdx++) {
int index = rowIdx * column_count + colIdx;
VARIANT result = variantArray[index];
if (colIdx == 3) {
assert (result.getVarType().intValue() & Variant.VT_DATE) > 0;
} else {
assert (result.getVarType().intValue() & Variant.VT_BSTR) > 0;
}
// see comment for urls
if (colIdx == 2) {
urls.add(result.stringValue());
} else if (colIdx == 1) {
names.add(result.stringValue());
}
}
}
} finally {
sa.unlock();
}
// Access SafeArray directly - Variant 2
Pointer data = sa.accessData();
try {
// Map the returned array to java
VARIANT[] variantArray = (VARIANT[]) (new VARIANT(data).toArray(row_count * column_count));
for (int rowIdx = 0; rowIdx < row_count; rowIdx++) {
for (int colIdx = 0; colIdx < column_count; colIdx++) {
int index = rowIdx * column_count + colIdx;
VARIANT result = variantArray[index];
if (colIdx == 3) {
assert (result.getVarType().intValue() & Variant.VT_DATE) > 0;
} else {
assert (result.getVarType().intValue() & Variant.VT_BSTR) > 0;
}
// see comment for urls
if (colIdx == 2) {
urls.add(result.stringValue());
} else if (colIdx == 1) {
names.add(result.stringValue());
}
}
}
} finally {
sa.unaccessData();
}
sa.destroy();
}
recordset.Close();
// Requery and fetch only columns "System.ItemUrl", "System.ItemName" and "System.ItemUrl"
recordset = fact.createObject(Recordset.class);
recordset.Open("SELECT TOP 5 System.ItemPathDisplay, System.ItemName, System.ItemUrl FROM SYSTEMINDEX ORDER BY System.ItemUrl", conn, CursorTypeEnum.adOpenUnspecified, LockTypeEnum.adLockUnspecified, -1);
// Create SAFEARRAY and wrap it into a VARIANT
// Array is initialized to one element and then redimmed. This is done
// to test SafeArrayRedim, in normal usage it is more efficient to
// intitialize directly to the correct size
SAFEARRAY arr = SAFEARRAY.createSafeArray(1);
arr.putElement(new VARIANT("System.ItemUrl"), 0);
boolean exceptionCaught = false;
try {
arr.putElement(new VARIANT("System.ItemName"), 1);
} catch (COMException ex) {
exceptionCaught = true;
}
assertTrue("Array is initialized to a size of one - it can't hold a second item.", exceptionCaught);
arr.redim(2, 0);
arr.putElement(new VARIANT("System.ItemName"), 1);
assertThat(arr.getDimensionCount(), is(1));
VARIANT columnList = new VARIANT();
columnList.setValue(Variant.VT_ARRAY | Variant.VT_VARIANT, arr);
assert !(recordset.getEOF());
while (!recordset.getEOF()) {
SAFEARRAY sa = recordset.GetRows(5, VARIANT.VARIANT_MISSING, columnList);
assertThat(sa.getDimensionCount(), is(2));
assertThat(sa.getVarType().intValue(), is(Variant.VT_VARIANT));
LONGByReference longRef = new LONGByReference();
OleAuto.INSTANCE.SafeArrayGetLBound(sa, new UINT(2), longRef);
int lowerBound = longRef.getValue().intValue();
assertThat(sa.getLBound(0), equalTo(lowerBound));
OleAuto.INSTANCE.SafeArrayGetUBound(sa, new UINT(2), longRef);
int upperBound = longRef.getValue().intValue();
assertThat(sa.getUBound(0), equalTo(upperBound));
// 5 rows are expected
assertThat(upperBound - lowerBound + 1, is(5));
for (int rowIdx = lowerBound; rowIdx <= upperBound; rowIdx++) {
VARIANT variantItemUrl = (VARIANT) sa.getElement(rowIdx, 0);
VARIANT variantItemName = (VARIANT) sa.getElement(rowIdx, 1);
assertThat(variantItemUrl.stringValue(), is(urls.get(rowIdx)));
assertThat(variantItemName.stringValue(), is(names.get(rowIdx)));
OleAuto.INSTANCE.VariantClear(variantItemUrl);
OleAuto.INSTANCE.VariantClear(variantItemName);
}
sa.destroy();
}
recordset.Close();
// Requery and fetch only columns "System.ItemUrl", "System.ItemName" and "System.ItemUrl"
recordset = fact.createObject(Recordset.class);
recordset.Open("SELECT TOP 5 System.ItemPathDisplay, System.ItemName, System.ItemUrl FROM SYSTEMINDEX ORDER BY System.ItemUrl", conn, CursorTypeEnum.adOpenUnspecified, LockTypeEnum.adLockUnspecified, -1);
assert !(recordset.getEOF());
while (!recordset.getEOF()) {
Object[][] data = (Object[][]) OaIdlUtil.toPrimitiveArray(recordset.GetRows(5, VARIANT.VARIANT_MISSING, columnList), true);
assertThat(data.length, is(5));
assertThat(data[0].length, is(2));
for (int rowIdx = 0; rowIdx < data.length; rowIdx++) {
assertThat((String) data[rowIdx][0], is(urls.get(rowIdx)));
assertThat((String) data[rowIdx][1], is(names.get(rowIdx)));
}
}
recordset.Close();
conn.Close();
fact.disposeAll();
}
use of com.sun.jna.platform.win32.COM.COMException in project jna by java-native-access.
the class MSExcel method insertValue.
public void insertValue(String range, String value) throws COMException {
Range pRange = new Range(this.getAutomationProperty("Range", this.getActiveSheet(), new VARIANT(range)));
this.setProperty("Value", pRange, new VARIANT(value));
}
use of com.sun.jna.platform.win32.COM.COMException in project jna by java-native-access.
the class MSOfficeDemo method testMSWord.
public void testMSWord() throws IOException {
File demoDocument = null;
MSWord msWord = null;
// http://msdn.microsoft.com/en-us/library/office/ff839952(v=office.15).aspx
// PDF format.
LONG wdFormatPDF = new LONG(17);
// Rich text format (RTF).
LONG wdFormatRTF = new LONG(6);
// Standard HTML format.
LONG wdFormatHTML = new LONG(8);
// Microsoft Office Word 97 - 2003 binary file format.
LONG wdFormatDocument = new LONG(0);
// Word default document file format. For Word 2010, this is the DOCX format.
LONG wdFormatDocumentDefault = new LONG(16);
// http://msdn.microsoft.com/en-us/library/office/ff838709(v=office.15).aspx
// Original document format.
LONG wdOriginalDocumentFormat = new LONG(1);
// Prompt user to select a document format.
LONG wdPromptUser = new LONG(2);
// Microsoft Word document format.
LONG wdWordDocument = new LONG(0);
try {
msWord = new MSWord();
System.out.println("MSWord version: " + msWord.getVersion());
msWord.setVisible(true);
Helper.sleep(5);
demoDocument = Helper.createNotExistingFile("jnatest", ".doc");
Helper.extractClasspathFileToReal("/com/sun/jna/platform/win32/COM/util/office/resources/jnatest.doc", demoDocument);
msWord.openDocument(demoDocument.getAbsolutePath());
msWord.insertText("Hello from JNA! \n\n");
// wait 10sec. before closing
Helper.sleep(10);
// save in different formats
// pdf format is only supported in MSWord 2007 and above
System.out.println("Wrinting files to: " + Helper.tempDir);
msWord.SaveAs(new File(Helper.tempDir, "jnatestSaveAs.doc").getAbsolutePath(), wdFormatDocument);
msWord.SaveAs(new File(Helper.tempDir, "jnatestSaveAs.pdf").getAbsolutePath(), wdFormatPDF);
msWord.SaveAs(new File(Helper.tempDir, "jnatestSaveAs.rtf").getAbsolutePath(), wdFormatRTF);
msWord.SaveAs(new File(Helper.tempDir, "jnatestSaveAs.html").getAbsolutePath(), wdFormatHTML);
// close and save the document
msWord.closeActiveDocument(false);
msWord.newDocument();
// msWord.openDocument(currentWorkingDir + "jnatest.doc", true);
msWord.insertText("Hello from JNA! \n Please notice that JNA can control MS Word via the new COM interface! \nHere we are creating a new word document and we save it to the 'TEMP' directory!");
// save with no user prompt
msWord.SaveAs(new File(Helper.tempDir, "jnatestNewDoc1.docx").getAbsolutePath(), wdFormatDocumentDefault);
msWord.SaveAs(new File(Helper.tempDir, "jnatestNewDoc2.docx").getAbsolutePath(), wdFormatDocumentDefault);
msWord.SaveAs(new File(Helper.tempDir, "jnatestNewDoc3.docx").getAbsolutePath(), wdFormatDocumentDefault);
// close and save the document
msWord.closeActiveDocument(false);
// open 3 documents
msWord.openDocument(new File(Helper.tempDir, "jnatestNewDoc1.docx").getAbsolutePath());
msWord.insertText("Hello some changes from JNA!\n");
msWord.openDocument(new File(Helper.tempDir, "jnatestNewDoc2.docx").getAbsolutePath());
msWord.insertText("Hello some changes from JNA!\n");
msWord.openDocument(new File(Helper.tempDir, "jnatestNewDoc3.docx").getAbsolutePath());
msWord.insertText("Hello some changes from JNA!\n");
// save the document and prompt the user
msWord.Save(false, wdPromptUser);
} catch (COMException e) {
if (e.getExcepInfo() != null) {
System.out.println("bstrSource: " + e.getExcepInfo().bstrSource);
System.out.println("bstrDescription: " + e.getExcepInfo().bstrDescription);
}
} finally {
if (msWord != null) {
msWord.quit();
}
if (demoDocument != null && demoDocument.exists()) {
demoDocument.delete();
}
}
}
use of com.sun.jna.platform.win32.COM.COMException in project jna by java-native-access.
the class COMBindingBaseObject method init.
private void init(boolean useActiveInstance, GUID clsid, int dwClsContext) throws COMException {
HRESULT hr;
if (useActiveInstance) {
hr = OleAuto.INSTANCE.GetActiveObject(clsid, null, this.pUnknown);
if (COMUtils.SUCCEEDED(hr)) {
this.iUnknown = new Unknown(this.pUnknown.getValue());
hr = iUnknown.QueryInterface(new REFIID(IDispatch.IID_IDISPATCH), this.pDispatch);
} else {
hr = Ole32.INSTANCE.CoCreateInstance(clsid, null, dwClsContext, IDispatch.IID_IDISPATCH, this.pDispatch);
}
} else {
hr = Ole32.INSTANCE.CoCreateInstance(clsid, null, dwClsContext, IDispatch.IID_IDISPATCH, this.pDispatch);
}
COMUtils.checkRC(hr);
this.iDispatch = new Dispatch(this.pDispatch.getValue());
}
use of com.sun.jna.platform.win32.COM.COMException in project jna by java-native-access.
the class COMBindingBaseObject method oleMethod.
protected HRESULT oleMethod(int nType, VARIANT.ByReference pvResult, IDispatch pDisp, DISPID dispId, VARIANT[] pArgs) throws COMException {
if (pDisp == null)
throw new COMException("pDisp (IDispatch) parameter is null!");
// variable declaration
int _argsLen = 0;
VARIANT[] _args = null;
DISPPARAMS.ByReference dp = new DISPPARAMS.ByReference();
EXCEPINFO.ByReference pExcepInfo = new EXCEPINFO.ByReference();
IntByReference puArgErr = new IntByReference();
// make parameter reverse ordering as expected by COM runtime
if ((pArgs != null) && (pArgs.length > 0)) {
_argsLen = pArgs.length;
_args = new VARIANT[_argsLen];
int revCount = _argsLen;
for (int i = 0; i < _argsLen; i++) {
_args[i] = pArgs[--revCount];
}
}
// Handle special-case for property-puts!
if (nType == OleAuto.DISPATCH_PROPERTYPUT) {
dp.setRgdispidNamedArgs(new DISPID[] { OaIdl.DISPID_PROPERTYPUT });
}
// Build DISPPARAMS
if (_argsLen > 0) {
dp.setArgs(_args);
// write 'DISPPARAMS' structure to memory
dp.write();
}
// Apply "fix" according to
// https://www.delphitools.info/2013/04/30/gaining-visual-basic-ole-super-powers/
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms221486(v=vs.85).aspx
//
// Summary: there are methods in the word typelibrary that require both
// PROPERTYGET _and_ METHOD to be set. With only one of these set the call
// fails.
//
// The article from delphitools argues, that automation compatible libraries
// need to be compatible with VisualBasic which does not distingish methods
// and property getters and will set both flags always.
//
// The MSDN article advises this behaviour: "[...] Some languages cannot
// distinguish between retrieving a property and calling a method. In this
//case, you should set the flags DISPATCH_PROPERTYGET and DISPATCH_METHOD.
// [...]"))
//
// This was found when trying to bind InchesToPoints from the _Application
// dispatch interface of the MS Word 15 type library
//
// The signature according the ITypeLib Viewer (OLE/COM Object Viewer):
// [id(0x00000172), helpcontext(0x09700172)]
// single InchesToPoints([in] single Inches);
final int finalNType;
if (nType == OleAuto.DISPATCH_METHOD || nType == OleAuto.DISPATCH_PROPERTYGET) {
finalNType = OleAuto.DISPATCH_METHOD | OleAuto.DISPATCH_PROPERTYGET;
} else {
finalNType = nType;
}
// Make the call!
HRESULT hr = pDisp.Invoke(dispId, new REFIID(Guid.IID_NULL), LOCALE_SYSTEM_DEFAULT, new WinDef.WORD(finalNType), dp, pvResult, pExcepInfo, puArgErr);
COMUtils.checkRC(hr, pExcepInfo, puArgErr);
return hr;
}
Aggregations