/*************************************************************************
*
* $RCSfile: Tools.java,v $
*
* $Revision: 1.9.36.2 $
*
* last change: $Author: vg $ $Date: 2004/01/28 11:31:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*/
package com.sun.star.wizards.common;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XElementAccess;
import com.sun.star.container.XNameAccess;
import com.sun.star.container.XEnumerationAccess;
import com.sun.star.container.XEnumeration;
import com.sun.star.container.XNameContainer;
import com.sun.star.document.XStandaloneDocumentInfo;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.Property;
import com.sun.star.beans.XPropertySet;
import com.sun.star.beans.XMultiPropertySet;
import com.sun.star.beans.PropertyAttribute;
import com.sun.star.comp.servicemanager.ServiceManager;
import com.sun.star.script.XInvocation;
import com.sun.star.connection.XConnector;
import com.sun.star.connection.XConnection;
import com.sun.star.sdb.XCompletedConnection;
import com.sun.star.sdbcx.XColumnsSupplier;
import com.sun.star.sdbc.*;
import com.sun.star.sdb.*;
import com.sun.star.sdbcx.XTablesSupplier;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.ucb.XFileIdentifierConverter;
import com.sun.star.ucb.XSimpleFileAccess;
import com.sun.star.uno.XInterface;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.XNamingService;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Any;
import com.sun.star.uno.Type;
import com.sun.star.sheet.*;
import com.sun.star.document.*;
import com.sun.star.table.*;
import com.sun.star.text.XTextRange;
import com.sun.star.task.XInteractionHandler;
import com.sun.star.style.XStyleLoader;
import com.sun.star.util.XNumberFormats;
import com.sun.star.util.XNumberFormatsSupplier;
import com.sun.star.util.NumberFormat;
import com.sun.star.util.XModifiable;
import com.sun.star.util.XURLTransformer;
import com.sun.star.util.URL;
import com.sun.star.script.XInvocation;
import com.sun.star.lang.Locale;
import com.sun.star.lang.*;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.EventObject;
import com.sun.star.lang.XTypeProvider;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lang.XSingleServiceFactory;
import com.sun.star.registry.XRegistryKey;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.text.XTextDocument;
import com.sun.star.ui.dialogs.XFilePicker;
import com.sun.star.ui.dialogs.XFilterManager;
import com.sun.star.ui.dialogs.XExecutableDialog;
import com.sun.star.ui.dialogs.XFilePickerControlAccess;
import com.sun.star.lang.XInitialization;
import com.sun.star.frame.XFramesSupplier;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XModel;
import com.sun.star.util.XURLTransformer;
import com.sun.star.frame.XDispatch;
import com.sun.star.frame.XDispatchProvider;
import com.sun.star.frame.XModel;
import java.util.*;
import java.io.*;
/**
*
* @author bc93774
* @version
*/
public class Tools {
/** Creates new Tools */
public Tools() {
}
public static String[] copyStringArray(String[] FirstArray){
if (FirstArray != null){
String[] SecondArray = new String[FirstArray.length];
for (int i = 0; i < FirstArray.length; i++){
SecondArray[i] = FirstArray[i];
}
return SecondArray;
}
else
return null;
}
public static int[] initializeintArray(int FieldCount, int nValue){
int[] LocintArray = new int[FieldCount];
for (int i = 0; i < LocintArray.length; i++){
LocintArray[i] = nValue;
}
return LocintArray;
}
public static String[][] getFolderTitles(XMultiServiceFactory xMSF, String FilterName, String FolderName){
String[][] LocLayoutFiles = new String[2][]; //{"",""}{""};
try{
java.util.Vector TitleVector = null;
java.util.Vector NameVector = null;
String[] NameList;
XInterface xDocInterface = (XInterface) xMSF.createInstance("com.sun.star.document.StandaloneDocumentInfo");
XStandaloneDocumentInfo xDocInfo = (XStandaloneDocumentInfo) UnoRuntime.queryInterface(XStandaloneDocumentInfo.class, xDocInterface);
XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
XSimpleFileAccess xSimpleFileAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class, xInterface);
NameList = xSimpleFileAccess.getFolderContents(FolderName, false);
TitleVector = new java.util.Vector(NameList.length);
NameVector = new java.util.Vector(NameList.length);
int FileCount = NameList.length;
int FilterLen = FilterName.length();
String CurFileName = "";
for (int i = 0; i<FileCount; i++){
CurFileName = NameList[i];
int s = CurFileName.indexOf(FilterName + "-");
if (CurFileName.indexOf(FilterName + "-")!= -1){
xDocInfo.loadFromURL(CurFileName);
NameVector.addElement(CurFileName);
TitleVector.addElement(AnyConverter.toString(getUNOPropertyValue(xDocInterface, "Title")));
}
}
String[]LocNameList = new String[NameVector.size()];
String[]LocTitleList = new String[TitleVector.size()];
NameVector.copyInto(LocNameList);
TitleVector.copyInto(LocTitleList);
LocLayoutFiles[1] = LocNameList;
LocLayoutFiles[0] = LocTitleList;
bubblesortList(LocLayoutFiles);
}
catch( Exception exception){
exception.printStackTrace(System.out);
}
return LocLayoutFiles;
}
public static XMultiComponentFactory getMultiComponentFactory()
throws com.sun.star.uno.Exception, com.sun.star.uno.RuntimeException, Exception {
XComponentContext xcomponentcontext = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext( null );
// initial serviceManager
return xcomponentcontext.getServiceManager();
}
public static void setUNOPropertyValue(Object oUNOObject, String PropertyName, Object PropertyValue){
try{
XPropertySet xPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oUNOObject);
if (xPSet.getPropertySetInfo().hasPropertyByName(PropertyName))
xPSet.setPropertyValue(PropertyName, PropertyValue);
}
catch(Exception exception){
exception.printStackTrace(System.out);
}}
public static void setUNOPropertyValues(Object oUNOObject, String[] PropertyNames, Object[] PropertyValues){
try{
XMultiPropertySet xMultiPSetLst = (XMultiPropertySet) UnoRuntime.queryInterface(XMultiPropertySet.class, oUNOObject);
xMultiPSetLst.setPropertyValues(PropertyNames, PropertyValues);
}
catch(Exception exception){
exception.printStackTrace(System.out);
}}
public static Object getUNOPropertyValue(Object oUNOObject, String PropertyName){
try{
if (oUNOObject != null){
XPropertySet xPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oUNOObject);
if (xPSet.getPropertySetInfo().hasPropertyByName(PropertyName) == true){
Object oObject = xPSet.getPropertyValue(PropertyName);
return oObject;
}
else
throw new com.sun.star.uno.RuntimeException();
}
else
throw new com.sun.star.uno.RuntimeException();
}
catch(Exception exception){
exception.printStackTrace(System.out);
return null;
}}
public static Object getUNOPropertyValue(Object oUNOObject, String PropertyName, java.lang.Class xClass){
try{
if (oUNOObject != null){
XPropertySet xPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oUNOObject);
if (xPSet.getPropertySetInfo().hasPropertyByName(PropertyName) == true){
Object oObject = xPSet.getPropertyValue(PropertyName);
return AnyConverter.toObject(new Type(xClass), oObject);
}
else
throw new com.sun.star.uno.RuntimeException();
}
else
throw new com.sun.star.uno.RuntimeException();
}
catch(Exception exception){
exception.printStackTrace(System.out);
return null;
}}
public static Object getUNOStructValue(Object oUNOObject, String PropertyName){
try{
if (oUNOObject != null){
XPropertySet xPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oUNOObject);
if (xPSet.getPropertySetInfo().hasPropertyByName(PropertyName) == true){
Object oObject = xPSet.getPropertyValue(PropertyName);
return oObject;
}
else
return null;
}
else
return null;
}
catch(Exception exception){
exception.printStackTrace(System.out);
return null;
}}
public static Object getUNOObjectbyName(Object oUNOObject, String ElementName){
try{
XNameAccess xName = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, oUNOObject);
if (xName.hasByName(ElementName) == true)
return xName.getByName(ElementName);
else
throw new com.sun.star.uno.RuntimeException();
}
catch(Exception exception){
exception.printStackTrace(System.out);
return null;
}}
public static Object getPropertyValue(PropertyValue[] CurPropertyValue, String PropertyName){
int MaxCount = CurPropertyValue.length;
for (int i = 0; i < MaxCount; i++){
if (CurPropertyValue[i] != null){
if (CurPropertyValue[i].Name == PropertyName){
return CurPropertyValue[i].Value;
}
}
}
throw new com.sun.star.uno.RuntimeException();
}
public static Object getPropertyValuefromAny(Object[] CurPropertyValue, String PropertyName){
if (CurPropertyValue != null){
int MaxCount = CurPropertyValue.length;
for (int i = 0; i < MaxCount; i++){
if (CurPropertyValue[i] != null){
PropertyValue aValue = (PropertyValue) CurPropertyValue[i];
if (aValue != null && aValue.Name.equals(PropertyName))
return aValue.Value;
}
}
}
// System.out.println("Property not found: " + PropertyName);
return null;
}
public static Object getPropertyValuefromAny(Object[] CurPropertyValue, String PropertyName, java.lang.Class xClass){
try{
if (CurPropertyValue != null){
int MaxCount = CurPropertyValue.length;
for (int i = 0; i < MaxCount; i++){
if (CurPropertyValue[i] != null){
PropertyValue aValue = (PropertyValue) CurPropertyValue[i];
if (aValue != null && aValue.Name.equals(PropertyName))
return AnyConverter.toObject(new Type(xClass), aValue.Value);
}
}
}
// System.out.println("Property not found: " + PropertyName);
return null;
}
catch( Exception exception){
exception.printStackTrace(System.out);
return null;
}}
public static long getNullDateCorrection(long lDate){
java.util.Calendar oCal = java.util.Calendar.getInstance();
oCal.set(1900,1,1);
Date dTime = oCal.getTime();
long lTime = dTime.getTime();
long lDBNullDate = lTime/(3600*24000);
long iDiffValue = lDBNullDate-lDate;
return iDiffValue;
}
public static long convertUnoDatetoInteger(com.sun.star.util.Date DateValue){
java.util.Calendar oCal = java.util.Calendar.getInstance();
oCal.set(DateValue.Year, DateValue.Month, DateValue.Day);
Date dTime = oCal.getTime();
long lTime = dTime.getTime();
long lDate = lTime/(3600*24000);
return lDate;
}
public static Object createNewDocument(XDesktop xDesktop, String sDocumentType) {
// XComponent xComponent = null;
Object oDocument = null;
PropertyValue xValues[] = new PropertyValue[1];
XComponentLoader xComponentLoader = null;
XInterface xInterface = null;
try {
String sURL = "private:factory/" + sDocumentType;
PropertyValue[] xEmptyArgs = new PropertyValue[0];
xComponentLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, xDesktop );
XComponent xComponent = xComponentLoader.loadComponentFromURL(sURL, "_default", 0, xEmptyArgs);
if (sDocumentType == "swriter")
oDocument = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class, xComponent);
else if (sDocumentType == "scalc")
oDocument = (XSpreadsheetDocument) UnoRuntime.queryInterface(XSpreadsheetDocument.class, xComponent);
// else if (sDocumentType == "simpress")
// else if (sDocumentType == "sdraw")
}
catch( Exception exception){
exception.printStackTrace(System.out);
}
return oDocument ;
}
public static XDesktop getDesktop(XMultiServiceFactory xMSF){
XInterface xInterface = null; XDesktop xDesktop = null;
if( xMSF != null ) {
try {
xInterface = (XInterface) xMSF.createInstance("com.sun.star.frame.Desktop");
xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, xInterface);
}
catch( Exception exception) {
exception.printStackTrace(System.out);
}
}
else
System.out.println( "Can't create a desktop. null pointer !" );
return xDesktop;
}
public static int FieldInList(String[] SearchList, String SearchString){
int FieldLen = SearchList.length;
int retvalue = -1;
for (int i = 0; i < FieldLen; i++){
if (SearchList[i].compareTo(SearchString) == 0){
retvalue = i;
break;
}
}
return retvalue;
}
public static int FieldInList(String[] SearchList, String SearchString, int StartIndex){
int FieldLen = SearchList.length;
int retvalue = -1;
if (StartIndex < FieldLen){
for (int i = StartIndex; i < FieldLen; i++){
if (SearchList[i].compareTo(SearchString) == 0){
retvalue = i;
break;
}
}
}
return retvalue;
}
public static int FieldInTable(String[][] SearchList, String SearchString){
int retvalue;
if (SearchList.length > 0){
int FieldLen = SearchList.length;
retvalue = -1;
for (int i = 0; i < FieldLen; i++){
if (SearchList[i][0] != null){
if (SearchList[i][0].compareTo(SearchString) == 0){
retvalue = i;
break;
}
}
}
}
else
retvalue = -1;
return retvalue;
}
public static int FieldInIntTable(int[][] SearchList, int SearchValue){
int FieldLen = SearchList.length;
int retvalue = -1;
for (int i = 0; i < FieldLen; i++){
if (SearchList[i][0] == SearchValue){
retvalue = i;
break;
}
}
return retvalue;
}
public static int getArraylength(Object[] MyArray){
int FieldCount = 0;
if (MyArray != null)
FieldCount = MyArray.length;
return FieldCount;
}
public static void addOfficePath(XMultiServiceFactory xMSF, String sPath, String sAddPath){
XSimpleFileAccess xSimpleFileAccess = null;
String ResultPath = getOfficePath(xMSF, sPath, xSimpleFileAccess);
// As there are several conventions about the look of Url (e.g. with " " or with "%20") you cannot make a
// simple String comparison to find out, if a path is already in "ResultPath"
String[] PathList = ArrayoutofString(ResultPath, ";");
boolean badd = false;
int MaxIndex = PathList.length - 1;
int iPos;
String CompCurPath;
// sAddPath.replace(null, (char) 47);
String CompAddPath = replaceSubString(sAddPath, "","/");
String CurPath;
for (int i = 0; i<=MaxIndex; i++){
CurPath = convertfromURLNotation(xMSF, PathList[i]);
CompCurPath = replaceSubString(CurPath, "", "/");
if (CompCurPath.equals(CompAddPath)){
return;
}
}
ResultPath += ";" + sAddPath;
return;
}
public static String getOfficePath(XMultiServiceFactory xMSF, String sPath, XSimpleFileAccess xSimpleFileAccess){
try{
String ResultPath = "";
XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.util.PathSettings");
ResultPath = AnyConverter.toString(getUNOPropertyValue(xInterface, sPath));
return ResultPath;
}
catch(Exception exception)
{
exception.printStackTrace(System.out);
return "";
}}
/* public convertJavaURL(XMultiServiceFactory xMSF, String JavaPath){
com.sun.star.util.URL aURL = new com.sun.star.util.URL(); //(XInterface) xMSF.createInstance("com.sun.star.util.URL");
aURL.Complete = JavaPath;
XInterface xIntURLTransformer = (XInterface) xMSF.createInstance("com.sun.star.util.URLTransformer");
XURLTransformer xURLTransformer = (XURLTransformer) UnoRuntime.queryInterface(XURLTransformer.class, xURLTransformer);
xURLTransformer.parseSmart(aURL, JavaPath);
String URLPath = java.net.URLDecoder.decode(JavaPath,"UTF-8");
} */
// In the return Officepath a possible slash at the end is cut off
public static String getOfficePath(XMultiServiceFactory xMSF, String sPath, String sType) throws NoValidPathException{
String ResultPath = "";
Object oPathSettings;
int iPathCount;
String[] PathList;
boolean bexists = false;
try{
XInterface xUcbInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
XSimpleFileAccess xSimpleFileAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class, xUcbInterface);
ResultPath = getOfficePath(xMSF, sPath, xSimpleFileAccess);
PathList = ArrayoutofString(ResultPath, ";");
if (sType != null){
String CurPath = "";
String EndString = "/" + sType;
int EndLength = EndString.length();
sType = "/" + sType + "/";
int MaxIndex = PathList.length - 1;
int iPos;
for (int i=0;i<=MaxIndex;i++){
CurPath = PathList[i];
iPos = CurPath.length()- EndLength;
if ((CurPath.indexOf(sType) > 0) || (CurPath.indexOf(EndString) == iPos)){
ResultPath = CurPath;
if (ResultPath.charAt(ResultPath.length()-1) == '/')
ResultPath = ResultPath.substring(0, ResultPath.length()-1);
break;
}
}
}
else
ResultPath = PathList[0];
if (ResultPath.equals("") == false)
bexists = xSimpleFileAccess.exists(ResultPath);
}
catch(Exception exception)
{
exception.printStackTrace(System.out);
ResultPath = "";
}
if (bexists == false){
throw new NoValidPathException(xMSF);
}
return ResultPath;
}
public static String combinePaths(XMultiServiceFactory xMSF, String FirstPath, String SecondPath) throws NoValidPathException{
boolean bexists = false;
try{
String ReturnPath = "";
XInterface xUcbInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
XSimpleFileAccess xSimpleFileAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class, xUcbInterface);
ReturnPath = FirstPath + SecondPath;
bexists = xSimpleFileAccess.exists(ReturnPath);
if (bexists == false)
throw new NoValidPathException(xMSF);
return ReturnPath;
}
catch(Exception exception)
{
exception.printStackTrace(System.out);
return "";
}}
public static String getFileDescription(String sPath){
String[] Hierarchy = ArrayoutofString(sPath, "/");
String[] FilenameList = ArrayoutofString(Hierarchy[Hierarchy.length-1], ".");
String FileDescription = "";
for (int i = 0; i < FilenameList.length-1; i++){
FileDescription += FilenameList[i];
}
return FileDescription;
}
public static String[] ArrayoutofString(String MainString, String Token){
String[] StringArray;
if (MainString.equals("") == false){
Vector StringVector = new Vector();
String LocString = null;
int iIndex;
do {
iIndex = MainString.indexOf(Token);
if (iIndex < 0)
StringVector.addElement(MainString);
else{
StringVector.addElement(MainString.substring(0, iIndex));
MainString = MainString.substring(iIndex+1, MainString.length());
}
} while (iIndex >= 0);
int FieldCount = StringVector.size();
StringArray = new String[FieldCount];
StringVector.copyInto(StringArray);
}
else
StringArray = new String[0];
return StringArray;
}
static class SystemDialog{
XInterface xSystemDialog;
XFilePicker xFilePicker;
XFilterManager xFilterManager;
XInitialization xInitialize;
XExecutableDialog xExecutable;
XComponent xComponent;
XFilePickerControlAccess xFilePickerControlAccess;
public SystemDialog(XMultiServiceFactory xMSF, String ServiceName){
try{
xSystemDialog = (XInterface) xMSF.createInstance(ServiceName);
xFilePicker = (XFilePicker) UnoRuntime.queryInterface(XFilePicker.class, xSystemDialog);
xFilterManager = (XFilterManager) UnoRuntime.queryInterface(XFilterManager.class, xSystemDialog);
xInitialize = (XInitialization) UnoRuntime.queryInterface(XInitialization.class, xSystemDialog);
xExecutable =(XExecutableDialog) UnoRuntime.queryInterface(XExecutableDialog.class, xSystemDialog);
xComponent =(XComponent) UnoRuntime.queryInterface(XComponent.class, xSystemDialog);
xFilePickerControlAccess = (XFilePickerControlAccess) UnoRuntime.queryInterface(XFilePickerControlAccess.class, xSystemDialog);
}
catch(com.sun.star.uno.Exception exception){
exception.printStackTrace(System.out);
}}
}
public static String callStoreDialog(XMultiServiceFactory xMSF, String DisplayDirectory, String DefaultName, String sDocuType){
String sPath = "";
SystemDialog StoreDialog = null;
try{
StoreDialog = new SystemDialog(xMSF, "com.sun.star.ui.dialogs.FilePicker");
Short[] ListAny = new Short[1];
ListAny[0] = new Short(com.sun.star.ui.dialogs.TemplateDescription.FILESAVE_AUTOEXTENSION_PASSWORD);
StoreDialog.xInitialize.initialize(ListAny);
StoreDialog.xFilePickerControlAccess.setValue(com.sun.star.ui.dialogs.ExtendedFilePickerElementIds.CHECKBOX_AUTOEXTENSION, (short) 0, new Boolean(true));
StoreDialog.xFilePicker.setDefaultName(DefaultName);
String sExtension = DefaultName.substring(DefaultName.length()-3, DefaultName.length());
addFiltersToDialog(xMSF, StoreDialog.xFilterManager, sDocuType, sExtension);
StoreDialog.xFilePicker.setDisplayDirectory(DisplayDirectory);
int iAccept = StoreDialog.xExecutable.execute();
if (iAccept == 1){
String[] sPathList = StoreDialog.xFilePicker.getFiles();
sPath = sPathList[0];
sPath = convertfromURLNotation(xMSF, sPath);
}
}
catch(com.sun.star.uno.Exception exception ){
exception.printStackTrace(System.out);
}
StoreDialog.xComponent.dispose();
return sPath;
}
public static XInvocation initResources(XMultiServiceFactory xMSF, String Description, String ShortDescription){
try{
XInterface oResource = (XInterface) xMSF.createInstance("com.sun.star.resource.VclStringResourceLoader");
if (oResource == null){
UNODialogs.showMessageBox(xMSF, "ErrorBox", com.sun.star.awt.VclWindowPeerAttribute.OK, "No Resource loader found" );
throw new com.sun.star.uno.RuntimeException();
}
else{
XInvocation xResInvoke = (XInvocation) UnoRuntime.queryInterface(XInvocation.class, oResource);
xResInvoke.setValue("FileName", ShortDescription);
return xResInvoke;
}
}
catch( Exception exception){
exception.printStackTrace(System.out);
return null;
}
}
public static String getResText(XInvocation xResInvoke, int nID)
throws com.sun.star.lang.IllegalArgumentException, com.sun.star.script.CannotConvertException, com.sun.star.reflection.InvocationTargetException{
short[][] PointerArray = new short[1][];
Object[][] DummyArray = new Object[1][];
Object[] nIDArray = new Object[1];
nIDArray[0] = new Integer(nID);
String IDString = (String) xResInvoke.invoke("getString", nIDArray, PointerArray, DummyArray);
return IDString;
}
// Todo: Currently it is not possible to retrieve the build version of the office via API
// As soon as this is possible we should insert a Message giving a hint about the missing resource file
public static void showCommonResourceError(XMultiServiceFactory xMSF){
String ProductName = Tools.getProductName(xMSF);
String sError = "The files required could not be found.<BR>Please start the %PRODUCTNAME Setup and choose 'Repair'.";
sError = Tools.replaceSubString(sError, ProductName, "%PRODUCTNAME");
sError = Tools.replaceSubString(sError, String.valueOf((char)13), "<BR>");
UNODialogs.showMessageBox(xMSF, "ErrorBox", com.sun.star.awt.VclWindowPeerAttribute.OK, sError);
}
public static String replaceSubString(String MainString, String NewSubString, String OldSubString){
try{
int NewIndex = 0;
int OldIndex = 0;
int NewSubLen = NewSubString.length();
int OldSubLen = OldSubString.length();
while (NewIndex != -1){
NewIndex = MainString.indexOf(OldSubString, OldIndex);
if (NewIndex != -1){
MainString = MainString.substring(0,NewIndex) + NewSubString + MainString.substring(NewIndex+OldSubLen);
OldIndex = NewIndex + NewSubLen;
}
}
return MainString;
}
catch(Exception exception)
{
exception.printStackTrace(System.out);
return null;
}}
public static boolean storeDocument(XMultiServiceFactory xMSF, XComponent xComponent, String StorePath, String FilterName, boolean bStoreToUrl, String sMsgSavingImpossible){
try{
XStorable xStoreable =(XStorable) UnoRuntime.queryInterface(XStorable.class, xComponent);
PropertyValue[] oStoreProperties;
if (FilterName.length() > 0){
oStoreProperties = new PropertyValue[1];
oStoreProperties[0] = new PropertyValue();
oStoreProperties[0].Name = "FilterName";
oStoreProperties[0].Value = FilterName;
}
else
oStoreProperties = new PropertyValue[0];
if (bStoreToUrl == true)
xStoreable.storeToURL(StorePath, oStoreProperties);
else
xStoreable.storeAsURL(StorePath, oStoreProperties);
return true;
}
catch(Exception exception)
{
exception.printStackTrace(System.out);
UNODialogs.showMessageBox(xMSF, "ErrorBox", com.sun.star.awt.VclWindowPeerAttribute.OK, sMsgSavingImpossible);
return false;
}}
public static String getProductName(XMultiServiceFactory xMSF){
Object oProdNameAccess = getRegistryKeyContent(xMSF, "org.openoffice.Setup/Product", false);
String ProductName = (String) getUNOObjectbyName(oProdNameAccess, "ooName");
return ProductName;
}
public static String getFilterName(XMultiServiceFactory xMSF, String sApplicationKey){
try{
Object oFactory = xMSF.createInstance("com.sun.star.document.FilterFactory");
Object oObject = getUNOObjectbyName(oFactory, sApplicationKey);
Object oArrayObject = AnyConverter.toArray(oObject);
PropertyValue[] xPropertyValue = (PropertyValue[]) oArrayObject; //UnoRuntime.queryInterface(XPropertyValue.class, oObject);
int MaxCount = xPropertyValue.length;
for (int i = 0; i < MaxCount; i++){
PropertyValue aValue = (PropertyValue) xPropertyValue[i];
if (aValue != null && aValue.Name.equals("UIName"))
return AnyConverter.toString(aValue.Value);
}
throw new com.sun.star.uno.RuntimeException();
}
catch(com.sun.star.uno.Exception exception){
exception.printStackTrace(System.out);
return null;
}}
//("writer_StarOffice_XML_Writer_Template") 'StarOffice XML (Writer)
public static void addFiltersToDialog(XMultiServiceFactory xMSF, XFilterManager xFilterManager, String sDocuType, String sExtension){
try{
String UIName = getFilterName(xMSF, sDocuType);
String[][] FilterNames = new String[1][3];
// Object oMasterKey = Tools.getRegistryKeyContent(xMSF, "org.openoffice.Office.TypeDetection/", false);
// Object oTypes = Tools.getUNOObjectbyName(oMasterKey,"Types");
// Object oFilter = getUNOObjectbyName(oTypes, sDocuType);
// String UIName = AnyConverter.toString(Tools.getUNOPropertyValue(oFilter, "UIName"));
FilterNames[0][0] = UIName;
FilterNames[0][1] = "*." + sExtension;
FilterNames[0][2] = "";
String ProdName = getProductName(xMSF);
int FilterCount = FilterNames.length;
for (int i=0; i<FilterCount; i++){
FilterNames[i][0] = replaceSubString(FilterNames[i][0], ProdName,"%productname%");
xFilterManager.appendFilter(FilterNames[i][0], FilterNames[i][1]);
}
xFilterManager.setCurrentFilter(FilterNames[0][0]);
}
catch(Exception exception){
exception.printStackTrace(System.out);
}}
public static String converttoURLNotation(String SystemPath){
try{
java.io.File oFileObject = new java.io.File(SystemPath);
char PathSeparator = oFileObject.separatorChar;
SystemPath.replace('\\', '/');
String URLPath = "file:/" + SystemPath;
URLPath.replace(PathSeparator, '/');
java.net.URL oURL = new java.net.URL(URLPath);
URLPath = oURL.toExternalForm();
URLPath = replaceSubString(URLPath,"file:///","file:/");
return URLPath;
}
catch(java.io.IOException jexception ){
jexception.printStackTrace(System.out);
return SystemPath;
}}
public static String convertfromURLNotation(XMultiServiceFactory xmsf, String URLPath){
try {
Object fcv = xmsf.createInstance("com.sun.star.ucb.FileContentProvider");
XFileIdentifierConverter filenameConverter =
(XFileIdentifierConverter) UnoRuntime.queryInterface(
XFileIdentifierConverter.class,fcv);
return filenameConverter.getSystemPathFromFileURL(URLPath);
}
catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static Object getRegistryKeyContent(XMultiServiceFactory xMSF, String KeyName, boolean bForUpdate){
try{
Object oConfigProvider;
PropertyValue[] aNodePath = new PropertyValue[1];
oConfigProvider = xMSF.createInstance("com.sun.star.configuration.ConfigurationProvider");
aNodePath[0] = new PropertyValue();
aNodePath[0].Name = "nodepath";
aNodePath[0].Value = KeyName;
XMultiServiceFactory xMSFConfig = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, oConfigProvider);
if (bForUpdate == true)
return xMSFConfig.createInstanceWithArguments("com.sun.star.configuration.ConfigurationUpdateAccess", aNodePath);
else
return xMSFConfig.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", aNodePath);
}
catch(Exception exception){
exception.printStackTrace(System.out);
return null;
}}
// a URL for a slot would e.g. be: "slot:" + Integer.toString(SlotID)
public static void dispatchURL(XMultiServiceFactory xMSF, String sURL, XFrame xFrame){
try{
PropertyValue[] oArg = new PropertyValue[0];
com.sun.star.util.URL[] oUrl = new com.sun.star.util.URL[1];
oUrl[0] = new com.sun.star.util.URL();
oUrl[0].Complete = sURL;
Object oTransformer = xMSF.createInstance("com.sun.star.util.URLTransformer");
XURLTransformer xTransformer = (XURLTransformer) UnoRuntime.queryInterface(XURLTransformer.class, oTransformer);
xTransformer.parseStrict(oUrl);
XDispatchProvider xDispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, xFrame);
XDispatch xDispatch = xDispatchProvider.queryDispatch(oUrl[0], "", 0); // "_self"
xDispatch.dispatch(oUrl[0], oArg);
}
catch(Exception exception) {
exception.printStackTrace(System.out);
}}
// Note: This method is to be used with caution because the retrieval of the active frame
// is depending on the focus handling of the operating system. Under Unix this is not necessarily the Toplevel frame;
public static XFrame getActiveFrame(XMultiServiceFactory xMSF){
XDesktop xDesktop = Tools.getDesktop(xMSF);
XFramesSupplier xFrameSuppl = (XFramesSupplier) UnoRuntime.queryInterface(XFramesSupplier.class, xDesktop);
XFrame xFrame = xFrameSuppl.getActiveFrame();
return xFrame;
}
public static void showJavaMessage(String Message){
// try{
java.awt.Frame oFrame = new java.awt.Frame();
java.awt.Frame[] oFrames = oFrame.getFrames();
oFrame = oFrames[oFrames.length-1];
oFrame.show();
oFrame.toFront();
java.awt.Component oComponent = oFrame.getFocusOwner();
javax.swing.JOptionPane.showMessageDialog(oFrame, Message, "StarOffice", javax.swing.JOptionPane.ERROR_MESSAGE);
oFrame.dispose();
// }
}
public static void attachEventCall(XTextDocument xTextDocument, String EventName, String EventType, String EventURL){
try{
XEventsSupplier xEventsSuppl = (XEventsSupplier) UnoRuntime.queryInterface(XEventsSupplier.class, xTextDocument);
PropertyValue[] oEventProperties = new PropertyValue[2];
oEventProperties[0] = new PropertyValue();
oEventProperties[0].Name = "EventType";
oEventProperties[0].Value = EventType; // "Service", "StarBasic"
oEventProperties[1] = new PropertyValue();
oEventProperties[1].Name = "Script"; //"URL";
oEventProperties[1].Value = EventURL;
xEventsSuppl.getEvents().replaceByName(EventName, oEventProperties);
}
catch( com.sun.star.uno.Exception exception ){
exception.printStackTrace(System.out);
}}
public static String ArraytoString(String[] LocArray){
String ResultString = "";
int iLen = LocArray.length;
for(int i=0; i<iLen;i++){
ResultString += LocArray[i];
if (i < iLen-1)
ResultString += ";";
}
return ResultString;
}
public static boolean createSubDirectory(XMultiServiceFactory xMSF, XSimpleFileAccess xSimpleFileAccess, String Path){
String sNoDirCreation = "";
try{
XInvocation xResInvoke = Tools.initResources(xMSF, "ImportWizard","imp");
if (xResInvoke != null){
sNoDirCreation = Tools.getResText(xResInvoke, 1050);
String sMsgDirNotThere = Tools.getResText(xResInvoke, 1051);
String sQueryForNewCreation = Tools.getResText(xResInvoke, 1052);
String OSPath = convertfromURLNotation(xMSF, Path);
String sQueryMessage = replaceSubString(sMsgDirNotThere, OSPath,"%1");
sQueryMessage = sQueryMessage + (char)13 + sQueryForNewCreation;
int icreate = UNODialogs.showMessageBox(xMSF, "QueryBox", com.sun.star.awt.VclWindowPeerAttribute.YES_NO, sQueryMessage);
if (icreate == 2){
xSimpleFileAccess.createFolder(Path);
return true;
}
}
return false;
}
catch (com.sun.star.ucb.CommandAbortedException exception){
String sMsgNoDir = replaceSubString(sNoDirCreation, Path, "%1");
UNODialogs.showMessageBox(xMSF, "ErrorBox", com.sun.star.awt.VclWindowPeerAttribute.OK, sMsgNoDir);
return false;
}
catch (com.sun.star.uno.Exception unoexception){
String sMsgNoDir = replaceSubString(sNoDirCreation, Path, "%1");
UNODialogs.showMessageBox(xMSF, "ErrorBox", com.sun.star.awt.VclWindowPeerAttribute.OK, sMsgNoDir);
return false;
}}
// checks if the root of a path exists. if the parameter xWindowPeer is not null then also the directory is
// created when it does not exists and the user
public static boolean PathisValid(XMultiServiceFactory xMSF, String Path, String sMsgFilePathInvalid, boolean baskbeforeOverwrite){
try{
String SubDir;
String SubDirPath = "";
int SubLen;
int NewLen;
int RestLen;
boolean bexists;
boolean bSubDirexists = true;
String LowerCasePath;
String NewPath = Path;
XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
XSimpleFileAccess xSimpleFileAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class, xInterface);
if (baskbeforeOverwrite){
if (xSimpleFileAccess.exists(Path)){
XInvocation xResInvoke = Tools.initResources(xMSF, "ImportWizard","imp");
String sFileexists = Tools.getResText(xResInvoke, 1053);
String NewString = convertfromURLNotation(xMSF, Path);
sFileexists = replaceSubString(sFileexists, NewString, "<1>");
sFileexists = replaceSubString(sFileexists, String.valueOf((char) 13), "<CR>");
int iLeave = UNODialogs.showMessageBox(xMSF, "QueryBox", com.sun.star.awt.VclWindowPeerAttribute.YES_NO, sFileexists);
if (iLeave == 3)
return false;
}
}
String[] DirArray = ArrayoutofString(Path, "/");
int MaxIndex = DirArray.length-1;
if (MaxIndex > 0){
for (int i = MaxIndex; i >=0; i--){
SubDir = DirArray[i];
SubLen = SubDir.length();
NewLen = NewPath.length();
RestLen = NewLen -SubLen;
if (RestLen > 0){
NewPath = NewPath.substring(0, NewLen - SubLen - 1);
if (i == MaxIndex)
SubDirPath = NewPath;
bexists = xSimpleFileAccess.exists(NewPath);
if (bexists){
LowerCasePath = NewPath.toLowerCase();
bexists = (((LowerCasePath.equals("file:///")) || (LowerCasePath.equals("file://")) || (LowerCasePath.equals("file:/")) || (LowerCasePath.equals("file:"))) == false);
}
if (bexists){
if (bSubDirexists == false){
boolean bSubDiriscreated = createSubDirectory(xMSF, xSimpleFileAccess, SubDirPath);
return bSubDiriscreated;
}
return true;
}
else
bSubDirexists = false;
}
}
}
UNODialogs.showMessageBox(xMSF, "ErrorBox", com.sun.star.awt.VclWindowPeerAttribute.OK, sMsgFilePathInvalid);
return false;
}
catch(com.sun.star.uno.Exception exception ){
exception.printStackTrace(System.out);
UNODialogs.showMessageBox(xMSF, "ErrorBox", com.sun.star.awt.VclWindowPeerAttribute.OK, sMsgFilePathInvalid);
return false;
}}
public static XMultiServiceFactory connect(String connectStr)
throws com.sun.star.uno.Exception, com.sun.star.uno.RuntimeException, Exception{
XComponentContext xcomponentcontext = null;
XMultiComponentFactory xMultiComponentFactory = Tools.getMultiComponentFactory();
// create a connector, so that it can contact the office
Object xUrlResolver = xMultiComponentFactory.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", xcomponentcontext );
XUnoUrlResolver urlResolver = (XUnoUrlResolver)UnoRuntime.queryInterface( XUnoUrlResolver.class, xUrlResolver );
Object rInitialObject = urlResolver.resolve( connectStr );
XNamingService rName = (XNamingService)UnoRuntime.queryInterface(XNamingService.class, rInitialObject );
XMultiServiceFactory xMSF = null;
if( rName != null ) {
System.err.println( "got the remote naming service !" );
Object rXsmgr = rName.getRegisteredObject("StarOffice.ServiceManager" );
xMSF = (XMultiServiceFactory) UnoRuntime.queryInterface( XMultiServiceFactory.class, rXsmgr );
}
return ( xMSF );
}
public static void showErrorBox(XMultiServiceFactory xMSF, String ResName, String ResPrefix, int ResID, String AddTag, String AddString){
try{
String ProductName = getProductName(xMSF);
XInvocation xResInvoke = Tools.initResources(xMSF, ResName, ResPrefix);
String sErrorMessage = Tools.getResText(xResInvoke, ResID);
sErrorMessage = replaceSubString(sErrorMessage, ProductName, "%PRODUCTNAME");
sErrorMessage = replaceSubString(sErrorMessage, String.valueOf((char)13), "<BR>");
sErrorMessage = replaceSubString(sErrorMessage, AddString, AddTag);
UNODialogs.showMessageBox(xMSF, "ErrorBox", com.sun.star.awt.VclWindowPeerAttribute.OK, sErrorMessage);
}
catch(com.sun.star.uno.Exception exception){
showCommonResourceError(xMSF);
}}
public static void showErrorBox(XMultiServiceFactory xMSF, String ResName, String ResPrefix, int ResID){
try{
String ProductName = getProductName(xMSF);
XInvocation xResInvoke = Tools.initResources(xMSF, ResName, ResPrefix);
String sErrorMessage = Tools.getResText(xResInvoke, ResID);
sErrorMessage = replaceSubString(sErrorMessage, ProductName, "%PRODUCTNAME");
sErrorMessage = replaceSubString(sErrorMessage, String.valueOf((char)13), "<BR>");
UNODialogs.showMessageBox(xMSF, "ErrorBox", com.sun.star.awt.VclWindowPeerAttribute.OK, sErrorMessage);
}
catch(com.sun.star.uno.Exception exception){
showCommonResourceError(xMSF);
}}
// This method must be used to ensure that after disposing a document
// from the backing window it is returned to the backing window, so the
// office won't be closed
public static void disposeDocument(XMultiServiceFactory xMSF, com.sun.star.lang.XComponent xComponent){
try{
if (xComponent != null){
XModifiable xModified = (XModifiable) UnoRuntime.queryInterface(XModifiable.class, xComponent);
XModel xModel = (XModel) UnoRuntime.queryInterface(XModel.class, xComponent);
XFrame xFrame = xModel.getCurrentController().getFrame();
if (xModified.isModified())
xModified.setModified(false);
dispatchURL(xMSF, ".uno:CloseDoc", xFrame);
}
}
catch( com.sun.star.beans.PropertyVetoException exception ){
exception.printStackTrace(System.out);
}}
// This function bubble sorts an array of with 2 dimensions.
// The default sorting order is the first dimension
// Only if sort2ndValue is True the second dimension is the relevant for the sorting order
public static String[][] bubblesortList(String[][] SortList){
String DisplayDummy;
int SortCount = SortList[0].length;
int DimCount = SortList.length;
for (int s = 0; s < SortCount; s++){
for (int t = 0; t < SortCount-s-1; t++){
if (SortList[0][t].compareTo(SortList[0][t+1]) > 0){
for (int k = 0; k < DimCount; k++){
DisplayDummy = SortList[k][t];
SortList[k][t] = SortList[k][t+1];
SortList[k][t+1] = DisplayDummy;
}
}
}
}
return SortList;
}
// Todo: The message could be specified more specific for a future version
public static class InvalidQueryException extends java.lang.Throwable {
public InvalidQueryException(XMultiServiceFactory xMSF, String sCommand){
final int RID_REPORT = 2400;
showErrorBox(xMSF, "ReportWizard", "dbw", RID_REPORT + 65, "<STATEMENT>", sCommand); // Querycreationnotpossible
}
}
public static class NoValidPathException extends java.lang.Throwable {
public NoValidPathException(XMultiServiceFactory xMSF){
showErrorBox(xMSF, "Common", "com", 1006); //OfficePathnotavailable
}
}
public static class TerminateWizardException extends Exception{
public TerminateWizardException(XMultiServiceFactory xMSF){
try{
XInvocation xResInvoke = Tools.initResources(xMSF, "AutoPilot","dbw");
String sErrorMessage = Tools.getResText(xResInvoke, 1006);
UNODialogs.showMessageBox(xMSF, "ErrorBox", com.sun.star.awt.VclWindowPeerAttribute.OK, sErrorMessage);
printStackTrace(System.out);
}
catch(com.sun.star.uno.Exception exception){
printStackTrace(System.out);
}}
}
}