diff options
Diffstat (limited to 'wizards/com/sun/star/wizards/db')
-rw-r--r-- | wizards/com/sun/star/wizards/db/BlindtextCreator.java | 100 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/ColumnPropertySet.java | 159 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/CommandMetaData.java | 539 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/CommandName.java | 261 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/DBMetaData.java | 1010 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/DatabaseObjectWizard.java | 170 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/FieldColumn.java | 403 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/MANIFEST.MF | 0 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/QueryMetaData.java | 244 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/RecordParser.java | 244 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/RelationController.java | 145 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/SQLQueryComposer.java | 436 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/TableDescriptor.java | 809 | ||||
-rw-r--r-- | wizards/com/sun/star/wizards/db/TypeInspector.java | 367 |
14 files changed, 4887 insertions, 0 deletions
diff --git a/wizards/com/sun/star/wizards/db/BlindtextCreator.java b/wizards/com/sun/star/wizards/db/BlindtextCreator.java new file mode 100644 index 000000000..0d79f457d --- /dev/null +++ b/wizards/com/sun/star/wizards/db/BlindtextCreator.java @@ -0,0 +1,100 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.wizards.common.PropertyNames; + +public class BlindtextCreator +{ + + private static final String BlindText = + "Ut wisi enim ad minim veniam, quis nostrud exerci tation " + "ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor " + "in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at " + "vero et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore " + "te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy " + "nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, " + "quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. " + "Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum " + "dolore eu feugiat nulla facilisis at vero et accumsan et iusto odio dignissim qui blandit praesent " + "luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis " + "eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum."; + + public static String adjustBlindTextlength(String FieldTitle, int FieldWidth, boolean bIsCurLandscape, boolean bIsGroupTable, String[] _RecordFieldNames) + { + String BlindTextString = PropertyNames.EMPTY_STRING; + if (bIsGroupTable) + { + return getBlindTextString(FieldTitle, FieldWidth); + } + int MaxFieldCount = getMaxFieldCount(bIsCurLandscape); + if (_RecordFieldNames.length <= 2 * MaxFieldCount) + { + if (_RecordFieldNames.length <= MaxFieldCount) + { + BlindTextString = getBlindTextString(FieldTitle, FieldWidth); + } + else + { + BlindTextString = getBlindTextString(FieldTitle, (int) (0.5 * FieldWidth)); + } + } + else + { + BlindTextString = getBlindTextString(FieldTitle, (int) 1.1 * FieldTitle.length()); + } + return BlindTextString; + } + + public static String getBlindTextString(String FieldTitle, int MaxWidth) + { + String[] BlindTextArray = JavaTools.ArrayoutofString(BlindText, PropertyNames.SPACE); + String PartBlindText = BlindTextArray[0]; + String NewPartBlindText; + int MaxHeaderWidth; + int Titlelength = (int) 1.1 * FieldTitle.length(); // We assume that the TableHeading is bold + + if (Titlelength > PartBlindText.length()) + { + MaxHeaderWidth = Titlelength; + } + else + { + MaxHeaderWidth = PartBlindText.length(); + } + if (MaxHeaderWidth > MaxWidth) + { + MaxWidth = MaxHeaderWidth; + } + int i = 1; + do + { + NewPartBlindText = PartBlindText + PropertyNames.SPACE + BlindTextArray[i]; + if (NewPartBlindText.length() < MaxWidth) + { + PartBlindText = NewPartBlindText; + i += 1; + } + } + while (NewPartBlindText.length() < MaxWidth); + return PartBlindText; + } + + private static int getMaxFieldCount(boolean bIsCurLandscape) + { + if (bIsCurLandscape) + { + return 5; + } + else + { + return 3; + } + } +} diff --git a/wizards/com/sun/star/wizards/db/ColumnPropertySet.java b/wizards/com/sun/star/wizards/db/ColumnPropertySet.java new file mode 100644 index 000000000..484dbf62f --- /dev/null +++ b/wizards/com/sun/star/wizards/db/ColumnPropertySet.java @@ -0,0 +1,159 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.sdbc.DataType; +import com.sun.star.wizards.common.Properties; +import com.sun.star.wizards.common.PropertyNames; + +public class ColumnPropertySet +{ + + private TypeInspector oTypeInspector; + public XPropertySet xPropertySet; + private int nType; + private String sTypeName = PropertyNames.EMPTY_STRING; + + public ColumnPropertySet(TypeInspector _oTypeInspector, XPropertySet _xPropertySet) + { + xPropertySet = _xPropertySet; + oTypeInspector = _oTypeInspector; + } + + private void assignPropertyValues(String _sNewName, PropertyValue[] _aNewColPropertyValues, boolean _bsetDefaultProperties) + { + try + { + nType = ((Integer) Properties.getPropertyValue(_aNewColPropertyValues, "Type")).intValue(); + nType = oTypeInspector.convertDataType(nType); + if (Properties.hasPropertyValue(_aNewColPropertyValues, "TypeName")) + { + sTypeName = (String) Properties.getPropertyValue(_aNewColPropertyValues, "TypeName"); + } + Integer precision = null; + if (Properties.hasPropertyValue(_aNewColPropertyValues, "Precision")) + { + precision = (Integer) Properties.getPropertyValue(_aNewColPropertyValues, "Precision"); + + } + if ((nType == DataType.VARCHAR) && (precision == null || precision.intValue() == 0)) + { + precision = 50; + } + if (precision != null) + { + xPropertySet.setPropertyValue("Precision", precision); + } + setType(sTypeName, precision); + for (int i = 0; i < _aNewColPropertyValues.length; i++) + { + String sPropName = _aNewColPropertyValues[i].Name; + if (_sNewName != null && sPropName.equals(PropertyNames.PROPERTY_NAME)) + { + xPropertySet.setPropertyValue(PropertyNames.PROPERTY_NAME, _sNewName); + } + else if (sPropName.equals("Precision")) + { + // do nothing, see above + } + else if ((!sPropName.equals("Type")) && (!sPropName.equals("TypeName"))) + { + Object oColValue = _aNewColPropertyValues[i].Value; + assignPropertyValue(sPropName, oColValue); + } + } + if (_bsetDefaultProperties) + { + assignPropertyValue("IsNullable", Integer.valueOf(oTypeInspector.isNullable(xPropertySet))); + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + + } + + public void assignPropertyValues(PropertyValue[] _aNewColPropertyValues, boolean _bsetDefaultProperties) + { + assignPropertyValues(null /* don't change the name */, _aNewColPropertyValues, _bsetDefaultProperties); + } + + private void setType(String _sTypeName, Integer precision) + { + if (_sTypeName.equals(PropertyNames.EMPTY_STRING)) + { + sTypeName = oTypeInspector.getDefaultTypeName(nType, precision); + } + else + { + sTypeName = _sTypeName; + } + nType = oTypeInspector.getDataType(sTypeName); + assignPropertyValue("Type", Integer.valueOf(nType)); + assignPropertyValue("TypeName", sTypeName); + } + + private void assignPropertyValue(String _spropname, Object _oValue) + { + try + { + if (_spropname.equals("Type")) + { + nType = ((Integer) _oValue).intValue(); + xPropertySet.setPropertyValue("Type", Integer.valueOf(nType)); + } + else if (_spropname.equals(PropertyNames.PROPERTY_NAME)) + { + String sName = (String) _oValue; + if (!sName.equals(PropertyNames.EMPTY_STRING)) + { + xPropertySet.setPropertyValue(PropertyNames.PROPERTY_NAME, sName); + } + } + else if (_spropname.equals("Scale")) + { + int nScale = ((Integer) _oValue).intValue(); + nScale = oTypeInspector.getScale(xPropertySet); + xPropertySet.setPropertyValue("Scale", Integer.valueOf(nScale)); + } + else if (_spropname.equals("IsNullable")) + { + int nNullability = ((Integer) _oValue).intValue(); + nNullability = oTypeInspector.getNullability(xPropertySet, nNullability); + xPropertySet.setPropertyValue("IsNullable", Integer.valueOf(nNullability)); + } + else if (_spropname.equals("TypeName")) + { + String sTypeName = (String) _oValue; + xPropertySet.setPropertyValue("TypeName", sTypeName); + } + else + { + xPropertySet.setPropertyValue(_spropname, _oValue); + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + } + +} diff --git a/wizards/com/sun/star/wizards/db/CommandMetaData.java b/wizards/com/sun/star/wizards/db/CommandMetaData.java new file mode 100644 index 000000000..28180382f --- /dev/null +++ b/wizards/com/sun/star/wizards/db/CommandMetaData.java @@ -0,0 +1,539 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdbc.SQLException; +import com.sun.star.uno.AnyConverter; +import com.sun.star.awt.VclWindowPeerAttribute; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XNameAccess; +import com.sun.star.wizards.common.Helper; +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.wizards.common.PropertyNames; +import com.sun.star.wizards.common.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class CommandMetaData extends DBMetaData +{ + + public Map<String, String> FieldTitleSet = new HashMap<String, String>(); + public String[] m_aAllFieldNames = new String[] + { + }; + public FieldColumn[] FieldColumns = new FieldColumn[] + { + }; + public String[] GroupFieldNames = new String[] + { + }; + private String[][] SortFieldNames = new String[][] + { + }; + private String[] RecordFieldNames = new String[] + { + }; + public String[][] AggregateFieldNames = new String[][] + { + }; + public String[] NumericFieldNames = new String[] + { + }; + public String[] NonAggregateFieldNames; + private int CommandType; + private String Command; + private String sIdentifierQuote = PropertyNames.EMPTY_STRING; + private boolean bCommandComposerAttributesalreadyRetrieved = false; + + public CommandMetaData(XMultiServiceFactory xMSF) + { + super(xMSF); + } + + public void initializeFieldColumns(String _CommandName, String[] _FieldNames) + { + this.setCommandName(_CommandName); + FieldColumns = new FieldColumn[_FieldNames.length]; + for (int i = 0; i < _FieldNames.length; i++) + { + FieldColumns[i] = new FieldColumn(this, _FieldNames[i], this.getCommandName(), false); + } + } + + public void initializeFieldColumns(String[] _FieldNames, XNameAccess _xColumns) + { + FieldColumns = new FieldColumn[_FieldNames.length]; + for (int i = 0; i < _FieldNames.length; i++) + { + FieldColumns[i] = new FieldColumn(this, _xColumns, _FieldNames[i]); + } + } + + public void initializeFieldColumns(String[] _FieldNames, String _CommandName) + { + this.setCommandName(_CommandName); + FieldColumns = new FieldColumn[_FieldNames.length]; + for (int i = 0; i < _FieldNames.length; i++) + { + FieldColumns[i] = new FieldColumn(this, _FieldNames[i], _CommandName, false); + if (FieldTitleSet != null && FieldTitleSet.containsKey(_FieldNames[i])) + { + FieldColumns[i].setFieldTitle(FieldTitleSet.get(_FieldNames[i])); + if (FieldColumns[i].getFieldTitle() == null) + { + FieldColumns[i].setFieldTitle(_FieldNames[i]); + FieldTitleSet.put(_FieldNames[i], _FieldNames[i]); + } + } + } + } + + public Map<String, String> getFieldTitleSet() + { + return FieldTitleSet; + } + + public XPropertySet getColumnObjectByFieldName(String _FieldName, boolean _bgetByDisplayName) + { + try + { + FieldColumn CurFieldColumn = null; + if (_bgetByDisplayName) + { + CurFieldColumn = this.getFieldColumnByDisplayName(_FieldName); + } + else + { + CurFieldColumn = this.getFieldColumnByFieldName(_FieldName); + } + String CurCommandName = CurFieldColumn.getCommandName(); + CommandObject oCommand = getTableByName(CurCommandName); + Object oColumn = oCommand.getColumns().getByName(CurFieldColumn.getFieldName()); + return UnoRuntime.queryInterface(XPropertySet.class, oColumn); + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + return null; + } + } + + // @SuppressWarnings("unchecked") + public void prependSortFieldNames(String[] _fieldnames) + { + ArrayList<String[]> aSortFields = new ArrayList<String[]>(); + for (int i = 0; i < _fieldnames.length; i++) + { + String[] sSortFieldName = new String[2]; + sSortFieldName[0] = _fieldnames[i]; + int index = JavaTools.FieldInTable(SortFieldNames, _fieldnames[i]); + if (index > -1) + { + sSortFieldName[1] = SortFieldNames[index][1]; + } + else + { + sSortFieldName[1] = PropertyNames.ASC; + } + aSortFields.add(sSortFieldName); + } + for (int i = 0; i < SortFieldNames.length; i++) + { + if (JavaTools.FieldInList(_fieldnames, SortFieldNames[i][0]) == -1) + { + aSortFields.add(SortFieldNames[i]); + } + } + SortFieldNames = new String[aSortFields.size()][2]; + aSortFields.toArray(SortFieldNames); + } + + public String[][] getSortFieldNames() + { + return SortFieldNames; + } + + public void setSortFieldNames(String[][] aNewListList) + { + SortFieldNames = aNewListList; + } + + public FieldColumn getFieldColumn(String _FieldName, String _CommandName) + { + for (int i = 0; i < FieldColumns.length; i++) + { + if (FieldColumns[i].getFieldName().equals(_FieldName) && FieldColumns[i].getCommandName().equals(_CommandName)) + { + return FieldColumns[i]; + } + } + return null; + } + + public FieldColumn getFieldColumnByFieldName(String _FieldName) + { + for (int i = 0; i < FieldColumns.length; i++) + { + String sFieldName = FieldColumns[i].getFieldName(); + if (sFieldName.equals(_FieldName)) + { + return FieldColumns[i]; + } + if (_FieldName.indexOf('.') == -1) + { + String sCompound = Command + "." + _FieldName; + if (sFieldName.equals(sCompound)) + { + return FieldColumns[i]; + } + } + } + throw new com.sun.star.uno.RuntimeException(); + } + + public FieldColumn getFieldColumnByDisplayName(String _DisplayName) + { + String identifierQuote = getIdentifierQuote(); + for (int i = 0; i < FieldColumns.length; i++) + { + String sDisplayName = FieldColumns[i].getDisplayFieldName(); + if (sDisplayName.equals(_DisplayName)) + { + return FieldColumns[i]; + } + if (_DisplayName.indexOf('.') == -1) + { + String sCompound = Command + "." + _DisplayName; + if (sDisplayName.equals(sCompound)) + { + return FieldColumns[i]; + } + } + String quotedName = new StringBuilder(CommandName.quoteName(FieldColumns[i].getCommandName(), identifierQuote)).append('.').append(CommandName.quoteName(FieldColumns[i].getFieldName(), identifierQuote)).toString(); + if (quotedName.equals(_DisplayName)) + { + return FieldColumns[i]; + } + } + throw new com.sun.star.uno.RuntimeException(); + } + + public FieldColumn getFieldColumnByTitle(String _FieldTitle) + { + for (int i = 0; i < FieldColumns.length; i++) + { + if (FieldColumns[i].getFieldTitle().equals(_FieldTitle)) + { + return FieldColumns[i]; + } + } + // throw new com.sun.star.uno.RuntimeException(); + // LLA: Group works with fields direct + for (int i = 0; i < FieldColumns.length; i++) + { + if (FieldColumns[i].getFieldName().equals(_FieldTitle)) + { + return FieldColumns[i]; + } + } + throw new com.sun.star.uno.RuntimeException(); + } + + public boolean getFieldNamesOfCommand(String _commandname, int _commandtype) + { + try + { + java.util.ArrayList<String> ResultFieldNames = new java.util.ArrayList<String>(10); + String[] FieldNames; + CommandObject oCommand = this.getCommandByName(_commandname, _commandtype); + FieldNames = oCommand.getColumns().getElementNames(); + if (FieldNames.length > 0) + { + for (int n = 0; n < FieldNames.length; n++) + { + final String sFieldName = FieldNames[n]; + Object oField = oCommand.getColumns().getByName(sFieldName); + int iType = AnyConverter.toInt(Helper.getUnoPropertyValue(oField, "Type")); + // BinaryFieldTypes are not included in the WidthList + if (JavaTools.FieldInIntTable(WidthList, iType) >= 0) + { + ResultFieldNames.add(sFieldName); + } + else if (JavaTools.FieldInIntTable(BinaryTypes, iType) >= 0) + { + ResultFieldNames.add(sFieldName); + } + } + m_aAllFieldNames = new String[ResultFieldNames.size()]; + m_aAllFieldNames = ResultFieldNames.toArray(m_aAllFieldNames); + return true; + } + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + } + Resource oResource = new Resource(xMSF); + String sMsgNoFieldsFromCommand = oResource.getResText("RID_DB_COMMON_45"); + sMsgNoFieldsFromCommand = JavaTools.replaceSubString(sMsgNoFieldsFromCommand, _commandname, "%NAME"); + showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMsgNoFieldsFromCommand); + return false; + } + + /** + * @return Returns the command. + */ + public String getCommandName() + { + return Command; + } + + /** + * @param _command The command to set. + */ + public void setCommandName(String _command) + { + Command = _command; + } + + /** + * @return Returns the commandType. + */ + public int getCommandType() + { + return CommandType; + } + + /** + * @param _commandType The commandType to set. + */ + public void setCommandType(int _commandType) + { + CommandType = _commandType; + } + + private boolean isnumeric(FieldColumn _oFieldColumn) + { + try + { + CommandObject oTable = super.getTableByName(_oFieldColumn.getCommandName()); + Object oField = oTable.getColumns().getByName(_oFieldColumn.getFieldName()); + int iType = AnyConverter.toInt(Helper.getUnoPropertyValue(oField, "Type")); + int ifound = java.util.Arrays.binarySearch(NumericTypes, iType); + if ((ifound < NumericTypes.length) && (ifound > 0)) + { + return (NumericTypes[ifound] == iType); + } + else + { + return false; + } + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + return false; + } + } + + public String[] setNumericFields() + { + try + { + ArrayList<String> numericfieldsvector = new java.util.ArrayList<String>(); + for (int i = 0; i < FieldColumns.length; i++) + { + if (isnumeric(FieldColumns[i])) + { + numericfieldsvector.add(FieldColumns[i].getDisplayFieldName()); + } + } + NumericFieldNames = new String[numericfieldsvector.size()]; + numericfieldsvector.toArray(NumericFieldNames); + return NumericFieldNames; + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + return new String[] + { + }; + } + } + + public String[] getFieldNames(String[] _sDisplayFieldNames, String _sCommandName) + { + ArrayList<String> sFieldNamesVector = new java.util.ArrayList<String>(); + for (int i = 0; i < FieldColumns.length; i++) + { + if (_sCommandName.equals(FieldColumns[i].getCommandName()) && JavaTools.FieldInList(_sDisplayFieldNames, FieldColumns[i].getDisplayFieldName()) > -1) + { + sFieldNamesVector.add(FieldColumns[i].getFieldName()); + } + } + String[] sFieldNames = new String[sFieldNamesVector.size()]; + sFieldNamesVector.toArray(sFieldNames); + return sFieldNames; + } + + public String[] getFieldNames() + { + String[] sFieldNames = new String[FieldColumns.length]; + for (int i = 0; i < FieldColumns.length; i++) + { + sFieldNames[i] = FieldColumns[i].getFieldName(); + } + return sFieldNames; + } + + public String[] getDisplayFieldNames() + { + String[] sDisplayFieldNames = new String[FieldColumns.length]; + for (int i = 0; i < FieldColumns.length; i++) + { + sDisplayFieldNames[i] = FieldColumns[i].getDisplayFieldName(); + } + return sDisplayFieldNames; + } + + public String[] setNonAggregateFieldNames() + { + try + { + ArrayList<String> nonaggregatefieldsvector = new java.util.ArrayList<String>(); + for (int i = 0; i < FieldColumns.length; i++) + { + if (JavaTools.FieldInTable(AggregateFieldNames, FieldColumns[i].getDisplayFieldName()) == -1) + { + nonaggregatefieldsvector.add(FieldColumns[i].getDisplayFieldName()); + } + } + NonAggregateFieldNames = new String[nonaggregatefieldsvector.size()]; + nonaggregatefieldsvector.toArray(NonAggregateFieldNames); + return NonAggregateFieldNames; + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + return new String[] + { + }; + } + } + + public String getFieldTitle(String FieldName) + { + String FieldTitle = FieldName; + if (this.FieldTitleSet != null) + { + FieldTitle = this.FieldTitleSet.get(FieldName); //FieldTitles[TitleIndex]; + if (FieldTitle == null) + { + return FieldName; + } + } + return FieldTitle; + } + + public void setFieldTitles(String[] sFieldTitles) + { + int nFieldColLength = FieldColumns.length; + for (int i = 0; i < sFieldTitles.length; i++) + { + if (i < nFieldColLength) + { + FieldColumns[i].setFieldTitle(sFieldTitles[i]); + } + + } + } + + public void setGroupFieldNames(String[] GroupFieldNames) + { + this.GroupFieldNames = GroupFieldNames; + } + + public String[] getGroupFieldNames() + { + return GroupFieldNames; + } + + public void createRecordFieldNames() + { + String CurFieldName; + int GroupFieldCount; + int TotFieldCount = FieldColumns.length; + GroupFieldCount = JavaTools.getArraylength(GroupFieldNames); + RecordFieldNames = new String[TotFieldCount - GroupFieldCount]; + + int a = 0; + for (int i = 0; i < TotFieldCount; i++) + { + CurFieldName = FieldColumns[i].getFieldName(); + if (JavaTools.FieldInList(GroupFieldNames, CurFieldName) < 0) + { + RecordFieldNames[a] = CurFieldName; + ++a; + } + } + } + + public void setRecordFieldNames(String[] _aNewList) + { + RecordFieldNames = _aNewList; + } + + public String[] getRecordFieldNames() + { + return RecordFieldNames; + } + + public String getRecordFieldName(int i) + { + return RecordFieldNames[i]; + } + + private void setCommandComposingAttributes() + { + try + { + xDBMetaData.getCatalogSeparator(); + sIdentifierQuote = xDBMetaData.getIdentifierQuoteString(); + bCommandComposerAttributesalreadyRetrieved = true; + } + catch (SQLException e) + { + e.printStackTrace(System.err); + } + } + + /** + * @return Returns the sIdentifierQuote. + */ + public String getIdentifierQuote() + { + if (!bCommandComposerAttributesalreadyRetrieved) + { + setCommandComposingAttributes(); + } + return sIdentifierQuote; + } +} diff --git a/wizards/com/sun/star/wizards/db/CommandName.java b/wizards/com/sun/star/wizards/db/CommandName.java new file mode 100644 index 000000000..4768018ef --- /dev/null +++ b/wizards/com/sun/star/wizards/db/CommandName.java @@ -0,0 +1,261 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import com.sun.star.sdbc.SQLException; +import com.sun.star.uno.Exception; +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.wizards.common.PropertyNames; + +public class CommandName +{ + + private CommandMetaData oCommandMetaData; + private String CatalogName = PropertyNames.EMPTY_STRING; + private String SchemaName = PropertyNames.EMPTY_STRING; + private String TableName = PropertyNames.EMPTY_STRING; + private String DisplayName = PropertyNames.EMPTY_STRING; + private String ComposedName = PropertyNames.EMPTY_STRING; + private String AliasName = PropertyNames.EMPTY_STRING; + private boolean bCatalogAtStart; + private String sCatalogSep; + private boolean baddQuotation = true; + + public CommandName(CommandMetaData _CommandMetaData, String _DisplayName) + { + oCommandMetaData = _CommandMetaData; + setComposedCommandName(_DisplayName); + } + + public CommandName(CommandMetaData _CommandMetaData, String _CatalogName, String _SchemaName, String _TableName, boolean _baddQuotation) + { + try + { + baddQuotation = _baddQuotation; + oCommandMetaData = _CommandMetaData; + if ((_CatalogName != null) && (oCommandMetaData.xDBMetaData.supportsCatalogsInTableDefinitions())) + { + if (!_CatalogName.equals(PropertyNames.EMPTY_STRING)) + { + CatalogName = _CatalogName; + } + } + if ((_SchemaName != null) && (oCommandMetaData.xDBMetaData.supportsSchemasInTableDefinitions())) + { + if (!_SchemaName.equals(PropertyNames.EMPTY_STRING)) + { + SchemaName = _SchemaName; + } + } + if (_TableName != null) + { + if (!_TableName.equals(PropertyNames.EMPTY_STRING)) + { + TableName = _TableName; + } + } + setComposedCommandName(); + } + catch (SQLException e) + { + e.printStackTrace(System.err); + } + } + + private void setComposedCommandName(String _DisplayName) + { + try + { + if (!setMetaDataAttributes()) + return; + + this.DisplayName = _DisplayName; + int iIndex; + if (oCommandMetaData.xDBMetaData.supportsCatalogsInDataManipulation()) + { // ...then Catalog also in TableName + iIndex = _DisplayName.indexOf(sCatalogSep); + if (iIndex >= 0) + { + if (bCatalogAtStart) + { + CatalogName = _DisplayName.substring(0, iIndex); + _DisplayName = _DisplayName.substring(iIndex + 1, _DisplayName.length()); + } + else + { + CatalogName = _DisplayName.substring(iIndex + 1, _DisplayName.length()); + _DisplayName = _DisplayName.substring(0, iIndex); + } + } + } + if (oCommandMetaData.xDBMetaData.supportsSchemasInDataManipulation()) + { + String[] NameList = JavaTools.ArrayoutofString(_DisplayName, "."); + if (NameList.length > 1) + { + SchemaName = NameList[0]; + TableName = NameList[1]; + } + else + { + TableName = _DisplayName; + } + } + else + { + TableName = _DisplayName; + } + setComposedCommandName(); + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + } + } + + private void setComposedCommandName() + { + if (this.setMetaDataAttributes()) + { + if (CatalogName != null) + { + if (!CatalogName.equals(PropertyNames.EMPTY_STRING)) + { + if (bCatalogAtStart) + { + ComposedName = quoteName(CatalogName) + sCatalogSep; + } + } + } + if (SchemaName != null) + { + if (!SchemaName.equals(PropertyNames.EMPTY_STRING)) + { + ComposedName += quoteName(SchemaName) + "."; + } + } + if (ComposedName.equals(PropertyNames.EMPTY_STRING)) + { + ComposedName = quoteName(TableName); + } + else + { + ComposedName += quoteName(TableName); + } + if ((!bCatalogAtStart) && (CatalogName != null)) + { + if (!CatalogName.equals(PropertyNames.EMPTY_STRING)) + { + ComposedName += sCatalogSep + quoteName(CatalogName); + } + } + } + } + + private boolean setMetaDataAttributes() + { + try + { + bCatalogAtStart = oCommandMetaData.xDBMetaData.isCatalogAtStart(); + sCatalogSep = oCommandMetaData.xDBMetaData.getCatalogSeparator(); + oCommandMetaData.xDBMetaData.getIdentifierQuoteString(); + return true; + } + catch (SQLException e) + { + e.printStackTrace(System.err); + return false; + } + } + + private String quoteName(String _sName) + { + if (baddQuotation) + { + return quoteName(_sName, this.oCommandMetaData.getIdentifierQuote()); + } + else + { + return _sName; + } + } + + public static String quoteName(String sName, String _sIdentifierQuote) + { + if (sName == null) + { + sName = PropertyNames.EMPTY_STRING; + } + return new StringBuilder(_sIdentifierQuote).append(sName).append(_sIdentifierQuote).toString(); + } + + public void setAliasName(String _AliasName) + { + AliasName = _AliasName; + } + + public String getAliasName() + { + return AliasName; + } + + /** + * @return Returns the catalogName. + */ + public String getCatalogName() + { + return CatalogName; + } + + /** + * @return Returns the composedName. + */ + public String getComposedName() + { + return ComposedName; + } + + /** + * @return Returns the displayName. + */ + public String getDisplayName() + { + return DisplayName; + } + + /** + * @return Returns the schemaName. + */ + public String getSchemaName() + { + return SchemaName; + } + + /** + * @return Returns the tableName. + */ + public String getTableName() + { + return TableName; + } + + public CommandMetaData getCommandMetaData() + { + return oCommandMetaData; + } +} diff --git a/wizards/com/sun/star/wizards/db/DBMetaData.java b/wizards/com/sun/star/wizards/db/DBMetaData.java new file mode 100644 index 000000000..1a720b0ac --- /dev/null +++ b/wizards/com/sun/star/wizards/db/DBMetaData.java @@ -0,0 +1,1010 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.sun.star.awt.VclWindowPeerAttribute; +import com.sun.star.awt.XWindow; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XHierarchicalNameAccess; +import com.sun.star.container.XHierarchicalNameContainer; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNameContainer; +import com.sun.star.frame.XModel; +import com.sun.star.frame.XStorable; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.Locale; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XInitialization; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; +import com.sun.star.sdb.XCompletedConnection; +import com.sun.star.sdb.XDocumentDataSource; +import com.sun.star.sdb.XFormDocumentsSupplier; +import com.sun.star.sdb.XOfficeDatabaseDocument; +import com.sun.star.sdb.XQueriesSupplier; +import com.sun.star.sdb.XQueryDefinitionsSupplier; +import com.sun.star.sdb.XReportDocumentsSupplier; +import com.sun.star.sdb.tools.XConnectionTools; +import com.sun.star.sdbc.DataType; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XConnection; +import com.sun.star.sdbc.XDataSource; +import com.sun.star.sdbc.XDatabaseMetaData; +import com.sun.star.sdbc.XResultSet; +import com.sun.star.sdbc.XRow; +import com.sun.star.sdbcx.XColumnsSupplier; +import com.sun.star.sdbcx.XTablesSupplier; +import com.sun.star.task.XInteractionHandler; +import com.sun.star.ucb.XSimpleFileAccess; +import com.sun.star.ui.dialogs.XExecutableDialog; +import com.sun.star.uno.Any; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.util.XCloseable; +import com.sun.star.util.XNumberFormatsSupplier; +import com.sun.star.wizards.common.Configuration; +import com.sun.star.wizards.common.Desktop; +import com.sun.star.wizards.common.FileAccess; +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.wizards.common.NamedValueCollection; +import com.sun.star.wizards.common.NumberFormatter; +import com.sun.star.wizards.common.Properties; +import com.sun.star.wizards.common.PropertyNames; +import com.sun.star.wizards.common.Resource; +import com.sun.star.wizards.common.SystemDialog; + +public class DBMetaData +{ + private XNameAccess xQueryNames; + public XDatabaseMetaData xDBMetaData; + private XDataSource m_dataSource; + private XPropertySet m_dataSourceSettings; + private XOfficeDatabaseDocument xModel; + private XPropertySet xDataSourcePropertySet; + private java.util.ArrayList<CommandObject> CommandObjects = new ArrayList<CommandObject>(1); + private Locale aLocale; + public String DataSourceName; + public com.sun.star.sdbc.XConnection DBConnection; + private com.sun.star.sdb.tools.XConnectionTools m_connectionTools; + public com.sun.star.lang.XMultiServiceFactory xMSF; + private XComponent xConnectionComponent; + + private XNameAccess xNameAccess; + private XInterface xDatabaseContext; + private XWindowPeer xWindowPeer; + private String[] TableNames = new String[] {}; + private String[] QueryNames = new String[] {}; + + protected int[][] WidthList; + protected static final int[] NumericTypes = { + DataType.TINYINT, // == -6; + DataType.BIGINT, // == -5 + DataType.NUMERIC, // == - 2 + DataType.DECIMAL, // == 3; + DataType.INTEGER, // == 4; + DataType.SMALLINT, // == 5; + DataType.FLOAT, // == 6; + DataType.REAL, // == 7; + DataType.DOUBLE, // == 8; + }; + protected static final int[] BinaryTypes = { //new int[12]; + DataType.BINARY, + DataType.VARBINARY, + DataType.LONGVARBINARY, + DataType.BLOB, + DataType.SQLNULL, + DataType.OBJECT, + DataType.DISTINCT, + DataType.STRUCT, + DataType.ARRAY, + DataType.CLOB, + DataType.REF + /* DataType.OTHER, */ + }; + + private int iMaxColumnsInSelect; + private int iMaxColumnNameLength = -1; + private int iMaxTableNameLength = -1; + private boolean bPasswordIsRequired; + private static final int NOLIMIT = 9999999; + private static final int INVALID = 9999999; + public TypeInspector oTypeInspector; + private NumberFormatter oNumberFormatter = null; + private long lDateCorrection = INVALID; + private boolean bdisposeConnection = false; + + public XPropertySet getDataSourcePropertySet() + { + return xDataSourcePropertySet; + } + + public DBMetaData(XMultiServiceFactory xMSF) + { + getInterfaces(xMSF); + InitializeWidthList(); + } + + public NumberFormatter getNumberFormatter() + { + if (oNumberFormatter == null) + { + try + { + XNumberFormatsSupplier xNumberFormatsSupplier = (XNumberFormatsSupplier) AnyConverter.toObject(XNumberFormatsSupplier.class, xDataSourcePropertySet.getPropertyValue("NumberFormatsSupplier")); + //TODO get the locale from the datasource + aLocale = Configuration.getLocale(xMSF); + oNumberFormatter = new NumberFormatter(xMSF, xNumberFormatsSupplier, aLocale); + lDateCorrection = oNumberFormatter.getNullDateCorrection(); + } + catch (Exception e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + } + return oNumberFormatter; + } + + public long getNullDateCorrection() + { + if (lDateCorrection == INVALID) + { + if (oNumberFormatter == null) + { + oNumberFormatter = getNumberFormatter(); + } + lDateCorrection = oNumberFormatter.getNullDateCorrection(); + } + return lDateCorrection; + } + + private void getInterfaces(XMultiServiceFactory xMSF) + { + try + { + this.xMSF = xMSF; + xDatabaseContext = (XInterface) xMSF.createInstance("com.sun.star.sdb.DatabaseContext"); + xNameAccess = UnoRuntime.queryInterface( XNameAccess.class, xDatabaseContext ); + xNameAccess.getElementNames(); + } + catch (Exception e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + } + + + + public boolean hasTableByName(String _stablename) + { + return getTableNamesAsNameAccess().hasByName(_stablename); + } + + public void setTableByName(String _tableName) + { + CommandObject oTableObject = new CommandObject(_tableName, com.sun.star.sdb.CommandType.TABLE); + this.CommandObjects.add(oTableObject); + } + + public CommandObject getTableByName(String _tablename) + { + return getCommandByName(_tablename, com.sun.star.sdb.CommandType.TABLE); + } + + public CommandObject getQueryByName(String _queryname) + { + return getCommandByName(_queryname, com.sun.star.sdb.CommandType.QUERY); + } + + public CommandObject getCommandByName(String _commandname, int _commandtype) + { + CommandObject oCommand = null; + for (int i = 0; i < CommandObjects.size(); i++) + { + oCommand = CommandObjects.get(i); + if ((oCommand.Name.equals(_commandname)) && (oCommand.CommandType == _commandtype)) + { + return oCommand; + } + } + if (oCommand == null) + { + oCommand = new CommandObject(_commandname, _commandtype); + CommandObjects.add(oCommand); + } + return oCommand; + } + + public void setQueryByName(String _QueryName) + { + CommandObject oQueryObject = new CommandObject(_QueryName, com.sun.star.sdb.CommandType.QUERY); + this.CommandObjects.add(oQueryObject); + } + + public class CommandObject + { + + private XNameAccess xColumns; + private XPropertySet xPropertySet; + private String Name; + private int CommandType; + + private CommandObject(String _CommandName, int _CommandType) + { + try + { + Object oCommand; + this.Name = _CommandName; + this.CommandType = _CommandType; + if (CommandType == com.sun.star.sdb.CommandType.TABLE) + { + oCommand = getTableNamesAsNameAccess().getByName(Name); + } + else + { + oCommand = getQueryNamesAsNameAccess().getByName(Name); + } + XColumnsSupplier xCommandCols = UnoRuntime.queryInterface( XColumnsSupplier.class, oCommand ); + xPropertySet = UnoRuntime.queryInterface( XPropertySet.class, oCommand ); +// TODO: Performance leak getColumns() take very long. + xColumns = UnoRuntime.queryInterface( XNameAccess.class, xCommandCols.getColumns() ); + } + catch (Exception e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + } + public XNameAccess getColumns() + { + return xColumns; + } + public String getName() + { + return Name; + } + public XPropertySet getPropertySet() + { + return xPropertySet; + } + } + + public boolean hasEscapeProcessing(XPropertySet _xQueryPropertySet) + { + boolean bHasEscapeProcessing = false; + try + { + if (_xQueryPropertySet.getPropertySetInfo().hasPropertyByName("EscapeProcessing")) + { + bHasEscapeProcessing = AnyConverter.toBoolean(_xQueryPropertySet.getPropertyValue("EscapeProcessing")); + } + } + catch (Exception e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + return bHasEscapeProcessing; + } + + private XNameAccess getQueryNamesAsNameAccess() + { + XQueriesSupplier xDBQueries = UnoRuntime.queryInterface( XQueriesSupplier.class, DBConnection ); + xQueryNames = xDBQueries.getQueries(); + return xQueryNames; + } + + public XNameAccess getTableNamesAsNameAccess() + { + XTablesSupplier xDBTables = UnoRuntime.queryInterface( XTablesSupplier.class, DBConnection ); + return xDBTables.getTables(); + } + + public String[] getQueryNames() + { + if (QueryNames != null && QueryNames.length > 0) + { + return QueryNames; + } + QueryNames = getQueryNamesAsNameAccess().getElementNames(); + return QueryNames; + } + + public String[] getTableNames() + { + if (TableNames != null && TableNames.length > 0) + { + return TableNames; + } + TableNames = getTableNamesAsNameAccess().getElementNames(); + return TableNames; + } + + private void InitializeWidthList() + { + WidthList = new int[17][2]; + WidthList[0][0] = DataType.BIT; // == -7; + WidthList[1][0] = DataType.BOOLEAN; // = 16 + WidthList[2][0] = DataType.TINYINT; // == -6; + WidthList[3][0] = DataType.BIGINT; // == -5; + WidthList[4][0] = DataType.LONGVARCHAR; // == -1; + WidthList[5][0] = DataType.CHAR; // == 1; + WidthList[6][0] = DataType.NUMERIC; // == 2; + WidthList[7][0] = DataType.DECIMAL; // == 3; [with fractional part] + WidthList[8][0] = DataType.INTEGER; // == 4; + WidthList[9][0] = DataType.SMALLINT; // == 5; + WidthList[10][0] = DataType.FLOAT; // == 6; + WidthList[11][0] = DataType.REAL; // == 7; + WidthList[12][0] = DataType.DOUBLE; // == 8; + WidthList[13][0] = DataType.VARCHAR; // == 12; + WidthList[14][0] = DataType.DATE; // == 91; + WidthList[15][0] = DataType.TIME; // == 92; + WidthList[16][0] = DataType.TIMESTAMP; // == 93; + // NumericTypes are all types where aggregate functions can be performed on. + // Similarly to a major competitor date/time/timestamp fields are not included + + + } + + public boolean isBinaryDataType(int _itype) + { + if (NumericTypes == null) + { + InitializeWidthList(); + } + return (JavaTools.FieldInIntTable(BinaryTypes, _itype) > -1); + } + + public int getMaxTablesInSelect() + { + try + { + int itablecount = xDBMetaData.getMaxTablesInSelect(); + if (itablecount == 0) + { + return DBMetaData.NOLIMIT; + } + else + { + return itablecount; + } + } + catch (SQLException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + return - 1; + } + } + + public int getMaxColumnsInSelect() + { + return iMaxColumnsInSelect; + } + + private void setMaxColumnsInSelect() throws SQLException + { + iMaxColumnsInSelect = xDBMetaData.getMaxColumnsInSelect(); + if (iMaxColumnsInSelect == 0) + { + iMaxColumnsInSelect = DBMetaData.NOLIMIT; + } + } + + public int getMaxColumnsInTable() throws SQLException + { + int iMaxColumnsInTable = xDBMetaData.getMaxColumnsInTable(); + if (iMaxColumnsInTable == 0) + { + iMaxColumnsInTable = DBMetaData.NOLIMIT; + } + return iMaxColumnsInTable; + } + + private void getDataSourceObjects() throws Exception + { + try + { + xDBMetaData = DBConnection.getMetaData(); + getDataSourceInterfaces(); + setMaxColumnsInSelect(); + } + catch (SQLException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + } + + private void ensureDataSourceSettings() throws UnknownPropertyException, WrappedTargetException + { + if ( m_dataSourceSettings != null ) + return; + + XPropertySet dataSourceProperties = UnoRuntime.queryInterface( XPropertySet.class, getDataSource() ); + m_dataSourceSettings = UnoRuntime.queryInterface( XPropertySet.class, dataSourceProperties.getPropertyValue( "Settings" ) ); + } + + public boolean isSQL92CheckEnabled() + { + boolean isSQL92CheckEnabled = false; + try + { + ensureDataSourceSettings(); + isSQL92CheckEnabled = AnyConverter.toBoolean( m_dataSourceSettings.getPropertyValue( "EnableSQL92Check" ) ); + } + catch (Exception e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + return isSQL92CheckEnabled; + } + + public XDataSource getDataSource() + { + if (m_dataSource == null) + { + try + { + Object oDataSource = xNameAccess.getByName(DataSourceName); + m_dataSource = UnoRuntime.queryInterface( XDataSource.class, oDataSource ); + } + catch (com.sun.star.container.NoSuchElementException e) + { + } + catch (com.sun.star.lang.WrappedTargetException e) + { + } + } + return m_dataSource; + } + + private void setDataSourceByName(String _DataSourceName) + { + try + { + this.DataSourceName = _DataSourceName; + getDataSourceInterfaces(); + XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, getDataSource() ); + if (xDocu != null) + { + xModel = xDocu.getDatabaseDocument(); + } + } + catch (Exception e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + } + + private void getDataSourceInterfaces() throws Exception + { + xDataSourcePropertySet = UnoRuntime.queryInterface( XPropertySet.class, getDataSource() ); + bPasswordIsRequired = ((Boolean) xDataSourcePropertySet.getPropertyValue("IsPasswordRequired")).booleanValue(); + } + + public boolean getConnection(PropertyValue[] curproperties) + { + try + { + XConnection xConnection = null; + if (Properties.hasPropertyValue(curproperties, PropertyNames.ACTIVE_CONNECTION)) + { + xConnection = UnoRuntime.queryInterface( XConnection.class, Properties.getPropertyValue( curproperties, PropertyNames.ACTIVE_CONNECTION ) ); + if (xConnection != null) + { + com.sun.star.container.XChild child = UnoRuntime.queryInterface( com.sun.star.container.XChild.class, xConnection ); + + m_dataSource = UnoRuntime.queryInterface( XDataSource.class, child.getParent() ); + XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, m_dataSource ); + if (xDocu != null) + { + xModel = xDocu.getDatabaseDocument(); + } + XPropertySet xPSet = UnoRuntime.queryInterface( XPropertySet.class, m_dataSource ); + if (xPSet != null) + { + DataSourceName = AnyConverter.toString(xPSet.getPropertyValue(PropertyNames.PROPERTY_NAME)); + } + return getConnection(xConnection); + } + else + { + bdisposeConnection = true; + } + } + else + { + bdisposeConnection = true; + } + if (Properties.hasPropertyValue(curproperties, "DataSourceName")) + { + String sDataSourceName = AnyConverter.toString(Properties.getPropertyValue(curproperties, "DataSourceName")); + return getConnection(sDataSourceName); + } + else if (Properties.hasPropertyValue(curproperties, "DataSource")) + { + m_dataSource = UnoRuntime.queryInterface( XDataSource.class, Properties.getPropertyValue( curproperties, "DataSource" ) ); + XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, this.m_dataSource ); + if (xDocu != null) + { + xModel = xDocu.getDatabaseDocument(); + } + return getConnection(m_dataSource); + } + if (Properties.hasPropertyValue(curproperties, "DatabaseLocation")) + { + String sDataSourceName = AnyConverter.toString(Properties.getPropertyValue(curproperties, "DatabaseLocation")); + return getConnection(sDataSourceName); + } + } + catch (IllegalArgumentException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + catch (UnknownPropertyException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + catch (WrappedTargetException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + + return false; + } + + private boolean getConnection(String _DataSourceName) + { + setDataSourceByName(_DataSourceName); + return getConnection( getDataSource() ); + } + + private boolean getConnection(com.sun.star.sdbc.XConnection _DBConnection) + { + try + { + this.DBConnection = _DBConnection; + this.m_connectionTools = UnoRuntime.queryInterface( XConnectionTools.class, this.DBConnection ); + getDataSourceObjects(); + return true; + } + catch (Exception e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + return false; + } + } + + private boolean getConnection(XDataSource _dataSource) + { + Resource oResource = new Resource(xMSF); + try + { + int iMsg = 0; + boolean bgetConnection = false; + if (DBConnection != null) + { + xConnectionComponent.dispose(); + } + getDataSourceInterfaces(); + if (!bPasswordIsRequired) + { + DBConnection = _dataSource.getConnection(PropertyNames.EMPTY_STRING, PropertyNames.EMPTY_STRING); + bgetConnection = true; + } + else + { + XInteractionHandler xInteractionHandler = UnoRuntime.queryInterface( XInteractionHandler.class, xMSF.createInstance("com.sun.star.task.InteractionHandler") ); + boolean bExitLoop = true; + do + { + XCompletedConnection xCompleted2 = UnoRuntime.queryInterface( XCompletedConnection.class, _dataSource ); + try + { + DBConnection = xCompleted2.connectWithCompletion( xInteractionHandler ); + bgetConnection = DBConnection != null; + if (!bgetConnection) + { + bExitLoop = true; + } + } + catch (Exception exception) + { + // Note: WindowAttributes from toolkit/source/awt/vclxtoolkit.cxx + String sMsgNoConnection = oResource.getResText("RID_DB_COMMON_14"); + iMsg = showMessageBox("QueryBox", VclWindowPeerAttribute.RETRY_CANCEL, sMsgNoConnection); + bExitLoop = iMsg == 0; + bgetConnection = false; + } + } + while (!bExitLoop); + } + if (!bgetConnection) + { + String sMsgConnectionImpossible = oResource.getResText("RID_DB_COMMON_35"); + showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMsgConnectionImpossible); + } + else + { + xConnectionComponent = UnoRuntime.queryInterface( XComponent.class, DBConnection ); + m_connectionTools = UnoRuntime.queryInterface( XConnectionTools.class, DBConnection ); + getDataSourceObjects(); + } + return bgetConnection; + } + catch (Exception e) + { + String sMsgConnectionImpossible = oResource.getResText("RID_DB_COMMON_35"); + showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMsgConnectionImpossible); + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + return false; + } + } + + public int getMaxColumnNameLength() + { + try + { + if (iMaxColumnNameLength <= 0) + { + iMaxColumnNameLength = xDBMetaData.getMaxColumnNameLength(); + } + return iMaxColumnNameLength; + } + catch (SQLException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + return 0; + } + } + + public int getMaxTableNameLength() + { + try + { + if (iMaxTableNameLength <= 0) + { + iMaxTableNameLength = xDBMetaData.getMaxTableNameLength(); + } + return iMaxTableNameLength; + } + catch (SQLException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + return 0; + } + } + + public boolean supportsPrimaryKeys() + { + boolean supportsPrimaryKeys = false; + try + { + ensureDataSourceSettings(); + Any primaryKeySupport = (Any)m_dataSourceSettings.getPropertyValue( "PrimaryKeySupport" ); + if ( AnyConverter.isVoid( primaryKeySupport ) ) + supportsPrimaryKeys = supportsCoreSQLGrammar(); + else + supportsPrimaryKeys = AnyConverter.toBoolean( primaryKeySupport ); + } + catch ( Exception ex ) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, ex ); + } + return supportsPrimaryKeys; + } + + private boolean supportsCoreSQLGrammar() + { + try + { + return xDBMetaData.supportsCoreSQLGrammar(); + } + catch (SQLException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + return false; + } + } + + public boolean supportsQueriesInFrom() throws SQLException + { + return m_connectionTools.getDataSourceMetaData().supportsQueriesInFrom(); + } + + public String suggestName( final int i_objectType, final String i_baseName ) throws IllegalArgumentException, SQLException + { + return m_connectionTools.getObjectNames().suggestName( i_objectType, i_baseName ); + } + + /** + * inserts a Query to a datasource; There is no validation if the queryname is already existing in the datasource + */ + public boolean createQuery(SQLQueryComposer _oSQLQueryComposer, String _QueryName) + { + try + { + XQueryDefinitionsSupplier xQueryDefinitionsSuppl = UnoRuntime.queryInterface( XQueryDefinitionsSupplier.class, m_dataSource ); + XNameAccess xQueryDefs = xQueryDefinitionsSuppl.getQueryDefinitions(); + XSingleServiceFactory xSSFQueryDefs = UnoRuntime.queryInterface( XSingleServiceFactory.class, xQueryDefs ); + Object oQuery = xSSFQueryDefs.createInstance(); //"com.sun.star.sdb.QueryDefinition" + XPropertySet xPSet = UnoRuntime.queryInterface( XPropertySet.class, oQuery ); + + String s = _oSQLQueryComposer.m_xQueryAnalyzer.getQuery(); + xPSet.setPropertyValue(PropertyNames.COMMAND, s); + + XNameContainer xNameCont = UnoRuntime.queryInterface( XNameContainer.class, xQueryDefs ); + m_connectionTools.getObjectNames().checkNameForCreate(com.sun.star.sdb.CommandType.QUERY, _QueryName); + xNameCont.insertByName(_QueryName, oQuery); + return true; + } + catch (WrappedTargetException exception) + { + SQLException sqlError = null; + try + { + sqlError = (SQLException) exception.TargetException; + } + catch (ClassCastException castError) + { + } + + if (sqlError != null) + { + callSQLErrorMessageDialog(sqlError, null); + return false; + } + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, exception ); + } + catch (SQLException e) + { + callSQLErrorMessageDialog(e, null); + return false; + } + catch (Exception e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + return false; + } + + public void dispose() + { + if ((DBConnection != null) && (this.bdisposeConnection)) + { + xConnectionComponent.dispose(); + } + } + + public XHierarchicalNameAccess getReportDocuments() + { + XReportDocumentsSupplier xReportDocumentSuppl = UnoRuntime.queryInterface( XReportDocumentsSupplier.class, this.xModel ); + xReportDocumentSuppl.getReportDocuments(); + return UnoRuntime.queryInterface( XHierarchicalNameAccess.class, xReportDocumentSuppl.getReportDocuments() ); + } + + public XHierarchicalNameAccess getFormDocuments() + { + XFormDocumentsSupplier xFormDocumentSuppl = UnoRuntime.queryInterface( XFormDocumentsSupplier.class, xModel ); + return UnoRuntime.queryInterface( XHierarchicalNameAccess.class, xFormDocumentSuppl.getFormDocuments() ); + } + + public boolean hasFormDocumentByName(String _sFormName) + { + XFormDocumentsSupplier xFormDocumentSuppl = UnoRuntime.queryInterface( XFormDocumentsSupplier.class, xModel ); + XNameAccess xFormNameAccess = UnoRuntime.queryInterface( XNameAccess.class, xFormDocumentSuppl.getFormDocuments() ); + return xFormNameAccess.hasByName(_sFormName); + } + + public void addFormDocument(XComponent _xComponent) + { + XHierarchicalNameAccess _xFormDocNameAccess = getFormDocuments(); + addDatabaseDocument(_xComponent, _xFormDocNameAccess, false); + } + + public void addReportDocument(XComponent _xComponent, boolean _bcreatedynamicreport) + { + XHierarchicalNameAccess xReportDocNameAccess = getReportDocuments(); + addDatabaseDocument(_xComponent, xReportDocNameAccess, _bcreatedynamicreport); + } + + /** + * adds the passed document as a report or a form to the database. Afterwards the document is deleted. + * the document may not be open + * @param i_createTemplate describes the type of the document: "form" or "report" + */ + private void addDatabaseDocument(XComponent _xComponent, XHierarchicalNameAccess _xDocNameAccess, boolean i_createTemplate) + { + try + { + XModel xDocumentModel = UnoRuntime.queryInterface( XModel.class, _xComponent ); + String documentURL = xDocumentModel.getURL(); + String basename = FileAccess.getBasename(documentURL, "/"); + XCloseable xCloseable = UnoRuntime.queryInterface( XCloseable.class, _xComponent ); + xCloseable.close(false); + + NamedValueCollection creationArgs = new NamedValueCollection(); + creationArgs.put( PropertyNames.PROPERTY_NAME, basename ); + creationArgs.put( PropertyNames.URL, documentURL ); + creationArgs.put( "AsTemplate", i_createTemplate ); + XMultiServiceFactory xDocMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, _xDocNameAccess ); + Object oDBDocument = xDocMSF.createInstanceWithArguments( "com.sun.star.sdb.DocumentDefinition", creationArgs.getPropertyValues() ); + XHierarchicalNameContainer xHier = UnoRuntime.queryInterface( XHierarchicalNameContainer.class, _xDocNameAccess ); + String sdocname = Desktop.getUniqueName(_xDocNameAccess, basename); + xHier.insertByHierarchicalName(sdocname, oDBDocument); + XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess"); + XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface( XSimpleFileAccess.class, xInterface ); + xSimpleFileAccess.kill(documentURL); + } + catch (Exception e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + } + + public void createTypeInspector() throws SQLException + { + oTypeInspector = new TypeInspector(xDBMetaData.getTypeInfo()); + } + + public TypeInspector getDBDataTypeInspector() + { + return oTypeInspector; + } + + private String[] StringsFromResultSet(XResultSet _xResultSet, int _icol) + { + String[] sColValues = null; + if (_xResultSet == null) + return sColValues; + try + { + XRow xRow = UnoRuntime.queryInterface( XRow.class, _xResultSet ); + ArrayList<String> aColVector = new ArrayList<String>(); + while (_xResultSet.next()) + { + aColVector.add(xRow.getString(_icol)); + } + sColValues = new String[aColVector.size()]; + aColVector.toArray(sColValues); + } + catch (SQLException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + } + return sColValues; + } + + public String[] getCatalogNames() + { + try + { + XResultSet xResultSet = xDBMetaData.getCatalogs(); + return StringsFromResultSet(xResultSet, 1); + } + catch (SQLException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + return null; + } + } + + public String[] getSchemaNames() + { + try + { + XResultSet xResultSet = xDBMetaData.getSchemas(); + return StringsFromResultSet(xResultSet, 1); + } + catch (SQLException e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + return null; + } + } + + public boolean storeDatabaseDocumentToTempPath(XComponent _xcomponent, String _storename) + { + try + { + String storepath = FileAccess.getOfficePath(xMSF, "Temp") + "/" + _storename; + XStorable xStoreable = UnoRuntime.queryInterface( XStorable.class, _xcomponent ); + PropertyValue[] oStoreProperties = new PropertyValue[1]; + oStoreProperties[0] = Properties.createProperty("FilterName", "writer8"); + storepath += ".odt"; + xStoreable.storeAsURL(storepath, oStoreProperties); + return true; + } + catch (Exception e) + { + Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e ); + return false; + } + } + + public int showMessageBox(String windowServiceName, int windowAttribute, String MessageText) + { + if (getWindowPeer() != null) + { + return SystemDialog.showMessageBox(xMSF, xWindowPeer, windowServiceName, windowAttribute, MessageText); + } + else + { + return SystemDialog.showMessageBox(xMSF, windowServiceName, windowAttribute, MessageText); + } + } + + /** + * @return Returns the xWindowPeer. + */ + private XWindowPeer getWindowPeer() + { + return xWindowPeer; + } + + /** + * @param windowPeer The xWindowPeer to set. + * Should be called as soon as a Windowpeer of a wizard dialog is available + * The windowpeer is needed to call a Messagebox + */ + public void setWindowPeer(XWindowPeer windowPeer) + { + xWindowPeer = windowPeer; + } + + public void callSQLErrorMessageDialog(SQLException oSQLException, XWindow _xWindow) + { + try + { + Object oDialog = xMSF.createInstance("com.sun.star.sdb.ErrorMessageDialog"); + XInitialization xInitialization = UnoRuntime.queryInterface( XInitialization.class, oDialog ); + PropertyValue[] aPropertyValue = new PropertyValue[2]; + aPropertyValue[0] = Properties.createProperty("SQLException", oSQLException); + aPropertyValue[1] = Properties.createProperty("ParentWindow", _xWindow); + xInitialization.initialize(aPropertyValue); + XExecutableDialog xExecutableDialog = UnoRuntime.queryInterface( XExecutableDialog.class, oDialog ); + xExecutableDialog.execute(); + } + catch (com.sun.star.uno.Exception ex) + { + Logger.getLogger( getClass().getName() ).log( Level.SEVERE, "error calling the error dialog", ex ); + } + } + + public void finish() + { + xQueryNames = null; + xNameAccess = null; + xDatabaseContext = null; + xDBMetaData = null; + m_dataSource = null; + xModel = null; + xDataSourcePropertySet = null; + xWindowPeer = null; + DBConnection = null; + m_connectionTools = null; + xMSF = null; + xConnectionComponent = null; + CommandObjects = null; + } +} diff --git a/wizards/com/sun/star/wizards/db/DatabaseObjectWizard.java b/wizards/com/sun/star/wizards/db/DatabaseObjectWizard.java new file mode 100644 index 000000000..013fb547c --- /dev/null +++ b/wizards/com/sun/star/wizards/db/DatabaseObjectWizard.java @@ -0,0 +1,170 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ + +package com.sun.star.wizards.db; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.frame.XController; +import com.sun.star.frame.XFrame; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdb.application.XDatabaseDocumentUI; +import com.sun.star.sdbc.SQLException; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.wizards.common.Desktop; +import com.sun.star.wizards.common.NamedValueCollection; +import com.sun.star.wizards.common.Properties; +import com.sun.star.wizards.ui.WizardDialog; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * is a base class for a wizard creating a database object + */ +public abstract class DatabaseObjectWizard extends WizardDialog +{ + protected final PropertyValue[] m_wizardContext; + protected final XDatabaseDocumentUI m_docUI; + protected final XFrame m_frame; + + protected DatabaseObjectWizard( final XMultiServiceFactory i_orb, final int i_helpIDBase, final PropertyValue[] i_wizardContext ) + { + super( i_orb, i_helpIDBase ); + m_wizardContext = i_wizardContext; + + final NamedValueCollection wizardContext = new NamedValueCollection( m_wizardContext ); + m_docUI = wizardContext.queryOrDefault( "DocumentUI", (XDatabaseDocumentUI)null, XDatabaseDocumentUI.class ); + + if ( m_docUI != null ) + { + XController docController = UnoRuntime.queryInterface( XController.class, m_docUI ); + m_frame = docController.getFrame(); + } + else + { + XFrame parentFrame = wizardContext.queryOrDefault( "ParentFrame", (XFrame)null, XFrame.class ); + if ( parentFrame != null ) + m_frame = parentFrame; + else + m_frame = Desktop.getActiveFrame( xMSF ); + } + } + + protected final void loadSubComponent( final int i_type, final String i_name, final boolean i_forEditing ) + { + try + { + if ( m_docUI != null ) + m_docUI.loadComponent( i_type, i_name, i_forEditing ); + } + catch ( IllegalArgumentException ex ) + { + Logger.getLogger( this.getClass().getName() ).log( Level.SEVERE, null, ex ); + } + catch ( NoSuchElementException ex ) + { + Logger.getLogger( this.getClass().getName() ).log( Level.SEVERE, null, ex ); + } + catch ( SQLException ex ) + { + Logger.getLogger( this.getClass().getName() ).log( Level.SEVERE, null, ex ); + } + } + + public interface WizardFromCommandLineStarter + { + void start(XMultiServiceFactory factory, PropertyValue[] curproperties); + } + + protected static void executeWizardFromCommandLine( final String i_args[], WizardFromCommandLineStarter starter ) + { + final String settings[] = new String[] { null, null, null }; + final int IDX_PIPE_NAME = 0; + final int IDX_LOCATION = 1; + final int IDX_DSN = 2; + + // some simple parsing + boolean failure = false; + int settingsIndex = -1; + for ( int i=0; i<i_args.length; ++i ) + { + if ( settingsIndex >= 0 ) + { + settings[ settingsIndex ] = i_args[i]; + settingsIndex = -1; + continue; + } + + if ( i_args[i].equals( "--pipe-name" ) ) + { + settingsIndex = IDX_PIPE_NAME; + continue; + } + + if ( i_args[i].equals( "--database-location" ) ) + { + settingsIndex = IDX_LOCATION; + continue; + } + + if ( i_args[i].equals( "--data-source-name" ) ) + { + settingsIndex = IDX_DSN; + continue; + } + + failure = true; + } + + if ( settings[ IDX_PIPE_NAME ] == null ) + failure = true; + + if ( ( settings[ IDX_DSN ] == null ) && ( settings[ IDX_LOCATION ] == null ) ) + failure = true; + + if ( failure ) + { + System.err.println( "supported arguments: " ); + System.err.println( " --pipe-name <name> : specifies the name of the pipe to connect to the running OOo instance" ); + System.err.println( " --database-location <url> : specifies the URL of the database document to work with" ); + System.err.println( " --data-source-name <name> : specifies the name of the data source to work with" ); + return; + } + + final String ConnectStr = "uno:pipe,name=" + settings[IDX_PIPE_NAME] + ";urp;StarOffice.ServiceManager"; + try + { + final XMultiServiceFactory serviceFactory = Desktop.connect(ConnectStr); + if (serviceFactory != null) + { + PropertyValue[] curproperties = new PropertyValue[1]; + if ( settings[ IDX_LOCATION ] != null ) + curproperties[0] = Properties.createProperty( "DatabaseLocation", settings[ IDX_LOCATION ] ); + else + curproperties[0] = Properties.createProperty( "DataSourceName", settings[ IDX_DSN ] ); + + starter.start(serviceFactory, curproperties); + } + } + catch (java.lang.Exception jexception) + { + jexception.printStackTrace(System.err); + } + } +} diff --git a/wizards/com/sun/star/wizards/db/FieldColumn.java b/wizards/com/sun/star/wizards/db/FieldColumn.java new file mode 100644 index 000000000..dd8b85a92 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/FieldColumn.java @@ -0,0 +1,403 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XNameAccess; +import com.sun.star.sdbc.DataType; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.wizards.common.*; + +public class FieldColumn +{ + protected int ColIndex; + + private Object DefaultValue; + private String m_sFieldName; + private String m_sDisplayFieldName; + private String FieldTitle; + private String m_sCommandName; + private int m_nDBFormatKey; + private int m_nFieldType; + private XPropertySet m_xColPropertySet; + + // field meta data + private int FieldWidth; + private boolean bIsNumberFormat; + + private static boolean bFormatKeysInitialized = false; + private static int iDateFormatKey; + private static int iDateTimeFormatKey; + private static int iNumberFormatKey; + private static int iTextFormatKey; + private static int iTimeFormatKey; + private static int iLogicalFormatKey; + + private CommandMetaData m_aCommandMetaData; + + public FieldColumn(CommandMetaData oCommandMetaData, String _FieldName, String _CommandName, boolean _bInstantiateByDisplayName) + { + m_sCommandName = _CommandName; + if (_bInstantiateByDisplayName) + { + m_sDisplayFieldName = _FieldName; + m_sFieldName = getOnlyFieldName(_FieldName, _CommandName); + } + else + { + m_sFieldName = _FieldName; + m_sDisplayFieldName = composeDisplayFieldName(_CommandName, m_sFieldName); + } + FieldTitle = m_sFieldName; + m_aCommandMetaData = oCommandMetaData; + } + + public FieldColumn(CommandMetaData oCommandMetaData, XNameAccess _xColumns, String _FieldName) + { + m_sFieldName = _FieldName; +// FieldTitle = m_sFieldName; + m_sDisplayFieldName = m_sFieldName; + ColIndex = JavaTools.FieldInList(_xColumns.getElementNames(), m_sFieldName) + 1; + initializeFormatKeys(oCommandMetaData, _xColumns); + try + { + m_sCommandName = (String)m_xColPropertySet.getPropertyValue("TableName"); + } + catch (com.sun.star.beans.UnknownPropertyException e) + { + } + catch (com.sun.star.lang.WrappedTargetException e) + { + } + } + + public int getFieldType() + { + if (m_nFieldType == 0) + { + DBMetaData.CommandObject oTable = m_aCommandMetaData.getTableByName(m_sCommandName); + initializeFormatKeys(m_aCommandMetaData, oTable.getColumns()); + } + return m_nFieldType; + } + + public int getFieldWidth() + { + getFieldType(); // will collect meta data 'bout the column, if not already done so + return FieldWidth; + } + + public int getDBFormatKey() + { + getFieldType(); // will collect meta data 'bout the column, if not already done so + return m_nDBFormatKey; + } + + public boolean isNumberFormat() + { + getFieldType(); // will collect meta data 'bout the column, if not already done so + return bIsNumberFormat; + } + + /** + * Remove the pre name, we want the name after the 'dot' + * @param _DisplayFieldName + * @param _CommandName + * @return + */ + private String getOnlyFieldName(String _DisplayFieldName, String _CommandName) + { + return _DisplayFieldName.substring(_CommandName.length() + 1); + } + + public static String composeDisplayFieldName(String _sCommandName, String _sFieldName) + { + return _sCommandName + "." + _sFieldName; + } + + private void initializeFormatKeys(CommandMetaData oCommandMetaData, XNameAccess _xColumns) + { + try + { + if (!bFormatKeysInitialized) + { + final NumberFormatter aNumberFormatter = oCommandMetaData.getNumberFormatter(); + + iDateFormatKey = aNumberFormatter.getDateFormatKey(); + iDateTimeFormatKey = aNumberFormatter.getDateTimeFormatKey(); + iNumberFormatKey = aNumberFormatter.getNumberFormatKey(); + iTextFormatKey = aNumberFormatter.getTextFormatKey(); + iTimeFormatKey = aNumberFormatter.getTimeFormatKey(); + iLogicalFormatKey = aNumberFormatter.getLogicalFormatKey(); + bFormatKeysInitialized = true; + } + + m_xColPropertySet = UnoRuntime.queryInterface(XPropertySet.class, _xColumns.getByName(m_sFieldName)); + ColIndex = JavaTools.FieldInList(_xColumns.getElementNames(), m_sFieldName) + 1; + m_nFieldType = AnyConverter.toInt(m_xColPropertySet.getPropertyValue("Type")); + getTyperelatedFieldData(); + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + } + + public XPropertySet getXColumnPropertySet() + { + getFieldType(); // will collect meta data 'bout the column, if not already done so + return m_xColPropertySet; + } + + public String getDisplayFieldName() + { + return m_sDisplayFieldName; + } + + public String getCommandName() + { + return m_sCommandName; + } + + public String getFieldName() + { + return m_sFieldName; + } + + public String getFieldTitle() + { + return FieldTitle; + } + + public void setFieldTitle(String _sTitle) + { + FieldTitle = _sTitle; + } + + + + public boolean isBoolean() + { + boolean bIsBoolean = false; + switch ( getFieldType() ) + { + case DataType.BIT: // == -7; + case DataType.BOOLEAN: + bIsBoolean = true; + break; + default: + bIsBoolean = false; + } + return bIsBoolean; + } + + private void getTyperelatedFieldData() + { + int StandardFormatKey = 0; + try + { + switch ( getFieldType() ) + { + case DataType.BIT: // == -7; + case DataType.BOOLEAN: + // Todo: Look if the defaultvalue has been set in the Datasource + StandardFormatKey = iLogicalFormatKey; + FieldWidth = 5; + bIsNumberFormat = true; + break; + + case DataType.TINYINT: // == -6; + case DataType.SMALLINT: // == 5; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 5; + bIsNumberFormat = true; + break; + + case DataType.INTEGER: // == 4; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 10; + bIsNumberFormat = true; + break; + + case DataType.BIGINT: // == -5; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 15; + bIsNumberFormat = true; + break; + + case DataType.CHAR: // == 1; + StandardFormatKey = iTextFormatKey; + getTextFieldWidth(10); + bIsNumberFormat = false; + break; + + case DataType.VARCHAR: // == 12; + StandardFormatKey = iTextFormatKey; + getTextFieldWidth(30); + bIsNumberFormat = false; + break; + + case DataType.LONGVARCHAR: // == -1; + StandardFormatKey = iTextFormatKey; + getTextFieldWidth(60); + bIsNumberFormat = false; + break; + + case DataType.NUMERIC: // == 2; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 20; + bIsNumberFormat = true; + break; + + case DataType.DECIMAL: // == 3; [with fractional part] + case DataType.FLOAT: // == 6; + case DataType.REAL: // == 7; + case DataType.DOUBLE: // == 8; + StandardFormatKey = iNumberFormatKey; + FieldWidth = 10 + AnyConverter.toInt(m_xColPropertySet.getPropertyValue("Scale")) + 1; + bIsNumberFormat = true; + break; + + case DataType.DATE: // == 91; + StandardFormatKey = iDateFormatKey; + FieldWidth = 10; + bIsNumberFormat = true; + break; + + case DataType.TIME: // == 92; + StandardFormatKey = iTimeFormatKey; + FieldWidth = 10; + bIsNumberFormat = true; + break; + + case DataType.TIMESTAMP: // == 93; + StandardFormatKey = iDateTimeFormatKey; + FieldWidth = 20; + bIsNumberFormat = true; + break; + } + + Object oKey = m_xColPropertySet.getPropertyValue("FormatKey"); + if (AnyConverter.isVoid(oKey)) + { + m_nDBFormatKey = StandardFormatKey; + } + else + { + m_nDBFormatKey = AnyConverter.toInt(oKey); + } + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + m_nDBFormatKey = StandardFormatKey; + } + } + + private void getTextFieldWidth(int iWidth) + { + try + { + FieldWidth = AnyConverter.toInt(m_xColPropertySet.getPropertyValue("Precision")); + if (FieldWidth > 0) + { + if (FieldWidth > (2 * iWidth)) + { + FieldWidth = 2 * iWidth; + } + else if (FieldWidth == 0) + { + FieldWidth = iWidth; + } + } + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + } + } + + private void initDefaultValue() + { + switch (getFieldType()) + { + case DataType.BIT: // == -7; + case DataType.BOOLEAN: + DefaultValue = Integer.valueOf("1"); + break; + + case DataType.TINYINT: // == -6; + DefaultValue = Integer.valueOf("98"); + break; + + case DataType.SMALLINT: // == 5; + DefaultValue = Integer.valueOf("987"); + break; + + case DataType.INTEGER: // == 4; + DefaultValue = Integer.valueOf("9876"); + break; + + case DataType.BIGINT: // == -5; + DefaultValue = Integer.valueOf("98765"); + break; + + case DataType.CHAR: // == 1; + DefaultValue = String.valueOf('x'); + break; + + case DataType.VARCHAR: // == 12; + case DataType.LONGVARCHAR: // == -1; + DefaultValue = BlindtextCreator.getBlindTextString(FieldTitle, FieldWidth); + break; + + case DataType.NUMERIC: // == 2; + case DataType.DECIMAL: // == 3; [with fractional part] + case DataType.FLOAT: // == 6; + case DataType.REAL: // == 7; + case DataType.DOUBLE: // == 8; + DefaultValue = Double.valueOf("9876.54"); + break; + + case DataType.DATE: // == 91; + DefaultValue = Double.valueOf("42510"); + break; + + case DataType.TIME: // == 92; + DefaultValue = Double.valueOf("10"); + break; + + case DataType.TIMESTAMP: // == 93; + DefaultValue = Double.valueOf("5454110"); + break; + + default: + break; + } + } + + public Object getDefaultValue() + { + if ( DefaultValue == null ) + initDefaultValue(); + return DefaultValue; + } + +} diff --git a/wizards/com/sun/star/wizards/db/MANIFEST.MF b/wizards/com/sun/star/wizards/db/MANIFEST.MF new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/wizards/com/sun/star/wizards/db/MANIFEST.MF diff --git a/wizards/com/sun/star/wizards/db/QueryMetaData.java b/wizards/com/sun/star/wizards/db/QueryMetaData.java new file mode 100644 index 000000000..abbc60367 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/QueryMetaData.java @@ -0,0 +1,244 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.beans.PropertyValue; + +import java.util.*; +import com.sun.star.wizards.common.*; + +public class QueryMetaData extends CommandMetaData +{ + + private SQLQueryComposer oSQLQueryComposer = null; + public String Command; + // Vector CommandNamesV; + private PropertyValue[][] m_aFilterConditions; /* = new PropertyValue[][] {}; */ + + public PropertyValue[][] GroupByFilterConditions = new PropertyValue[][] + { + }; + public int Type = QueryType.SODETAILQUERY; + + public interface QueryType + { + int SOSUMMARYQUERY = 0; + int SODETAILQUERY = 1; + } + + public QueryMetaData(XMultiServiceFactory _xMSF) + { + super(_xMSF); + } + + public void setFilterConditions(PropertyValue[][] _FilterConditions) + { + this.m_aFilterConditions = _FilterConditions; + } + + public PropertyValue[][] getFilterConditions() + { + if (m_aFilterConditions == null) + { + m_aFilterConditions = new PropertyValue[][] + { + }; + } + return m_aFilterConditions; + } + + public void setGroupByFilterConditions(PropertyValue[][] _GroupByFilterConditions) + { + this.GroupByFilterConditions = _GroupByFilterConditions; + } + + public PropertyValue[][] getGroupByFilterConditions() + { + return this.GroupByFilterConditions; + } + + public void addSeveralFieldColumns(String[] _FieldNames, String _sCommandName) + { + ArrayList<FieldColumn> oToBeAddedFieldColumns = new ArrayList<FieldColumn>(); + for (int i = 0; i < _FieldNames.length; i++) + { + FieldColumn oFieldColumn = getFieldColumn(_FieldNames[i], _sCommandName); + if (oFieldColumn == null) + { + oToBeAddedFieldColumns.add(new FieldColumn(this, _FieldNames[i], _sCommandName, false)); + } + } + if (oToBeAddedFieldColumns.size() > 0) + { + int nOldFieldCount = FieldColumns.length; + FieldColumn[] LocFieldColumns = new FieldColumn[nOldFieldCount + oToBeAddedFieldColumns.size()]; + System.arraycopy(FieldColumns, 0, LocFieldColumns, 0, nOldFieldCount); + for (int i = 0; i < oToBeAddedFieldColumns.size(); i++) + { + LocFieldColumns[nOldFieldCount + i] = oToBeAddedFieldColumns.get(i); + } + FieldColumns = LocFieldColumns; + } + } + + public void reorderFieldColumns(String[] _sDisplayFieldNames) + { + FieldColumn[] LocFieldColumns = new FieldColumn[FieldColumns.length]; + for (int i = 0; i < _sDisplayFieldNames.length; i++) + { + FieldColumn LocFieldColumn = this.getFieldColumnByDisplayName(_sDisplayFieldNames[i]); + LocFieldColumns[i] = LocFieldColumn; + } + System.arraycopy(LocFieldColumns, 0, FieldColumns, 0, LocFieldColumns.length); + } + + public void removeSeveralFieldColumnsByDisplayFieldName(String[] _DisplayFieldNames) + { + ArrayList<FieldColumn> oRemainingFieldColumns = new ArrayList<FieldColumn>(); + for (int n = 0; n < FieldColumns.length; n++) + { + String sDisplayFieldName = FieldColumns[n].getDisplayFieldName(); + if (JavaTools.FieldInList(_DisplayFieldNames, sDisplayFieldName) <= -1) + { + oRemainingFieldColumns.add(FieldColumns[n]); + } + } + FieldColumns = new FieldColumn[oRemainingFieldColumns.size()]; + oRemainingFieldColumns.toArray(FieldColumns); + } + + + + public String[] getIncludedCommandNames() + { + ArrayList<String> CommandNamesV = new ArrayList<String>(1); + for (int i = 0; i < FieldColumns.length; i++) + { + final FieldColumn CurQueryField = FieldColumns[i]; + final String CurCommandName = CurQueryField.getCommandName(); + if (!CommandNamesV.contains(CurCommandName)) + { + CommandNamesV.add(CurCommandName); + } + } + String[] sIncludedCommandNames = new String[CommandNamesV.size()]; + CommandNamesV.toArray(sIncludedCommandNames); + return sIncludedCommandNames; + } + + public static String[] getIncludedCommandNames(String[] _FieldNames) + { + ArrayList<String> CommandNames = new ArrayList<String>(1); + for (int i = 0; i < _FieldNames.length; i++) + { + String[] MetaList = JavaTools.ArrayoutofString(_FieldNames[i], "."); + if (MetaList.length > 1) + { + StringBuilder sb = new StringBuilder(PropertyNames.EMPTY_STRING); + for (int a = 0; a < MetaList.length - 1; a++) + { + sb.append(MetaList[a]); + } + String CurCommandName = sb.toString(); + if (!CommandNames.contains(CurCommandName)) + { + CommandNames.add(CurCommandName); + } + } + } + String[] sIncludedCommandNames = new String[CommandNames.size()]; + CommandNames.toArray(sIncludedCommandNames); + return sIncludedCommandNames; + } + + public void initializeFieldTitleSet() + { + try + { + if (FieldTitleSet == null) + { + FieldTitleSet = new HashMap<String, String>(); + } + String[] aCommandNames = getIncludedCommandNames(); + for (int i = 0; i < aCommandNames.length; i++) + { + String sCommandName = aCommandNames[i]; + CommandObject oTable = getTableByName(sCommandName); + String sTableName = oTable.getName(); + String[] LocFieldNames = oTable.getColumns().getElementNames(); + for (int a = 0; a < LocFieldNames.length; a++) + { + String sDisplayFieldName = FieldColumn.composeDisplayFieldName(sTableName, LocFieldNames[a]); + if (!FieldTitleSet.containsKey(sDisplayFieldName)) + { + FieldTitleSet.put(sDisplayFieldName, LocFieldNames[a]); + } + } + } + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + } + } + + public String[] getUniqueAggregateFieldNames() + { + ArrayList<String> UniqueAggregateFieldVector = new ArrayList<String>(); + for (int i = 0; i < AggregateFieldNames.length; i++) + { + if (!UniqueAggregateFieldVector.contains(AggregateFieldNames[i][0])) + { + UniqueAggregateFieldVector.add(AggregateFieldNames[i][0]); + } + } + return UniqueAggregateFieldVector.toArray(new String[UniqueAggregateFieldVector.size()]); + } + + public boolean hasNumericalFields() + { + for (int i = 0; i < FieldColumns.length; i++) + { + if (FieldColumns[i].isNumberFormat()) + { + return true; + } + } + return false; + } + + public int getAggregateIndex(String _DisplayFieldName) + { + int iAggregate = -1; + if (Type == QueryType.SOSUMMARYQUERY) + { + iAggregate = JavaTools.FieldInTable(AggregateFieldNames, _DisplayFieldName); + } + return iAggregate; + } + + public SQLQueryComposer getSQLQueryComposer() + { + if (oSQLQueryComposer == null) + { + oSQLQueryComposer = new SQLQueryComposer(this); + } + return oSQLQueryComposer; + } +} diff --git a/wizards/com/sun/star/wizards/db/RecordParser.java b/wizards/com/sun/star/wizards/db/RecordParser.java new file mode 100644 index 000000000..bb35b041f --- /dev/null +++ b/wizards/com/sun/star/wizards/db/RecordParser.java @@ -0,0 +1,244 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.XComponent; +import com.sun.star.sdbc.DataType; +import com.sun.star.sdbcx.XColumnsSupplier; +import com.sun.star.uno.Any; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.wizards.common.Helper; +import com.sun.star.sdb.XCompletedExecution; +import com.sun.star.wizards.common.InvalidQueryException; +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.sdbc.XResultSet; +import com.sun.star.task.XInteractionHandler; +import com.sun.star.wizards.common.PropertyNames; + +public class RecordParser extends QueryMetaData +{ + + private XNameAccess xColumns; + private com.sun.star.sdbc.XRow xResultSetRow; + public XResultSet ResultSet; + private XInterface xRowSet; + private XCompletedExecution xExecute; + private XComponent xRowSetComponent; + private XInteractionHandler xInteraction; + public FieldColumn[] GroupFieldColumns; + public FieldColumn[] RecordFieldColumns; + + /** Creates a new instance of RecordParser */ + public RecordParser(XMultiServiceFactory _xMSF) + { + super(_xMSF); + getInterfaces(); + } + + private void getInterfaces() + { + try + { + xRowSet = (XInterface) xMSF.createInstance("com.sun.star.sdb.RowSet"); + UnoRuntime.queryInterface(XColumnsSupplier.class, xRowSet); + xRowSetComponent = UnoRuntime.queryInterface(XComponent.class, xRowSet); + xExecute = UnoRuntime.queryInterface(XCompletedExecution.class, xRowSet); + XInterface oInteraction = (XInterface) xMSF.createInstance("com.sun.star.task.InteractionHandler"); + xInteraction = UnoRuntime.queryInterface(XInteractionHandler.class, oInteraction); + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + } + } + + private Object getColumnStringValue(int ColIndex) + { + try + { + com.sun.star.uno.Type CurType; + Object oAny; + String sValue = xResultSetRow.getString(ColIndex); //??? + CurType = new com.sun.star.uno.Type(String.class); + oAny = AnyConverter.toObject(CurType, sValue); + return oAny; + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + return null; + } + } + + private Object getColumnDoubleValue(int ColIndex, boolean bisDate) + { + try + { + Double DblValue; + if (bisDate) + { + DblValue = new Double(xResultSetRow.getDouble(ColIndex) + super.getNullDateCorrection()); + } + else + { + DblValue = new Double(xResultSetRow.getDouble(ColIndex)); + } + if (!xResultSetRow.wasNull()) + { + return DblValue; + } + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + } + return Any.VOID; + } + + private Object getColumnValue(int ColIndex, int iType) + { + Object oAny = Any.VOID; + switch (iType) + { + case DataType.BIT: // == -7; + case DataType.BOOLEAN: + case DataType.TINYINT: // == -6; + case DataType.BIGINT: // == -5; + case DataType.NUMERIC: // == 2; + case DataType.INTEGER: // == 4; + case DataType.SMALLINT: // == 5; + case DataType.DECIMAL: // == 3; [with fractional part] + case DataType.FLOAT: // == 6; + case DataType.REAL: // == 7; + case DataType.DOUBLE: // == 8; + case DataType.TIME: // == 92; + oAny = getColumnDoubleValue(ColIndex, false); + break; + + case DataType.DATE: // == 91; + case DataType.TIMESTAMP: // == 93; + oAny = getColumnDoubleValue(ColIndex, true); + break; + case DataType.CHAR: // == 1; + case DataType.VARCHAR: // == 12; + case DataType.LONGVARCHAR: // == -1; + oAny = getColumnStringValue(ColIndex); + break; + + } + + // Is the index OK; increment? + return oAny; + } + + public boolean executeCommand(int _nCommandType) throws InvalidQueryException + { + try + { + Helper.setUnoPropertyValue(xRowSet, "DataSourceName", DataSourceName); + Helper.setUnoPropertyValue(xRowSet, PropertyNames.ACTIVE_CONNECTION, DBConnection); + Helper.setUnoPropertyValue(xRowSet, PropertyNames.COMMAND, Command); + Helper.setUnoPropertyValue(xRowSet, PropertyNames.COMMAND_TYPE, Integer.valueOf(_nCommandType)); // CommandType + xExecute.executeWithCompletion(xInteraction); + com.sun.star.sdb.XResultSetAccess xResultAccess = UnoRuntime.queryInterface(com.sun.star.sdb.XResultSetAccess.class, xRowSet); + ResultSet = xResultAccess.createResultSet(); + xResultSetRow = UnoRuntime.queryInterface(com.sun.star.sdbc.XRow.class, ResultSet); + XColumnsSupplier xDBCols = UnoRuntime.queryInterface(XColumnsSupplier.class, ResultSet); + xColumns = xDBCols.getColumns(); + setCommandType(_nCommandType); + return true; + } + catch (Exception exception) + { + throw new InvalidQueryException(xMSF, Command, exception); + } + } + + public boolean getFields(String[] _sFieldNames, boolean binitializeDBColumns) + { + try + { + if (binitializeDBColumns) + { + initializeFieldColumns(_sFieldNames, xColumns); + } + String[] AllQueryFieldNames = xColumns.getElementNames(); + for (int i = 0; i < FieldColumns.length; i++) + { + String sFieldName = FieldColumns[i].getFieldName(); + int nColIndex = JavaTools.FieldInList(AllQueryFieldNames, sFieldName) + 1; + FieldColumns[i].ColIndex = nColIndex; + if (nColIndex == -1) + { + throw new InvalidQueryException(xMSF, Command); + } + } + GroupFieldColumns = getFieldColumnList(GroupFieldNames); + RecordFieldColumns = getFieldColumnList(getRecordFieldNames()); + return true; + } + catch (InvalidQueryException queryexception) + { + queryexception.printStackTrace(System.err); + return false; + } + } + + private FieldColumn[] getFieldColumnList(String[] _FieldNames) + { + FieldColumn[] LocFieldColumns = new FieldColumn[_FieldNames.length]; + for (int i = 0; i < _FieldNames.length; i++) + { + LocFieldColumns[i] = super.getFieldColumnByFieldName(_FieldNames[i]); + } + return LocFieldColumns; + } + + public Object getGroupColumnValue(int ColIndex) + { + FieldColumn CurDBFieldColumn = this.GroupFieldColumns[ColIndex]; + return getColumnValue(CurDBFieldColumn.ColIndex, CurDBFieldColumn.getFieldType()); + } + + public boolean getcurrentRecordData(java.util.ArrayList<Object[]> DataVector) + { + Object[] RecordValueArray = new Object[RecordFieldColumns.length]; + for (int i = 0; i < RecordFieldColumns.length; i++) + { + FieldColumn CurDBFieldColumn = this.RecordFieldColumns[i]; + RecordValueArray[i] = getColumnValue(CurDBFieldColumn.ColIndex, CurDBFieldColumn.getFieldType()); //FinalColIndex + } + DataVector.add(RecordValueArray); + return true; + } + + @Override + public void dispose() + { + if (xRowSetComponent != null) + { + xRowSetComponent.dispose(); + } + super.dispose(); + } +} diff --git a/wizards/com/sun/star/wizards/db/RelationController.java b/wizards/com/sun/star/wizards/db/RelationController.java new file mode 100644 index 000000000..0c77d92bb --- /dev/null +++ b/wizards/com/sun/star/wizards/db/RelationController.java @@ -0,0 +1,145 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import java.util.ArrayList; + +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XResultSet; +import com.sun.star.sdbc.XRow; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.wizards.common.PropertyNames; + +/** + * TODO To change the template for this generated type comment go to + * Window - Preferences - Java - Code Style - Code Templates + */ +public class RelationController extends CommandName +{ + + private static final int PKTABLE_CAT = 1; + private static final int PKTABLE_SCHEM = 2; + private static final int PKTABLE_NAME = 3; + private static final int PKCOLUMN_NAME = 4; + private static final int FKTABLE_CAT = 5; + private static final int FKTABLE_SCHEM = 6; + private static final int FKTABLE_NAME = 7; + private static final int FKCOLUMN_NAME = 8; + + public RelationController(CommandMetaData _CommandMetaData, String _DisplayName) + { + super(_CommandMetaData, _DisplayName); + } + + public String[] getExportedKeys() + { + String[] sReferencedTableNames = new String[] + { + }; + try + { + ArrayList<String> aReferencedTableVector = new ArrayList<String>(); + XResultSet xResultSet = super.getCommandMetaData().xDBMetaData.getExportedKeys(getCatalogName(this), getSchemaName(), getTableName()); + XRow xRow = UnoRuntime.queryInterface(XRow.class, xResultSet); + while (xResultSet.next()) + { + String sForeignCatalog = xRow.getString(FKTABLE_CAT); + String sForeignScheme = xRow.getString(FKTABLE_SCHEM); + String sForeignTableName = xRow.getString(FKTABLE_NAME); + CommandName oCommandName = new CommandName(getCommandMetaData(), sForeignCatalog, sForeignScheme, sForeignTableName, false); + aReferencedTableVector.add(oCommandName.getComposedName()); + } + sReferencedTableNames = new String[aReferencedTableVector.size()]; + aReferencedTableVector.toArray(sReferencedTableNames); + } + catch (SQLException e) + { + e.printStackTrace(System.err); + } + return sReferencedTableNames; + } + + private Object getCatalogName(CommandName _oCommandName) + { + String sLocCatalog = _oCommandName.getCatalogName(); + if (sLocCatalog.equals(PropertyNames.EMPTY_STRING)) + { + return null; + } + else + { + return sLocCatalog; + } + } + + public String[][] getImportedKeyColumns(String _sreferencedtablename) + { + String[][] sKeyColumnNames = new String[][] + { + }; + try + { + CommandName oLocCommandName = new CommandName(super.getCommandMetaData(), _sreferencedtablename); + XResultSet xResultSet = super.getCommandMetaData().xDBMetaData.getImportedKeys(getCatalogName(oLocCommandName), oLocCommandName.getSchemaName(), oLocCommandName.getTableName()); + XRow xRow = UnoRuntime.queryInterface(XRow.class, xResultSet); + boolean bleaveLoop = false; + ArrayList<String> aMasterFieldNamesVector = new ArrayList<String>(); + ArrayList<String> aSlaveFieldNamesVector = new ArrayList<String>(); + while (xResultSet.next() && !bleaveLoop) + { + String sPrimaryCatalog = null; + String sPrimarySchema = null; + if (super.getCommandMetaData().xDBMetaData.supportsCatalogsInDataManipulation()) + { + sPrimaryCatalog = xRow.getString(PKTABLE_CAT); + } + if (super.getCommandMetaData().xDBMetaData.supportsSchemasInDataManipulation()) + { + sPrimarySchema = xRow.getString(PKTABLE_SCHEM); + } + String sPrimaryTableName = xRow.getString(PKTABLE_NAME); + String sPrimaryColumnName = xRow.getString(PKCOLUMN_NAME); + String sForeignColumnName = xRow.getString(FKCOLUMN_NAME); + if (JavaTools.isSame(getTableName(), sPrimaryTableName)) + { + if (sPrimarySchema == null || JavaTools.isSame(getSchemaName(), sPrimarySchema)) + { + if (JavaTools.isSame(getCatalogName(), sPrimaryCatalog)) + { + aSlaveFieldNamesVector.add(sForeignColumnName); + aMasterFieldNamesVector.add(sPrimaryColumnName); + bleaveLoop = true; //Only one relation may exist between two tables... + } + } + + } + } + sKeyColumnNames = new String[2][aMasterFieldNamesVector.size()]; + sKeyColumnNames[0] = new String[aSlaveFieldNamesVector.size()]; + sKeyColumnNames[1] = new String[aMasterFieldNamesVector.size()]; + aSlaveFieldNamesVector.toArray(sKeyColumnNames[0]); + aMasterFieldNamesVector.toArray(sKeyColumnNames[1]); + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + return sKeyColumnNames; + } +} diff --git a/wizards/com/sun/star/wizards/db/SQLQueryComposer.java b/wizards/com/sun/star/wizards/db/SQLQueryComposer.java new file mode 100644 index 000000000..17bc953af --- /dev/null +++ b/wizards/com/sun/star/wizards/db/SQLQueryComposer.java @@ -0,0 +1,436 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.beans.*; +import com.sun.star.container.XIndexAccess; +import com.sun.star.sdb.XSingleSelectQueryComposer; +import com.sun.star.sdb.XSingleSelectQueryAnalyzer; +import com.sun.star.ui.dialogs.XExecutableDialog; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.sdbc.SQLException; +import com.sun.star.lang.XInitialization; +import com.sun.star.awt.XWindow; +import com.sun.star.sdb.SQLFilterOperator; + +import com.sun.star.wizards.common.*; +import java.util.ArrayList; + +public class SQLQueryComposer +{ + + private QueryMetaData CurDBMetaData; + public XSingleSelectQueryAnalyzer m_xQueryAnalyzer; + private ArrayList<CommandName> composedCommandNames = new ArrayList<CommandName>(1); + private XSingleSelectQueryComposer m_queryComposer; + private XMultiServiceFactory xMSF; + private boolean bincludeGrouping = true; + + public SQLQueryComposer(QueryMetaData _CurDBMetaData) + { + try + { + setDBMetaData(_CurDBMetaData); + xMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, CurDBMetaData.DBConnection); + final Object oQueryComposer = xMSF.createInstance("com.sun.star.sdb.SingleSelectQueryComposer"); + m_xQueryAnalyzer = UnoRuntime.queryInterface(XSingleSelectQueryAnalyzer.class, oQueryComposer); + m_queryComposer = UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, m_xQueryAnalyzer); + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + } + } + + private boolean addtoSelectClause(String DisplayFieldName) throws SQLException + { + return !(bincludeGrouping && CurDBMetaData.xDBMetaData.supportsGroupByUnrelated() && CurDBMetaData.GroupFieldNames != null && JavaTools.FieldInList(CurDBMetaData.GroupFieldNames, DisplayFieldName) > -1); + } + + public String getSelectClause(boolean _baddAliasFieldNames) throws SQLException + { + // getFromClause() must be called first to populate composedCommandNames, + // but it's idempotent, so let's call it now in case the caller didn't already: + getFromClause(); + + String sSelectBaseClause = "SELECT "; + StringBuilder sb = new StringBuilder(sSelectBaseClause); + for (int i = 0; i < CurDBMetaData.FieldColumns.length; i++) + { + if (addtoSelectClause(CurDBMetaData.FieldColumns[i].getDisplayFieldName())) + { + int iAggregate = CurDBMetaData.getAggregateIndex(CurDBMetaData.FieldColumns[i].getDisplayFieldName()); + if (iAggregate > -1) + { + sb.append(CurDBMetaData.AggregateFieldNames[iAggregate][1]).append("(").append(getComposedAliasDisplayName(CurDBMetaData.AggregateFieldNames[iAggregate][0])).append(")"); + if (_baddAliasFieldNames) + { + sb.append(getAliasFieldNameClause(CurDBMetaData.AggregateFieldNames[iAggregate][0])); + } + } + else + { + sb.append(getComposedAliasDisplayName(CurDBMetaData.FieldColumns[i].getDisplayFieldName())); + if (_baddAliasFieldNames) + { + sb.append(getAliasFieldNameClause(CurDBMetaData.FieldColumns[i].getDisplayFieldName())); + } + } + sb.append(", "); + } + } + String sSelectClause = sb.toString(); + // TODO: little bit unhandy version of remove the append 'comma' at the end + if (sSelectClause.equals(sSelectBaseClause)) + { + sSelectClause = sSelectClause.substring(0, sSelectClause.length() - 1); + } + else + { + sSelectClause = sSelectClause.substring(0, sSelectClause.length() - 2); + } + return sSelectClause; + } + + private String getAliasFieldNameClause(String _FieldName) + { + String FieldTitle = CurDBMetaData.getFieldTitle(_FieldName); + if (!FieldTitle.equals(_FieldName)) + { + return " AS " + CommandName.quoteName(FieldTitle, CurDBMetaData.getIdentifierQuote()); + } + else + { + return ""; + } + } + + + + public void prependSortingCriteria() throws SQLException + { + prependSortingCriteria(false); + } + + private void prependSortingCriteria(boolean _baddAliasFieldNames) throws SQLException + { + XIndexAccess xColumnIndexAccess = m_xQueryAnalyzer.getOrderColumns(); + m_queryComposer.setOrder(""); + for (int i = 0; i < CurDBMetaData.getSortFieldNames().length; i++) + { + appendSortingCriterion(i, _baddAliasFieldNames); + } + for (int i = 0; i < xColumnIndexAccess.getCount(); i++) + { + try + { + XPropertySet xColumnPropertySet = UnoRuntime.queryInterface(XPropertySet.class, xColumnIndexAccess.getByIndex(i)); + String sName = (String) xColumnPropertySet.getPropertyValue(PropertyNames.PROPERTY_NAME); + if (JavaTools.FieldInTable(CurDBMetaData.getSortFieldNames(), sName) == -1) + { + boolean bascend = AnyConverter.toBoolean(xColumnPropertySet.getPropertyValue("IsAscending")); + m_queryComposer.appendOrderByColumn(xColumnPropertySet, bascend); + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + } + } + + private void appendSortingCriterion(int _SortIndex, boolean _baddAliasFieldNames) throws SQLException + { + String sSortValue = CurDBMetaData.getSortFieldNames()[_SortIndex][0]; + XPropertySet xColumn = CurDBMetaData.getColumnObjectByFieldName(sSortValue, _baddAliasFieldNames); + + String sSort = "ASC"; + if(CurDBMetaData.getSortFieldNames()[_SortIndex].length > 1) + { + sSort = CurDBMetaData.getSortFieldNames()[_SortIndex][1]; + } + boolean bascend = !(sSort.equals("DESC")); + m_queryComposer.appendOrderByColumn(xColumn, bascend); + } + + private void appendSortingcriteria(boolean _baddAliasFieldNames) throws SQLException + { + m_queryComposer.setOrder(""); + for (int i = 0; i < CurDBMetaData.getSortFieldNames().length; i++) + { + String sSortValue = CurDBMetaData.getSortFieldNames()[i][0]; + int iAggregate = CurDBMetaData.getAggregateIndex(sSortValue); + if (iAggregate > -1) + { + String sOrder = m_xQueryAnalyzer.getOrder(); + if (sOrder.length() > 0) + { + sOrder += ", "; + } + sOrder += CurDBMetaData.AggregateFieldNames[iAggregate][1] + "(" + getComposedAliasDisplayName(CurDBMetaData.AggregateFieldNames[iAggregate][0]) + ")"; + sOrder += " " + CurDBMetaData.getSortFieldNames()[i][1]; + m_queryComposer.setOrder(sOrder); + } + else + { + appendSortingCriterion(i, _baddAliasFieldNames); + } + } + } + + private void appendGroupByColumns(boolean _baddAliasFieldNames) throws SQLException + { + for (int i = 0; i < CurDBMetaData.GroupFieldNames.length; i++) + { + XPropertySet xColumn = CurDBMetaData.getColumnObjectByFieldName(CurDBMetaData.GroupFieldNames[i], _baddAliasFieldNames); + m_queryComposer.appendGroupByColumn(xColumn); + } + } + + private void setDBMetaData(QueryMetaData _oDBMetaData) + { + this.CurDBMetaData = _oDBMetaData; + updateComposedCommandNames(); + } + + private PropertyValue[][] replaceConditionsByAlias(PropertyValue _filterconditions[][]) + { + for (int n = 0; n < _filterconditions.length; n++) + { + for (int m = 0; m < _filterconditions[n].length; m++) + { + final String aliasName = getComposedAliasFieldName(_filterconditions[n][m].Name); + _filterconditions[n][m].Name = aliasName; + } + } + return _filterconditions; + } + + public String getQuery() + { + return m_xQueryAnalyzer.getQuery(); + } + + private void updateComposedCommandNames() + { + composedCommandNames.clear(); + String[] sCommandNames = CurDBMetaData.getIncludedCommandNames(); + for (int i = 0; i < sCommandNames.length; i++) + { + CommandName curCommandName = new CommandName(CurDBMetaData, sCommandNames[i]); + curCommandName.setAliasName(getuniqueAliasName(curCommandName.getTableName())); + composedCommandNames.add(curCommandName); + } + } + + public StringBuilder getFromClause() throws SQLException + { + StringBuilder sFromClause = new StringBuilder("FROM"); + String[] sCommandNames = CurDBMetaData.getIncludedCommandNames(); + for (int i = 0; i < sCommandNames.length; i++) + { + CommandName curCommandName = getComposedCommandByDisplayName(sCommandNames[i]); + if (curCommandName == null) { + throw new SQLException("Error: CommandName unavailable"); + } + sFromClause.append(" ").append(curCommandName.getComposedName()).append(" ").append(quoteName(curCommandName.getAliasName())); + if (i < sCommandNames.length - 1) + { + sFromClause.append(", "); + } + } + return sFromClause; + } + + public boolean setQueryCommand(XWindow _xParentWindow, boolean _bincludeGrouping, boolean _baddAliasFieldNames) + { + return setQueryCommand(_xParentWindow, _bincludeGrouping, _baddAliasFieldNames, true); + } + + private boolean setQueryCommand(XWindow _xParentWindow, boolean _bincludeGrouping, boolean _baddAliasFieldNames, boolean addQuery) + { + return setQueryCommand(_xParentWindow, _bincludeGrouping, _baddAliasFieldNames, addQuery, false); + } + + private boolean setQueryCommand(XWindow _xParentWindow, boolean _bincludeGrouping, boolean _baddAliasFieldNames, boolean addQuery, boolean prependSortingCriteria) + { + try + { + bincludeGrouping = _bincludeGrouping; + if (addQuery) + { + StringBuilder fromClause = getFromClause(); + String sSelectClause = getSelectClause(_baddAliasFieldNames); + StringBuilder queryclause = new StringBuilder(sSelectClause).append(" ").append(fromClause); + m_xQueryAnalyzer.setQuery(queryclause.toString()); + if (CurDBMetaData.getFilterConditions() != null && CurDBMetaData.getFilterConditions().length > 0) + { + CurDBMetaData.setFilterConditions(replaceConditionsByAlias(CurDBMetaData.getFilterConditions())); + m_queryComposer.setStructuredFilter(CurDBMetaData.getFilterConditions()); + } + } + if (_bincludeGrouping) + { + appendGroupByColumns(_baddAliasFieldNames); + if (CurDBMetaData.GroupByFilterConditions.length > 0) + { + m_queryComposer.setStructuredHavingClause(CurDBMetaData.GroupByFilterConditions); + } + } + if (prependSortingCriteria) + { + prependSortingCriteria(_baddAliasFieldNames); + } + else + { + appendSortingcriteria(_baddAliasFieldNames); + } + + return true; + } + catch (Exception exception) + { + exception.printStackTrace(System.err); + displaySQLErrorDialog(exception, _xParentWindow); + return false; + } + } + + private String getComposedAliasDisplayName(String _fieldname) + { + FieldColumn CurFieldColumn = CurDBMetaData.getFieldColumnByDisplayName(_fieldname); + final String curCommandName = CurFieldColumn.getCommandName(); + final String curFieldName = CurFieldColumn.getFieldName(); + CommandName curComposedCommandName = getComposedCommandByDisplayName(curCommandName); + if (curComposedCommandName == null) + { + //return _fieldname; + if ( curCommandName.length() > 0 ) + return quoteName(curCommandName) + "." + quoteName(curFieldName); + else + return quoteName(curFieldName); + } + String curAliasName = curComposedCommandName.getAliasName(); + return quoteName(curAliasName) + "." + quoteName(curFieldName); + } + + private String getComposedAliasFieldName(String _fieldname) + { + FieldColumn CurFieldColumn = CurDBMetaData.getFieldColumnByFieldName(_fieldname); + final String curCommandName = CurFieldColumn.getCommandName(); + final String curFieldName = CurFieldColumn.getFieldName(); + CommandName curComposedCommandName = getComposedCommandByDisplayName(curCommandName); + if (curComposedCommandName == null) + { + //return _fieldname; + if ( curCommandName.length() > 0 ) + return quoteName(curCommandName) + "." + quoteName(curFieldName); + else + return quoteName(curFieldName); + } + String curAliasName = curComposedCommandName.getAliasName(); + return quoteName(curAliasName) + "." + quoteName(curFieldName); + } + + private CommandName getComposedCommandByAliasName(String _AliasName) + { + if (composedCommandNames != null) + { + for (CommandName commandName : composedCommandNames) + { + if (commandName.getAliasName().equals(_AliasName)) + { + return commandName; + } + } + } + return null; + } + + private CommandName getComposedCommandByDisplayName(String _DisplayName) + { + if (composedCommandNames != null) + { + for (CommandName commandName : composedCommandNames) + { + if (commandName.getDisplayName().equals(_DisplayName)) + { + return commandName; + } + } + } + return null; + } + + private String getuniqueAliasName(String _TableName) + { + int a = 0; + String AliasName = ""; + boolean bAliasNameexists = true; + String locAliasName = _TableName; + while (bAliasNameexists) + { + bAliasNameexists = (getComposedCommandByAliasName(locAliasName) != null); + if (bAliasNameexists) + { + a++; + locAliasName = _TableName + "_" + a; + } + else + { + AliasName = locAliasName; + } + } + return AliasName; + } + + private String quoteName(String _sname) + { + return CommandName.quoteName(_sname, CurDBMetaData.getIdentifierQuote()); + } + + private void displaySQLErrorDialog(Exception _exception, XWindow _xParentWindow) + { + try + { + Object oErrorDialog = CurDBMetaData.xMSF.createInstance("com.sun.star.sdb.ErrorMessageDialog"); + XInitialization xInitialize = UnoRuntime.queryInterface(XInitialization.class, oErrorDialog); + XExecutableDialog xExecute = UnoRuntime.queryInterface(XExecutableDialog.class, oErrorDialog); + PropertyValue[] rDispatchArguments = new PropertyValue[3]; + rDispatchArguments[0] = Properties.createProperty(PropertyNames.PROPERTY_TITLE, Configuration.getProductName(CurDBMetaData.xMSF) + " Base"); + rDispatchArguments[1] = Properties.createProperty("ParentWindow", _xParentWindow); + rDispatchArguments[2] = Properties.createProperty("SQLException", _exception); + xInitialize.initialize(rDispatchArguments); + xExecute.execute(); + //TODO dispose??? + } + catch (Exception typeexception) + { + typeexception.printStackTrace(System.err); + } + } + + public XSingleSelectQueryComposer getQueryComposer() + { + return m_queryComposer; + } +} diff --git a/wizards/com/sun/star/wizards/db/TableDescriptor.java b/wizards/com/sun/star/wizards/db/TableDescriptor.java new file mode 100644 index 000000000..fca261989 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/TableDescriptor.java @@ -0,0 +1,809 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import java.util.ArrayList; + +import com.sun.star.awt.VclWindowPeerAttribute; +import com.sun.star.awt.XWindow; +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.ContainerEvent; +import com.sun.star.container.XContainer; +import com.sun.star.container.XContainerListener; +import com.sun.star.container.XIndexAccess; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.EventObject; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbcx.KeyType; +import com.sun.star.sdbcx.XAppend; +import com.sun.star.sdbcx.XColumnsSupplier; +import com.sun.star.sdbcx.XDataDescriptorFactory; +import com.sun.star.sdbcx.XDrop; +import com.sun.star.sdbcx.XKeysSupplier; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.wizards.common.Desktop; +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.wizards.common.Properties; +import com.sun.star.wizards.common.PropertyNames; + +public class TableDescriptor extends CommandMetaData implements XContainerListener +{ + + private XDataDescriptorFactory xTableDataDescriptorFactory; + private XPropertySet xPropTableDataDescriptor; + private XNameAccess xNameAccessColumns; + private XIndexAccess xIndexAccessKeys; + private XDataDescriptorFactory xColumnDataDescriptorFactory; + private XContainer xTableContainer; + private XAppend xTableAppend; + private XDrop xTableDrop; + private XAppend xKeyAppend; + private XDrop xKeyDrop; + private String[] sTableFilters = null; + private final ArrayList<ColumnDescriptor> columncontainer; + private final ArrayList<XPropertySet> keycolumncontainer; + private CommandName ComposedTableName; + private XAppend xKeyColAppend; + private XColumnsSupplier xKeyColumnSupplier; + private XPropertySet xKey; + private boolean bIDFieldisInserted = false; + private String IDFieldName = PropertyNames.EMPTY_STRING; + private final String sColumnAlreadyExistsMessage; + private final XWindow xWindow; + + public TableDescriptor(XMultiServiceFactory xMSF, XWindow _xWindow, String _sColumnAlreadyExistsMessage) + { + super(xMSF); + columncontainer = new ArrayList<ColumnDescriptor>(); + keycolumncontainer = new ArrayList<XPropertySet>(); + sColumnAlreadyExistsMessage = _sColumnAlreadyExistsMessage; + xWindow = _xWindow; + } + + private static class ColumnDescriptor + { + String Name; + XPropertySet xColPropertySet; + + public ColumnDescriptor(XPropertySet _xColPropertySet, String _Name) + { + Name = _Name; + xColPropertySet = _xColPropertySet; + } + } + + @Override + public boolean getConnection(PropertyValue[] _curPropertyValue) + { + if (super.getConnection(_curPropertyValue)) + { + xTableAppend = UnoRuntime.queryInterface( XAppend.class, getTableNamesAsNameAccess() ); + xTableDrop = UnoRuntime.queryInterface( XDrop.class, getTableNamesAsNameAccess() ); + xTableDataDescriptorFactory = UnoRuntime.queryInterface( XDataDescriptorFactory.class, getTableNamesAsNameAccess() ); + xPropTableDataDescriptor = xTableDataDescriptorFactory.createDataDescriptor(); + XColumnsSupplier xColumnsSupplier = UnoRuntime.queryInterface( XColumnsSupplier.class, xPropTableDataDescriptor ); + xNameAccessColumns = xColumnsSupplier.getColumns(); + xColumnDataDescriptorFactory = UnoRuntime.queryInterface( XDataDescriptorFactory.class, xNameAccessColumns ); + try + { + createTypeInspector(); + sTableFilters = (String[]) AnyConverter.toArray(getDataSourcePropertySet().getPropertyValue("TableFilter")); + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + return true; + } + else + { + return false; + } + } + + private void removePrimaryKeys() + { + if (keycolumncontainer.size() > 0) + { + for (int i = (keycolumncontainer.size() - 1); i >= 0; i--) + { + keycolumncontainer.remove(i); + } + } + } + + private boolean createPrimaryKeys(String[] _fieldnames, boolean _bAutoincrementation) + { + try + { + XKeysSupplier xKeySupplier = UnoRuntime.queryInterface(XKeysSupplier.class, xPropTableDataDescriptor); + xIndexAccessKeys = xKeySupplier.getKeys(); + XDataDescriptorFactory xKeyFac = UnoRuntime.queryInterface(XDataDescriptorFactory.class, xIndexAccessKeys); + xKeyDrop = UnoRuntime.queryInterface(XDrop.class, xIndexAccessKeys); + xKeyAppend = UnoRuntime.queryInterface(XAppend.class, xKeyFac); + xKey = xKeyFac.createDataDescriptor(); + xKey.setPropertyValue("Type", Integer.valueOf(KeyType.PRIMARY)); + xKeyColumnSupplier = UnoRuntime.queryInterface(XColumnsSupplier.class, xKey); + XDataDescriptorFactory xKeyColFac = UnoRuntime.queryInterface(XDataDescriptorFactory.class, xKeyColumnSupplier.getColumns()); + xKeyColAppend = UnoRuntime.queryInterface(XAppend.class, xKeyColFac); + removePrimaryKeys(); + for (int i = 0; i < _fieldnames.length; i++) + { + XPropertySet xKeyColPropertySet = xKeyColFac.createDataDescriptor(); + xKeyColPropertySet.setPropertyValue(PropertyNames.PROPERTY_NAME, _fieldnames[i]); + keycolumncontainer.add(xKeyColPropertySet); + XPropertySet xColPropertySet = null; + if (hasByName(_fieldnames[i])) + { + xColPropertySet = getByName(_fieldnames[i]); + } + else + { + xColPropertySet = addPrimaryKeyColumn(_fieldnames[i]); + } + xColPropertySet.setPropertyValue("IsNullable", Integer.valueOf(com.sun.star.sdbc.ColumnValue.NO_NULLS)); + if (_bAutoincrementation) + { + int nDataType = oTypeInspector.getAutoIncrementIndex(xColPropertySet); + if (nDataType != TypeInspector.INVALID) + { + if (xColPropertySet.getPropertySetInfo().hasPropertyByName("IsAutoIncrement")) + { + xColPropertySet.setPropertyValue("Type", Integer.valueOf(nDataType)); + xColPropertySet.setPropertyValue("IsAutoIncrement", Boolean.valueOf(_bAutoincrementation)); + } + } + } + modifyColumn(_fieldnames[i], xColPropertySet); + } + return true; + } + catch (UnknownPropertyException e) + { + e.printStackTrace(System.err); + } + catch (PropertyVetoException e) + { + e.printStackTrace(System.err); + } + catch (IllegalArgumentException e) + { + e.printStackTrace(System.err); + } + catch (WrappedTargetException e) + { + e.printStackTrace(System.err); + } + + return false; + } + + private boolean isColumnNameDuplicate(XNameAccess _xColumns, XPropertySet _xToBeAppendedPropertySet) + { + try + { + String sColumnName = AnyConverter.toString(_xToBeAppendedPropertySet.getPropertyValue(PropertyNames.PROPERTY_NAME)); + if (_xColumns.hasByName(sColumnName)) + { + String sMessage = JavaTools.replaceSubString(sColumnAlreadyExistsMessage, sColumnName, "%FIELDNAME"); + showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMessage); + return true; + } + return false; + } + catch (Exception ex) + { + ex.printStackTrace(System.err); + return false; + } + } + + /** + * creates the table under the passed name + * @param _tablename is made unique if necessary + * @return true or false to indicate successful creation or not + */ + public boolean createTable(String _catalogname, String _schemaname, String _tablename) + { + boolean breturn = true; + try + { + XAppend xAppendColumns = UnoRuntime.queryInterface(XAppend.class, xNameAccessColumns); + for (int i = 0; i < columncontainer.size(); i++) + { + XPropertySet xColPropertySet = getByIndex(i); + if (xColPropertySet != null && !isColumnNameDuplicate(xNameAccessColumns, xColPropertySet)) + { + xAppendColumns.appendByDescriptor(xColPropertySet); //xColPropertySet.setPropertyValue("Type", 32423) + } + else + { + breturn = false; + } + } + if (breturn) + { + assignTableProperty(PropertyNames.PROPERTY_NAME, _tablename); + assignTableProperty("CatalogName", _catalogname); + assignTableProperty("SchemaName", _schemaname); + xTableContainer = UnoRuntime.queryInterface(XContainer.class, getTableNamesAsNameAccess()); + xTableContainer.addContainerListener(this); + if (keycolumncontainer.size() > 0) + { + for (int i = 0; i < keycolumncontainer.size(); i++) + { + XPropertySet xKeyColPropertySet = keycolumncontainer.get(i); + if (!isColumnNameDuplicate(xKeyColumnSupplier.getColumns(), xKeyColPropertySet)) + { + xKeyColAppend.appendByDescriptor(xKeyColPropertySet); + } + else + { + breturn = false; + } + } + if (breturn) + { + xKeyAppend.appendByDescriptor(xKey); + } + } + if (breturn) + { + // TODO: LLA: describe what is he doing here. + xTableAppend.appendByDescriptor(xPropTableDataDescriptor); + } + } + } + catch (SQLException oSQLException) + { + super.callSQLErrorMessageDialog(oSQLException, xWindow); + breturn = false; + } + catch (Exception e) + { + e.printStackTrace(System.err); + breturn = false; + } + if (!breturn) + { + removeAllColumnsFromDescriptor(_tablename); + this.removePrimaryKeys(); + } + return breturn; + } + + private boolean removeAllColumnsFromDescriptor(String _tablename) + { + try + { + xPropTableDataDescriptor.setPropertyValue(PropertyNames.PROPERTY_NAME, PropertyNames.EMPTY_STRING); + if ((xKeyDrop != null) && (xIndexAccessKeys != null)) + { + int icount = xIndexAccessKeys.getCount(); + if (icount > 0) + { + for (int i = xIndexAccessKeys.getCount() - 1; i >= 0; i--) + { + xKeyDrop.dropByIndex(i); + } + } + } + XDrop xColumnDrop = UnoRuntime.queryInterface(XDrop.class, xNameAccessColumns); + for (int i = xNameAccessColumns.getElementNames().length - 1; i >= 0; i--) + { + xColumnDrop.dropByIndex(i); + } + if (xTableDrop != null) + { + if (getTableNamesAsNameAccess().hasByName(_tablename)) + { + xTableDrop.dropByName(_tablename); + } + } + if (bIDFieldisInserted) + { + this.dropColumnbyName(this.IDFieldName); + bIDFieldisInserted = false; + } + return false; + } + catch (SQLException oSQLException) + { + super.callSQLErrorMessageDialog(oSQLException, xWindow); + } + catch (Exception e1) + { + e1.printStackTrace(System.err); + } + return false; + } + + public boolean createTable(String _catalogname, String _schemaname, String _tablename, String[] _keycolumnnames, boolean _bAutoincrementation) + { + if (createPrimaryKeys(_keycolumnnames, _bAutoincrementation)) + { + return createTable(_catalogname, _schemaname, _tablename); + } + return false; + } + + private void assignTableProperty(String _spropname, String _svalue) + { + if (_svalue != null && !_svalue.equals(PropertyNames.EMPTY_STRING)) + { + try + { + xPropTableDataDescriptor.setPropertyValue(_spropname, _svalue); + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + } + } + + public boolean modifyColumnName(String _soldname, String _snewname) + { + try + { + return modifyColumn(_soldname, PropertyNames.PROPERTY_NAME, _snewname); + } + catch (Exception e) + { + e.printStackTrace(System.err); + showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, e.getMessage()); + return false; + } + } + + private boolean modifyColumn(String _sname, String _spropname, Object _oValue) + { + try + { + if (this.columncontainer.size() > 0) + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = columncontainer.get(i); + if (oColumnDescriptor.Name.equals(_sname)) + { + oColumnDescriptor.xColPropertySet.setPropertyValue(_spropname, _oValue); + if (_spropname.equals(PropertyNames.PROPERTY_NAME)) + { + oColumnDescriptor.Name = (String) _oValue; + } + columncontainer.remove(i); + columncontainer.add(i, oColumnDescriptor); + return true; + } + } + } + } + catch (UnknownPropertyException e) + { + e.printStackTrace(System.err); + } + catch (PropertyVetoException e) + { + e.printStackTrace(System.err); + } + catch (IllegalArgumentException e) + { + e.printStackTrace(System.err); + } + catch (WrappedTargetException e) + { + e.printStackTrace(System.err); + } + return false; + } + + public boolean modifyColumn(String _sname, XPropertySet _xColPropertySet) + { + try + { + if (this.columncontainer.size() > 0) + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = columncontainer.get(i); + if (oColumnDescriptor.Name.equals(_sname)) + { + oColumnDescriptor.xColPropertySet = _xColPropertySet; + oColumnDescriptor.Name = (String) _xColPropertySet.getPropertyValue(PropertyNames.PROPERTY_NAME); + columncontainer.remove(i); + columncontainer.add(i, oColumnDescriptor); + return true; + } + } + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + return false; + } + + public void dropColumnbyName(String _sname) + { + try + { + if (columncontainer.size() > 0) + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = columncontainer.get(i); + if (oColumnDescriptor != null) + { + if (oColumnDescriptor.Name.equals(_sname)) + { + columncontainer.remove(i); + } + } + } + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + } + + private String[] getColumnNames() + { + if (columncontainer.size() > 0) + { + try + { + String[] fieldnames = new String[columncontainer.size()]; + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = columncontainer.get(i); + fieldnames[i] = oColumnDescriptor.Name; + } + return fieldnames; + } + catch (RuntimeException e) + { + e.printStackTrace(System.err); + } + } + return new String[] + { + }; + } + + private boolean hasByName(String _fieldname) + { + try + { + if (columncontainer.size() > 0) + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = columncontainer.get(i); + if (oColumnDescriptor.Name.equals(_fieldname)) + { + return true; + } + } + } + } + catch (RuntimeException e) + { + e.printStackTrace(System.err); + } + return false; + } + + private ColumnDescriptor getColumnDescriptorByName(String _fieldname) + { + try + { + if (this.columncontainer.size() > 0) + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = columncontainer.get(i); + if (oColumnDescriptor.Name.equals(_fieldname)) + { + return oColumnDescriptor; + } + } + } + } + catch (RuntimeException e) + { + e.printStackTrace(System.err); + } + return null; + } + + public XPropertySet getByName(String _fieldname) + { + ColumnDescriptor oColumnDescriptor = getColumnDescriptorByName(_fieldname); + if (oColumnDescriptor != null) + { + return oColumnDescriptor.xColPropertySet; + } + else + { + return null; + } + } + + private XPropertySet getByIndex(int _index) + { + try + { + if (columncontainer.size() > _index) + { + ColumnDescriptor oColumnDescriptor = columncontainer.get(_index); + return oColumnDescriptor.xColPropertySet; + } + } + catch (RuntimeException e) + { + e.printStackTrace(System.err); + } + return null; + } + + public XPropertySet clonePropertySet(String _snewname, XPropertySet _xnewPropertySet) + { + XPropertySet xRetPropertySet = xColumnDataDescriptorFactory.createDataDescriptor(); + try + { + if (hasByName(_snewname)) + { + Object oColumn = getByName(_snewname); + XPropertySet xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, oColumn); + Property[] aColProperties = xPropertySet.getPropertySetInfo().getProperties(); + for (int i = 0; i < aColProperties.length; i++) + { + String sPropName = aColProperties[i].Name; + Object oColValue = _xnewPropertySet.getPropertyValue(sPropName); + xRetPropertySet.setPropertyValue(sPropName, oColValue); + } + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + return xRetPropertySet; + } + + public boolean addColumn(PropertyValue[] _aNewPropertyValues) + { + try + { + String sname = (String) Properties.getPropertyValue(_aNewPropertyValues, PropertyNames.PROPERTY_NAME); + if (!hasByName(sname)) + { + ColumnPropertySet oPropertySet = new ColumnPropertySet(oTypeInspector, xColumnDataDescriptorFactory.createDataDescriptor()); + oPropertySet.assignPropertyValues(_aNewPropertyValues, true); + ColumnDescriptor oColumnDescriptor = new ColumnDescriptor(oPropertySet.xPropertySet, sname); + this.columncontainer.add(oColumnDescriptor); + return true; + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + return false; + } + + public boolean moveColumn(int _nOldIndex, int _nNewIndex) + { + try + { + ColumnDescriptor oColumnDescriptor = this.columncontainer.get(_nOldIndex); + this.columncontainer.remove(_nOldIndex); + columncontainer.add(_nNewIndex, oColumnDescriptor); + return true; + } + catch (Exception e) + { + e.printStackTrace(System.err); + return false; + } + } + + + + private XPropertySet addPrimaryKeyColumn(String _columnname) + { + try + { + if (!hasByName(_columnname)) + { + try + { + XPropertySet xColPropertySet = xColumnDataDescriptorFactory.createDataDescriptor(); + IDFieldName = Desktop.getUniqueName(getColumnNames(), _columnname, PropertyNames.EMPTY_STRING); + xColPropertySet.setPropertyValue(PropertyNames.PROPERTY_NAME, IDFieldName); + + int nDataType = oTypeInspector.convertDataType(com.sun.star.sdbc.DataType.INTEGER); + xColPropertySet.setPropertyValue("Type", Integer.valueOf(nDataType)); + xColPropertySet.setPropertyValue("TypeName", oTypeInspector.getDefaultTypeName(nDataType, null)); + ColumnDescriptor oColumnDescriptor = new ColumnDescriptor(xColPropertySet, IDFieldName); + this.columncontainer.add(0, oColumnDescriptor); + this.bIDFieldisInserted = true; + return xColPropertySet; + } + catch (RuntimeException e1) + { + e1.printStackTrace(System.err); + } + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + return null; + } + + public String[] getNonBinaryFieldNames() + { + ArrayList<String> NonBinaryFieldNameVector = new ArrayList<String>(); + try + { + for (int i = 0; i < columncontainer.size(); i++) + { + ColumnDescriptor oColumnDescriptor = columncontainer.get(i); + XPropertySet xColPropertySet = getByName(oColumnDescriptor.Name); + int itype; + try + { + itype = AnyConverter.toInt(xColPropertySet.getPropertyValue("Type")); + if (!isBinaryDataType(itype)) + { + NonBinaryFieldNameVector.add(oColumnDescriptor.Name); + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + } + } + catch (RuntimeException e) + { + e.printStackTrace(System.err); + } + String[] sbinaryfieldnames = new String[NonBinaryFieldNameVector.size()]; + NonBinaryFieldNameVector.toArray(sbinaryfieldnames); + return sbinaryfieldnames; + } + + public String getComposedTableName(String _scatalogname, String _sschemaname, String _stablename) + { + ComposedTableName = new CommandName(this, _scatalogname, _sschemaname, _stablename, false); + return ComposedTableName.getComposedName(); + } + + public String getComposedTableName() + { + if (ComposedTableName != null) + { + return this.ComposedTableName.getComposedName(); + } + else + { + return null; + } + } + + /* (non-Javadoc) + * @see com.sun.star.container.XContainerListener#elementInserted(com.sun.star.container.ContainerEvent) + */ + public void elementInserted(ContainerEvent arg0) + { + try + { + XPropertySet xTablePropertySet = UnoRuntime.queryInterface(XPropertySet.class, arg0.Element); + String stablename = AnyConverter.toString(xTablePropertySet.getPropertyValue(PropertyNames.PROPERTY_NAME)); + String sschemaname = AnyConverter.toString(xPropTableDataDescriptor.getPropertyValue("SchemaName")); + String scatalogname = AnyConverter.toString(xPropTableDataDescriptor.getPropertyValue("CatalogName")); + ComposedTableName = new CommandName(this, scatalogname, sschemaname, stablename, false); + appendTableNameToFilter(ComposedTableName.getComposedName()); + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + } + + /* (non-Javadoc) + * @see com.sun.star.container.XContainerListener#elementRemoved(com.sun.star.container.ContainerEvent) + */ + public void elementRemoved(ContainerEvent arg0) + { + } + + /* (non-Javadoc) + * @see com.sun.star.container.XContainerListener#elementReplaced(com.sun.star.container.ContainerEvent) + */ + public void elementReplaced(ContainerEvent arg0) + { + } + + /* (non-Javadoc) + * @see com.sun.star.lang.XEventListener#disposing(com.sun.star.lang.EventObject) + */ + public void disposing(EventObject arg0) + { + } + + private boolean appendTableNameToFilter(String _scomposedtablename) + { + boolean bhastoinsert = true; + for (int i = 0; i < sTableFilters.length; i++) + { + if (sTableFilters[i].compareTo("%") > -1) + { + if (sTableFilters[i].endsWith("." + _scomposedtablename)) + { + bhastoinsert = false; + } + else if (sTableFilters[i].length() == 1) + { + bhastoinsert = false; + } + } + else if (sTableFilters[i].equals(_scomposedtablename)) + { + bhastoinsert = false; + } + if (!bhastoinsert) + { + break; + } + } + if (bhastoinsert) + { + String[] sNewTableFilters = new String[sTableFilters.length + 1]; + System.arraycopy(sTableFilters, 0, sNewTableFilters, 0, sTableFilters.length); + sNewTableFilters[sTableFilters.length] = _scomposedtablename; + sTableFilters = sNewTableFilters; + try + { + getDataSourcePropertySet().setPropertyValue("TableFilter", sTableFilters); + } + catch (Exception e) + { + e.printStackTrace(System.err); + bhastoinsert = false; + } + } + return bhastoinsert; + } +} + diff --git a/wizards/com/sun/star/wizards/db/TypeInspector.java b/wizards/com/sun/star/wizards/db/TypeInspector.java new file mode 100644 index 000000000..831378e96 --- /dev/null +++ b/wizards/com/sun/star/wizards/db/TypeInspector.java @@ -0,0 +1,367 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 . + */ +package com.sun.star.wizards.db; + +import java.util.ArrayList; + +import com.sun.star.beans.XPropertySet; +import com.sun.star.sdbc.ColumnValue; +import com.sun.star.sdbc.DataType; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XResultSet; +import com.sun.star.sdbc.XRow; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.wizards.common.JavaTools; +import com.sun.star.wizards.common.PropertyNames; + +public class TypeInspector +{ + + private String[] sDataTypeNames; + private int[] nDataTypeInfos; + private int[] nPrecisionInfos; + private int[] nNullableInfos; + private boolean[] bisAutoIncrementableInfos; + private int[] nMinScaleInfos; + private int[] nMaxScaleInfos; + private final int[] nNumericFallBackList = new int[] + { + DataType.INTEGER, DataType.FLOAT, DataType.REAL, DataType.DOUBLE, DataType.NUMERIC, DataType.DECIMAL + }; + static final int INVALID = 999999; + + public TypeInspector(XResultSet _xResultSet) + { + try + { + ArrayList<String> aTypeNameVector = new ArrayList<String>(); + ArrayList<Integer> aTypeVector = new ArrayList<Integer>(); + ArrayList<Integer> aNullableVector = new ArrayList<Integer>(); + ArrayList<Boolean> aAutoIncrementVector = new ArrayList<Boolean>(); + ArrayList<Integer> aPrecisionVector = new ArrayList<Integer>(); + ArrayList<Integer> aMinScaleVector = new ArrayList<Integer>(); + ArrayList<Integer> aMaxScaleVector = new ArrayList<Integer>(); + XRow xRow = UnoRuntime.queryInterface(XRow.class, _xResultSet); + while (_xResultSet.next()) + { + aTypeNameVector.add(xRow.getString(1)); + aTypeVector.add(Integer.valueOf(xRow.getShort(2))); + aPrecisionVector.add(Integer.valueOf(xRow.getInt(3))); + aNullableVector.add(Integer.valueOf(xRow.getShort(7))); + aAutoIncrementVector.add(Boolean.valueOf(xRow.getBoolean(12))); + aMinScaleVector.add(Integer.valueOf(xRow.getShort(14))); + aMaxScaleVector.add(Integer.valueOf(xRow.getShort(15))); + + } + sDataTypeNames = new String[aTypeNameVector.size()]; + aTypeNameVector.toArray(sDataTypeNames); + nDataTypeInfos = JavaTools.IntegerTointList(aTypeVector); + nNullableInfos = JavaTools.IntegerTointList(aNullableVector); + bisAutoIncrementableInfos = JavaTools.BooleanTobooleanList(aAutoIncrementVector); + nPrecisionInfos = JavaTools.IntegerTointList(aPrecisionVector); + nMinScaleInfos = JavaTools.IntegerTointList(aMinScaleVector); + nMaxScaleInfos = JavaTools.IntegerTointList(aMaxScaleVector); + } + catch (SQLException e) + { + e.printStackTrace(System.err); + } + } + + public int getScale(XPropertySet _xColPropertySet) + { + try + { + int i = getDataTypeIndex(_xColPropertySet, false); + int nScale = AnyConverter.toInt(_xColPropertySet.getPropertyValue("Scale")); + if (i == -1) + { + return nScale; + } + if (nScale > nMaxScaleInfos[i]) + { + return nMaxScaleInfos[i]; + } + else if (nScale < nMinScaleInfos[i]) + { + return nMinScaleInfos[i]; + } + else + { + return nScale; + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + return 0; + } + } + + public int getNullability(XPropertySet _xColPropertySet, int _nNullable) + { + int i = getDataTypeIndex(_xColPropertySet, false); + if (i == -1) + { + return ColumnValue.NO_NULLS; + } + if (_nNullable == ColumnValue.NULLABLE) + { + return nNullableInfos[i]; //probably nullability is not allowed + } + return _nNullable; + } + + + + public int isNullable(XPropertySet _xColPropertySet) + { + int i = getDataTypeIndex(_xColPropertySet, false); + if (i > -1) + { + return nNullableInfos[i]; + } + else + { + return ColumnValue.NO_NULLS; + } + } + + private int getDataTypeIndex(XPropertySet _xColPropertySet, boolean _bCheckNumericAttributes) + { + try + { + int nPrecision = -1; + int nScale = -1; + int nDataType = AnyConverter.toInt(_xColPropertySet.getPropertyValue("Type")); + String sTypeName = AnyConverter.toString(_xColPropertySet.getPropertyValue("TypeName")); + if (_bCheckNumericAttributes) + { + nPrecision = AnyConverter.toInt(_xColPropertySet.getPropertyValue("Precision")); + nScale = AnyConverter.toInt(_xColPropertySet.getPropertyValue("Scale")); + } + boolean bleaveloop = false; + int startindex = 0; + while (!bleaveloop) + { + int i = JavaTools.FieldInIntTable(nDataTypeInfos, nDataType, startindex); + startindex = i + 1; + bleaveloop = (i < 0); + if (!bleaveloop && sTypeName.equals(sDataTypeNames[i])) + { + if (_bCheckNumericAttributes) + { + if (nPrecision <= nPrecisionInfos[i] && (nScale >= nMinScaleInfos[i]) && (nScale <= nMinScaleInfos[i]) ) + { + return i; + } + } + else + { + return i; + } + } + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + return -1; + } + + private boolean supportsDataType(int _curDataType) + { + return (JavaTools.FieldInIntTable(nDataTypeInfos, _curDataType) > -1); + } + + private int getLastConversionFallbackDataType() + { + if (supportsDataType(DataType.VARCHAR)) + { + return DataType.VARCHAR; + } + else + { + return DataType.LONGVARCHAR; + } + } + + /** + * an empty string is returned when no appropriate Typename can be found + * finds the first TypeName of the passed datatype. + */ + public String getDefaultTypeName(int _curDataType, Integer precision) + { + String ret = PropertyNames.EMPTY_STRING; + for (int i = 0; i < nDataTypeInfos.length; i++) + { + if (nDataTypeInfos[i] == _curDataType) + { + if (precision == null || nPrecisionInfos[i] >= precision.intValue()) + { + ret = sDataTypeNames[i]; // this fits best ! + break; + } + else if (ret.length() == 0) + { + // in case we don't find anything else, we at return a typename + // with the correct class + ret = sDataTypeNames[i]; + } + } + } + return ret; + } + + public int getDataType(String _sTypeName) + { + int i = JavaTools.FieldInList(sDataTypeNames, _sTypeName); + if (i > -1) + { + return nDataTypeInfos[i]; + } + else + { + return getLastConversionFallbackDataType(); + } + } + + public int convertDataType(int _curDataType) + { + int retDataType = _curDataType; + if (!supportsDataType(_curDataType)) + { + switch (_curDataType) + { + case DataType.BIT: + retDataType = convertDataType(DataType.BOOLEAN); + break; + case DataType.BOOLEAN: + retDataType = convertDataType(DataType.BIT); + break; + case DataType.TINYINT: + retDataType = convertDataType(DataType.SMALLINT); + break; + case DataType.SMALLINT: + retDataType = convertDataType(DataType.INTEGER); + break; + case DataType.INTEGER: + retDataType = convertDataType(DataType.FLOAT); + break; + case DataType.FLOAT: + retDataType = convertDataType(DataType.REAL); + break; + case DataType.DATE: + case DataType.TIME: + retDataType = convertDataType(DataType.TIMESTAMP); + break; + case DataType.TIMESTAMP: + case DataType.REAL: + case DataType.BIGINT: + retDataType = convertDataType(DataType.DOUBLE); + break; + case DataType.DOUBLE: + retDataType = convertDataType(DataType.NUMERIC); + break; + case DataType.NUMERIC: + retDataType = convertDataType(DataType.DECIMAL); + break; + case DataType.DECIMAL: + if (supportsDataType(DataType.DOUBLE)) + { + retDataType = convertDataType(DataType.DOUBLE); + } + else if (supportsDataType(DataType.NUMERIC)) + { + retDataType = DataType.NUMERIC; + } + else + { + retDataType = getLastConversionFallbackDataType(); + } + break; + case DataType.VARCHAR: + retDataType = getLastConversionFallbackDataType(); + break; + default: + retDataType = getLastConversionFallbackDataType(); + } + } + return retDataType; + } + + public int getAutoIncrementIndex(XPropertySet _xColPropertySet) + { + try + { + boolean bleaveloop = false; + int startindex = 0; + int curDataType = ((Integer) _xColPropertySet.getPropertyValue("Type")).intValue(); + while (!bleaveloop) + { + int i = JavaTools.FieldInIntTable(nDataTypeInfos, curDataType, startindex); + startindex = i + 1; + bleaveloop = (i == -1); + if (!bleaveloop && bisAutoIncrementableInfos[i]) + { + return nDataTypeInfos[i]; + } + } + } + catch (Exception e) + { + e.printStackTrace(System.err); + } + return INVALID; + + } + + public boolean isAutoIncrementable(XPropertySet _xColPropertySet) + { + return (getAutoIncrementIndex(_xColPropertySet) != INVALID); + } + + /** Do we have a datatype that supports AutoIncrementation? + */ + public boolean isAutoIncrementationSupported() + { + for (int n = 0; n < this.nNumericFallBackList.length; n++) + { + int nDataType = nNumericFallBackList[n]; + boolean bleaveloop = false; + int startindex = 0; + while (!bleaveloop) + { + int i = JavaTools.FieldInIntTable(nDataTypeInfos, nDataType, startindex); + bleaveloop = (i < 0); + if (!bleaveloop) + { + if (this.bisAutoIncrementableInfos[i]) + { + return true; + } + startindex = i + 1; + } + startindex = i + 1; + } + } + return false; + } +} |