diff options
author | Rüdiger Timm <rt@openoffice.org> | 2008-12-09 07:25:38 +0000 |
---|---|---|
committer | Rüdiger Timm <rt@openoffice.org> | 2008-12-09 07:25:38 +0000 |
commit | 568af9ac86c8eee3531ff9cb718aeba240f274be (patch) | |
tree | 710059fbd5080acac11680bc02bf27761346e17b /reportdesign | |
parent | b4e6996966166bf80447fc9eda619b283e8c86ef (diff) |
CWS-TOOLING: integrate CWS dba31d
2008-12-08 16:22:07 +0100 rt r265005 : Remove DOS lineends
2008-12-05 13:56:24 +0100 fs r264906 : #i10000# removed unreachable statement
2008-11-20 11:41:26 +0100 fs r264037 : merged in the fix for #i95865# (it was wrongly committed to CWS dba32a, should have been here)
2008-11-20 11:34:24 +0100 fs r264036 : line ends
2008-11-14 08:44:50 +0100 lla r263665 : #i10000# comparsion between int and uint fixed
2008-11-13 13:31:12 +0100 lla r263641 : #i10000# build problem fixed
2008-11-13 11:20:01 +0100 lla r263625 : #i96130# hard code name of extension
2008-11-12 11:13:41 +0100 fs r263582 : #i96096# when opening a SRB-report fails due to the missing SRB extension, log this as warning only, and proceed with the migration
2008-11-12 11:11:35 +0100 fs r263581 : #i96096# ContentType handling. Now all contents deliver proper results in XContent::getContentType
2008-11-12 11:10:11 +0100 fs r263580 : #i96096# new ctors taking UNO_QUERY_THROW
2008-11-11 10:10:13 +0100 lla r263546 : CWS-TOOLING: rebase CWS dba31d to trunk@263288 (milestone: DEV300:m35)
2008-11-06 15:55:39 +0100 oj r263393 : #i93452# get field from model fallbackis the name
2008-11-06 15:31:47 +0100 oj r263392 : #i93465# remeber location of floating windows
2008-11-06 13:36:24 +0100 oj r263381 : #i93450# check typemap for null
2008-11-06 13:28:49 +0100 oj r263379 : #i93020# empty column list boxes when new relation should be created
2008-11-06 12:33:53 +0100 oj r263377 : #i93012# set border to default : flat
2008-11-06 12:26:54 +0100 oj r263375 : #i74927# do some less calls for odbc
2008-11-06 09:34:01 +0100 oj r263362 : #i93383# grabFocus in suspend to get allmodified cells
2008-11-03 21:01:39 +0100 oj r263308 : #i86739# check if slash can be valid for tables
2008-11-03 14:40:21 +0100 oj r263287 : #i86739# check if slash can be valid for tables
2008-11-03 14:32:17 +0100 oj r263286 : #i95227# column width
2008-11-03 14:27:26 +0100 oj r263285 : link fwe
2008-11-03 14:24:54 +0100 oj r263284 : #i95235# changed to hold no ref only weak
2008-10-31 11:21:48 +0100 oj r262859 : #i93459# set images add menu entry
2008-10-31 09:06:37 +0100 oj r262851 : #i88629# correct fileopen filter for database odb files
2008-10-30 15:01:04 +0100 oj r262828 : #i95229# set filter at the composer
2008-10-29 15:57:41 +0100 oj r262817 : #i95235# changed to hold no ref only weak
2008-10-29 15:57:19 +0100 oj r262816 : #i95235# changed to hold no ref only weak
2008-10-29 15:57:03 +0100 oj r262815 : #i95235# changed to hold no ref only weak
2008-10-29 15:56:15 +0100 oj r262814 : #i95235# filtermanger changed to hold no ref only weak
2008-10-29 10:32:39 +0100 oj r262773 : #i93474# use correct table name
2008-10-28 13:49:33 +0100 lla r262744 : #i95524# make an Invalidate and refresh on Tables
2008-10-28 10:45:02 +0100 fs r262707 : line ends
2008-10-28 10:34:42 +0100 fs r262706 : #i95522# don't expect the component to live in a TopWindow
2008-10-28 08:30:40 +0100 lla r262696 : #i93176# set preview mode on view
2008-10-28 07:56:57 +0100 oj r262694 : merge cvs svn
2008-10-27 14:13:51 +0100 oj r262673 : #i94129# use dummy data
2008-10-27 12:38:45 +0100 fs r262669 : #i94125# rework ScrollColumns
2008-10-23 15:53:57 +0200 oj r262624 : #i94568# do not load the embeddedobj just copy the storage
2008-10-23 14:39:14 +0200 oj r262622 : #i94129# handle chart correctly
2008-10-22 10:51:19 +0200 lla r262582 : #i94115# problem with left walk chart shape fixed
2008-10-22 07:47:48 +0200 oj r262576 : #i94455# rename now do not use remove insert
2008-10-22 07:47:27 +0200 oj r262575 : #i94455# rename now do not use remove insert
2008-10-21 12:46:26 +0200 lla r262567 : #i93845# extra check if default schema doesn't exists, fix assertion
Diffstat (limited to 'reportdesign')
15 files changed, 3066 insertions, 3010 deletions
diff --git a/reportdesign/java/com/sun/star/report/SDBCReportDataFactory.java b/reportdesign/java/com/sun/star/report/SDBCReportDataFactory.java index 915e4523504a..463bf0a44f11 100644 --- a/reportdesign/java/com/sun/star/report/SDBCReportDataFactory.java +++ b/reportdesign/java/com/sun/star/report/SDBCReportDataFactory.java @@ -1,639 +1,637 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: SDBCReportDataFactory.java,v $ - * $Revision: 1.9.18.1 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.report; - -import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.beans.XPropertySet; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XIndexAccess; -import com.sun.star.lang.IllegalArgumentException; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.sdbc.XConnection; -import com.sun.star.container.XNameAccess; -import com.sun.star.lang.XComponent; -import com.sun.star.lang.XMultiServiceFactory; -import com.sun.star.sdb.CommandType; -import com.sun.star.sdb.XCompletedExecution; -import com.sun.star.sdb.XParametersSupplier; -import com.sun.star.sdb.XQueriesSupplier; -import com.sun.star.sdb.XSingleSelectQueryComposer; -import com.sun.star.sdb.tools.XConnectionTools; -import com.sun.star.sdbc.SQLException; -import com.sun.star.sdbc.XParameters; -import com.sun.star.sdbc.XPreparedStatement; -import com.sun.star.uno.Exception; -import java.util.Map; - -import com.sun.star.sdbc.XRowSet; -import com.sun.star.sdbcx.XColumnsSupplier; -import com.sun.star.sdbcx.XTablesSupplier; -import com.sun.star.task.XInteractionHandler; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import org.jfree.util.Log; - -/** - * Very primitive implementation, just to show how this could be used ... - * - */ -public class SDBCReportDataFactory implements DataSourceFactory -{ - - public static final String COMMAND_TYPE = "command-type"; - public static final String ESCAPE_PROCESSING = "escape-processing"; - public static final String GROUP_EXPRESSIONS = "group-expressions"; - public static final String MASTER_VALUES = "master-values"; - public static final String DETAIL_COLUMNS = "detail-columns"; - public static final String UNO_FILTER = "Filter"; - private static final String APPLY_FILTER = "ApplyFilter"; - private static final String UNO_COMMAND = "Command"; - private static final String UNO_ORDER = "Order"; - private static final String UNO_APPLY_FILTER = "ApplyFilter"; - private static final String UNO_COMMAND_TYPE = "CommandType"; - private final XConnection connection; - private final XComponentContext m_cmpCtx; - private static final int FAILED = 0; - private static final int DONE = 1; - private static final int RETRIEVE_COLUMNS = 2; - private static final int RETRIEVE_OBJECT = 3; - private static final int HANDLE_QUERY = 4; - private static final int HANDLE_TABLE = 5; - private static final int HANDLE_SQL = 6; - - public SDBCReportDataFactory(final XComponentContext cmpCtx, final XConnection connection) - { - this.connection = connection; - m_cmpCtx = cmpCtx; - } - - public DataSource queryData(final String command, final Map parameters) throws DataSourceException - { - try - { - if (command == null) - { - return new SDBCReportData(null); - } - int commandType = CommandType.COMMAND; - final String commandTypeValue = (String) parameters.get(COMMAND_TYPE); - if (commandTypeValue != null) - { - if (commandTypeValue.equals("query")) - { - commandType = CommandType.QUERY; - } - else if (commandTypeValue.equals("table")) - { - commandType = CommandType.TABLE; - } - else - { - commandType = CommandType.COMMAND; - } - } - final XRowSet rowSet = createRowSet(command, commandType, parameters); - final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet); - - final XConnectionTools tools = (XConnectionTools) UnoRuntime.queryInterface(XConnectionTools.class, connection); - fillOrderStatement(command, commandType, parameters, tools, rowSetProp); - - if (command.length() != 0) - { - final int oldParameterCount = fillParameter(parameters, tools, command, commandType, rowSet); - - final XCompletedExecution execute = (XCompletedExecution) UnoRuntime.queryInterface(XCompletedExecution.class, rowSet); - if (execute != null && oldParameterCount > 0) - { - final XInteractionHandler handler = (XInteractionHandler) UnoRuntime.queryInterface(XInteractionHandler.class, m_cmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.sdb.InteractionHandler", m_cmpCtx)); - execute.executeWithCompletion(handler); - } - else - { - rowSet.execute(); - } - } - return new SDBCReportData(rowSet); - } - catch (Exception ex) - { - throw new DataSourceException(ex.getMessage(), ex); - } - } - - private String getOrderStatement(final int commandType, final String command, final List groupExpressions) - { - final StringBuffer order = new StringBuffer(); - final int count = groupExpressions.size(); - if (count != 0) - { - try - { - final String quote = connection.getMetaData().getIdentifierQuoteString(); - final XComponent[] hold = new XComponent[1]; - final XNameAccess columns = getFieldsByCommandDescriptor(commandType, command, hold); - - for (int i = 0; i < count; i++) - { - final Object[] pair = (Object[]) groupExpressions.get(i); - String expression = (String) pair[0]; - - if (columns.hasByName(expression)) - { - expression = quote + expression + quote; - } - expression = expression.trim(); // Trim away white spaces - - if (expression.length() > 0) - { - order.append(expression); - if (order.length() > 0) - { - order.append(' '); - } - final String sorting = (String) pair[1]; - if (sorting == null || sorting.equals(OfficeToken.FALSE)) - { - order.append("DESC"); - } - if ((i + 1) < count) - { - order.append(' '); - } - } - } - } - catch (IndexOutOfBoundsException ex) - { - Log.error("ReportProcessing failed", ex); - } - catch (SQLException ex) - { - Log.error("ReportProcessing failed", ex); - } - } - return order.toString(); - } - - private XNameAccess getFieldsByCommandDescriptor(final int commandType, final String command, final XComponent[] out) throws SQLException - { - final Class[] parameter = new Class[3]; - parameter[0] = Integer.class; - parameter[1] = String.class; - parameter[2] = out.getClass(); - final XConnectionTools tools = (XConnectionTools) UnoRuntime.queryInterface(XConnectionTools.class, connection); - try - { - tools.getClass().getMethod("getFieldsByCommandDescriptor", parameter); - return tools.getFieldsByCommandDescriptor(commandType, command, out); - } - catch (NoSuchMethodException ex) - { - } - - XNameAccess xFields = null; - // some kind of state machine to ease the sharing of code - int eState = FAILED; - switch (commandType) - { - case CommandType.TABLE: - eState = HANDLE_TABLE; - break; - case CommandType.QUERY: - eState = HANDLE_QUERY; - break; - case CommandType.COMMAND: - eState = HANDLE_SQL; - break; - } - - // needed in various states: - XNameAccess xObjectCollection = null; - XColumnsSupplier xSupplyColumns = null; - - try - { - // go! - while ((DONE != eState) && (FAILED != eState)) - { - switch (eState) - { - case HANDLE_TABLE: - { - // initial state for handling the tables - - // get the table objects - final XTablesSupplier xSupplyTables = (XTablesSupplier) UnoRuntime.queryInterface(XTablesSupplier.class, connection); - if (xSupplyTables != null) - { - xObjectCollection = xSupplyTables.getTables(); - // if something went wrong 'til here, then this will be handled in the next state - - // next state: get the object - } - eState = RETRIEVE_OBJECT; - } - break; - - case HANDLE_QUERY: - { - // initial state for handling the tables - - // get the table objects - final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection); - if (xSupplyQueries != null) - { - xObjectCollection = xSupplyQueries.getQueries(); - // if something went wrong 'til here, then this will be handled in the next state - - // next state: get the object - } - eState = RETRIEVE_OBJECT; - } - break; - - case RETRIEVE_OBJECT: - // here we should have an object (aka query or table) collection, and are going - // to retrieve the desired object - - // next state: default to FAILED - eState = FAILED; - - if (xObjectCollection != null && xObjectCollection.hasByName(command)) - { - xSupplyColumns = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xObjectCollection.getByName(command)); - - // next: go for the columns - eState = RETRIEVE_COLUMNS; - } - break; - - case RETRIEVE_COLUMNS: - // next state: default to FAILED - eState = FAILED; - - if (xSupplyColumns != null) - { - xFields = xSupplyColumns.getColumns(); - // that's it - eState = DONE; - } - break; - - case HANDLE_SQL: - { - String sStatementToExecute = command; - - // well, the main problem here is to handle statements which contain a parameter - // If we would simply execute a parametrized statement, then this will fail because - // we cannot supply any parameter values. - // Thus, we try to analyze the statement, and to append a WHERE 0=1 filter criterion - // This should cause every driver to not really execute the statement, but to return - // an empty result set with the proper structure. We then can use this result set - // to retrieve the columns. - - try - { - final XMultiServiceFactory xComposerFac = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, connection); - - if (xComposerFac != null) - { - final XSingleSelectQueryComposer xComposer = (XSingleSelectQueryComposer) UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, xComposerFac.createInstance("com.sun.star.sdb.SingleSelectQueryComposer")); - if (xComposer != null) - { - xComposer.setQuery(sStatementToExecute); - - // Now set the filter to a dummy restriction which will result in an empty - // result set. - xComposer.setFilter("0=1"); - - sStatementToExecute = xComposer.getQuery(); - } - } - } - catch (com.sun.star.uno.Exception ex) - { - // silent this error, this was just a try. If we're here, we did not change sStatementToExecute, - // so it will still be _rCommand, which then will be executed without being touched - } - - // now execute - XPreparedStatement xStatement = connection.prepareStatement(sStatementToExecute); - // transfer ownership of this temporary object to the caller - out[0] = (XComponent) UnoRuntime.queryInterface(XComponent.class, xStatement); - - // set the "MaxRows" to 0. This is just in case our attempt to append a 0=1 filter - // failed - in this case, the MaxRows restriction should at least ensure that there - // is no data returned (which would be potentially expensive) - final XPropertySet xStatementProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xStatement); - try - { - if (xStatementProps != null) - { - xStatementProps.setPropertyValue("MaxRows", new Integer(0)); - } - } - catch (com.sun.star.uno.Exception ex) - { - // oh damn. Not much of a chance to recover, we will no retrieve the complete - // full blown result set - } - - xSupplyColumns = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xStatement.executeQuery()); - // this should have given us a result set which does not contain any data, but - // the structural information we need - - // so the next state is to get the columns - eState = RETRIEVE_COLUMNS; - } - break; - default: - eState = FAILED; - } - } - } - catch (com.sun.star.uno.Exception ex) - { - } - return xFields; - } - - private XSingleSelectQueryComposer getComposer(final XConnectionTools tools, - final String command, - final int commandType) - { - final Class[] parameter = new Class[2]; - parameter[0] = Integer.class; - parameter[1] = String.class; - try - { - final Object[] param = new Object[2]; - param[0] = new Integer(commandType); - param[1] = command; - return (XSingleSelectQueryComposer) tools.getClass().getMethod("getComposer", parameter).invoke(tools, param); - } - catch (NoSuchMethodException ex) - { - } - catch (IllegalAccessException ex) - { - // should not happen - // assert False - } - catch (java.lang.reflect.InvocationTargetException ex) - { - // should not happen - // assert False - } - try - { - final XMultiServiceFactory factory = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, connection); - final XSingleSelectQueryComposer out = (XSingleSelectQueryComposer) UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, factory.createInstance("com.sun.star.sdb.SingleSelectQueryAnalyzer")); - final String quote = connection.getMetaData().getIdentifierQuoteString(); - String statement = command; - switch (commandType) - { - case CommandType.TABLE: - statement = "SELECT * FROM " + quote + command + quote; - break; - case CommandType.QUERY: - { - final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection); - final XNameAccess queries = xSupplyQueries.getQueries(); - if (queries.hasByName(command)) - { - final XPropertySet prop = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, queries.getByName(command)); - final Boolean escape = (Boolean) prop.getPropertyValue("EscapeProcessing"); - if (escape.booleanValue()) - { - statement = (String) prop.getPropertyValue(UNO_COMMAND); - final XSingleSelectQueryComposer composer = getComposer(tools, statement, CommandType.COMMAND); - if (composer != null) - { - final String order = (String) prop.getPropertyValue(UNO_ORDER); - if (order != null && order.length() != 0) - { - composer.setOrder(order); - } - final Boolean applyFilter = (Boolean) prop.getPropertyValue(UNO_APPLY_FILTER); - if (applyFilter.booleanValue()) - { - final String filter = (String) prop.getPropertyValue(UNO_FILTER); - if (filter != null && filter.length() != 0) - { - composer.setFilter(filter); - } - } - statement = composer.getQuery(); - } - } - } - } - break; - case CommandType.COMMAND: - statement = command; - break; - } - out.setElementaryQuery(statement); - return out; - } - catch (Exception e) - { - } - return null; - } - - int fillParameter(final Map parameters, - final XConnectionTools tools, - final String command, - final int commandType, final XRowSet rowSet) - throws SQLException, - UnknownPropertyException, - PropertyVetoException, - IllegalArgumentException, - WrappedTargetException - { - int oldParameterCount = 0; - - final XSingleSelectQueryComposer composer = getComposer(tools, command, commandType); - if (composer != null) - { - // get old parameter count - final XParametersSupplier paraSup = (XParametersSupplier) UnoRuntime.queryInterface(XParametersSupplier.class, composer); - if (paraSup != null) - { - final XIndexAccess params = paraSup.getParameters(); - if (params != null) - { - oldParameterCount = params.getCount(); - } - } - final ArrayList masterValues = (ArrayList) parameters.get(MASTER_VALUES); - if (masterValues != null && !masterValues.isEmpty()) - { - // Vector masterColumns = (Vector) parameters.get("master-columns"); - final ArrayList detailColumns = (ArrayList) parameters.get(DETAIL_COLUMNS); - - // create the new filter - final String quote = connection.getMetaData().getIdentifierQuoteString(); - final StringBuffer oldFilter = new StringBuffer(); - oldFilter.append(composer.getFilter()); - if (oldFilter.length() != 0) - { - oldFilter.append(" AND "); - } - int newParamterCounter = 1; - for (final Iterator it = detailColumns.iterator(); it.hasNext(); - ++newParamterCounter) - { - final String detail = (String) it.next(); - //String master = (String) masterIt.next(); - oldFilter.append(quote); - oldFilter.append(detail); - oldFilter.append(quote); - oldFilter.append(" = :link_"); - oldFilter.append(newParamterCounter); - if (it.hasNext()) - { - oldFilter.append(" AND "); - } - } - - composer.setFilter(oldFilter.toString()); - - final String sQuery = composer.getQuery(); - final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet); - rowSetProp.setPropertyValue(UNO_COMMAND, sQuery); - rowSetProp.setPropertyValue(UNO_COMMAND_TYPE, - new Integer(CommandType.COMMAND)); - - final XParameters para = (XParameters) UnoRuntime.queryInterface(XParameters.class, rowSet); - - for (int i = 0; - i < masterValues.size(); - i++) - { - Object object = masterValues.get(i); - if (object instanceof BigDecimal) - { - object = ((BigDecimal) object).toString(); - } - para.setObject(oldParameterCount + i + 1, object); - } - } - } - - return oldParameterCount; - } - - final XRowSet createRowSet(final String command, - final int commandType, final Map parameters) - throws Exception - { - final XRowSet rowSet = (XRowSet) UnoRuntime.queryInterface(XRowSet.class, m_cmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.sdb.RowSet", m_cmpCtx)); - final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet); - - rowSetProp.setPropertyValue("ActiveConnection", connection); - final Boolean escapeProcessing = (Boolean)parameters.get(ESCAPE_PROCESSING); - rowSetProp.setPropertyValue("EscapeProcessing", escapeProcessing); - rowSetProp.setPropertyValue(UNO_COMMAND_TYPE, new Integer(commandType)); - rowSetProp.setPropertyValue(UNO_COMMAND, command); - - final String filter = (String) parameters.get(UNO_FILTER); - if (filter != null) - { - rowSetProp.setPropertyValue("Filter", filter); - rowSetProp.setPropertyValue(APPLY_FILTER, Boolean.valueOf(filter.length() != 0)); - } - else - { - rowSetProp.setPropertyValue(APPLY_FILTER, Boolean.FALSE); - } - return rowSet; - } - - void fillOrderStatement(final String command, - final int commandType, final Map parameters, - final XConnectionTools tools, - final XPropertySet rowSetProp) - throws SQLException, - UnknownPropertyException, - PropertyVetoException, - IllegalArgumentException, - WrappedTargetException, - NoSuchElementException - { - final StringBuffer order = new StringBuffer(getOrderStatement(commandType, command, (ArrayList) parameters.get(GROUP_EXPRESSIONS))); - if (order.length() > 0 && commandType != CommandType.TABLE) - { - String statement = command; - final XSingleSelectQueryComposer composer = getComposer(tools, command, commandType); - if (composer != null) - { - statement = composer.getQuery(); - composer.setQuery(statement); - final String sOldOrder = composer.getOrder(); - if (sOldOrder.length() > 0) - { - order.append(','); - order.append(sOldOrder); - composer.setOrder(""); - statement = composer.getQuery(); - } - } - else - { - if (commandType == CommandType.QUERY) - { - final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection); - final XNameAccess queries = xSupplyQueries.getQueries(); - if (queries.hasByName(command)) - { - final XPropertySet prop = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, queries.getByName(command)); - final String queryCommand = (String) prop.getPropertyValue(UNO_COMMAND); - statement = "SELECT * FROM (" + queryCommand + ")"; - } - } - else - { - statement = "SELECT * FROM (" + command + ")"; - } - } - rowSetProp.setPropertyValue(UNO_COMMAND, statement); - rowSetProp.setPropertyValue(UNO_COMMAND_TYPE, new Integer(CommandType.COMMAND)); - } - rowSetProp.setPropertyValue("Order", order.toString()); - } -} - +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: SDBCReportDataFactory.java,v $
+ * $Revision: 1.9.18.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.report;
+
+import com.sun.star.beans.PropertyVetoException;
+import com.sun.star.beans.UnknownPropertyException;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.container.NoSuchElementException;
+import com.sun.star.container.XIndexAccess;
+import com.sun.star.lang.IllegalArgumentException;
+import com.sun.star.lang.WrappedTargetException;
+import com.sun.star.sdbc.XConnection;
+import com.sun.star.container.XNameAccess;
+import com.sun.star.lang.XComponent;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.sdb.CommandType;
+import com.sun.star.sdb.XCompletedExecution;
+import com.sun.star.sdb.XParametersSupplier;
+import com.sun.star.sdb.XQueriesSupplier;
+import com.sun.star.sdb.XSingleSelectQueryComposer;
+import com.sun.star.sdb.tools.XConnectionTools;
+import com.sun.star.sdbc.SQLException;
+import com.sun.star.sdbc.XParameters;
+import com.sun.star.sdbc.XPreparedStatement;
+import com.sun.star.uno.Exception;
+import java.util.Map;
+
+import com.sun.star.sdbc.XRowSet;
+import com.sun.star.sdbcx.XColumnsSupplier;
+import com.sun.star.sdbcx.XTablesSupplier;
+import com.sun.star.task.XInteractionHandler;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XComponentContext;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import org.jfree.util.Log;
+
+/**
+ * Very primitive implementation, just to show how this could be used ...
+ *
+ */
+public class SDBCReportDataFactory implements DataSourceFactory
+{
+
+ public static final String COMMAND_TYPE = "command-type";
+ public static final String ESCAPE_PROCESSING = "escape-processing";
+ public static final String GROUP_EXPRESSIONS = "group-expressions";
+ public static final String MASTER_VALUES = "master-values";
+ public static final String MASTER_COLUMNS = "master-columns";
+ public static final String DETAIL_COLUMNS = "detail-columns";
+ public static final String UNO_FILTER = "Filter";
+ private static final String APPLY_FILTER = "ApplyFilter";
+ private static final String UNO_COMMAND = "Command";
+ private static final String UNO_ORDER = "Order";
+ private static final String UNO_APPLY_FILTER = "ApplyFilter";
+ private static final String UNO_COMMAND_TYPE = "CommandType";
+ private final XConnection connection;
+ private final XComponentContext m_cmpCtx;
+ private static final int FAILED = 0;
+ private static final int DONE = 1;
+ private static final int RETRIEVE_COLUMNS = 2;
+ private static final int RETRIEVE_OBJECT = 3;
+ private static final int HANDLE_QUERY = 4;
+ private static final int HANDLE_TABLE = 5;
+ private static final int HANDLE_SQL = 6;
+
+ public SDBCReportDataFactory(final XComponentContext cmpCtx, final XConnection connection)
+ {
+ this.connection = connection;
+ m_cmpCtx = cmpCtx;
+ }
+
+ public DataSource queryData(final String command, final Map parameters) throws DataSourceException
+ {
+ try
+ {
+ if ( command == null )
+ {
+ return new SDBCReportData(null);
+ }
+ int commandType = CommandType.COMMAND;
+ final String commandTypeValue = (String) parameters.get(COMMAND_TYPE);
+ if ( commandTypeValue != null )
+ {
+ if ( commandTypeValue.equals("query") )
+ {
+ commandType = CommandType.QUERY;
+ }
+ else if ( commandTypeValue.equals("table") )
+ {
+ commandType = CommandType.TABLE;
+ }
+ else
+ {
+ commandType = CommandType.COMMAND;
+ }
+ }
+ final XRowSet rowSet = createRowSet(command, commandType, parameters);
+ final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet);
+
+ final XConnectionTools tools = (XConnectionTools) UnoRuntime.queryInterface(XConnectionTools.class, connection);
+ fillOrderStatement(command, commandType, parameters, tools, rowSetProp);
+
+ if ( command.length() != 0 )
+ {
+ final int oldParameterCount = fillParameter(parameters, tools, command, commandType, rowSet);
+
+ final XCompletedExecution execute = (XCompletedExecution) UnoRuntime.queryInterface(XCompletedExecution.class, rowSet);
+ if ( execute != null && oldParameterCount > 0 )
+ {
+ final XInteractionHandler handler = (XInteractionHandler) UnoRuntime.queryInterface(XInteractionHandler.class, m_cmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.sdb.InteractionHandler", m_cmpCtx));
+ execute.executeWithCompletion(handler);
+ }
+ else
+ {
+ rowSet.execute();
+ }
+ }
+ return new SDBCReportData(rowSet);
+ } catch ( Exception ex )
+ {
+ throw new DataSourceException(ex.getMessage(), ex);
+ }
+ }
+
+ private String getOrderStatement(final int commandType, final String command, final List groupExpressions)
+ {
+ final StringBuffer order = new StringBuffer();
+ final int count = groupExpressions.size();
+ if ( count != 0 )
+ {
+ try
+ {
+ final String quote = connection.getMetaData().getIdentifierQuoteString();
+ final XComponent[] hold = new XComponent[1];
+ final XNameAccess columns = getFieldsByCommandDescriptor(commandType, command, hold);
+
+ for (int i = 0; i < count; i++)
+ {
+ final Object[] pair = (Object[]) groupExpressions.get(i);
+ String expression = (String) pair[0];
+
+ if ( columns.hasByName(expression) )
+ {
+ expression = quote + expression + quote;
+ }
+ expression = expression.trim(); // Trim away white spaces
+
+ if ( expression.length() > 0 )
+ {
+ order.append(expression);
+ if ( order.length() > 0 )
+ {
+ order.append(' ');
+ }
+ final String sorting = (String) pair[1];
+ if ( sorting == null || sorting.equals(OfficeToken.FALSE) )
+ {
+ order.append("DESC");
+ }
+ if ( (i + 1) < count )
+ {
+ order.append(' ');
+ }
+ }
+ }
+ } catch ( IndexOutOfBoundsException ex )
+ {
+ Log.error("ReportProcessing failed", ex);
+ } catch ( SQLException ex )
+ {
+ Log.error("ReportProcessing failed", ex);
+ }
+ }
+ return order.toString();
+ }
+
+ private XNameAccess getFieldsByCommandDescriptor(final int commandType, final String command, final XComponent[] out) throws SQLException
+ {
+ final Class[] parameter = new Class[3];
+ parameter[0] = Integer.class;
+ parameter[1] = String.class;
+ parameter[2] = out.getClass();
+ final XConnectionTools tools = (XConnectionTools) UnoRuntime.queryInterface(XConnectionTools.class, connection);
+ try
+ {
+ tools.getClass().getMethod("getFieldsByCommandDescriptor", parameter);
+ return tools.getFieldsByCommandDescriptor(commandType, command, out);
+ } catch ( NoSuchMethodException ex )
+ {
+ }
+
+ XNameAccess xFields = null;
+ // some kind of state machine to ease the sharing of code
+ int eState = FAILED;
+ switch ( commandType )
+ {
+ case CommandType.TABLE:
+ eState = HANDLE_TABLE;
+ break;
+ case CommandType.QUERY:
+ eState = HANDLE_QUERY;
+ break;
+ case CommandType.COMMAND:
+ eState = HANDLE_SQL;
+ break;
+ }
+
+ // needed in various states:
+ XNameAccess xObjectCollection = null;
+ XColumnsSupplier xSupplyColumns = null;
+
+ try
+ {
+ // go!
+ while ((DONE != eState) && (FAILED != eState))
+ {
+ switch ( eState )
+ {
+ case HANDLE_TABLE:
+ {
+ // initial state for handling the tables
+
+ // get the table objects
+ final XTablesSupplier xSupplyTables = (XTablesSupplier) UnoRuntime.queryInterface(XTablesSupplier.class, connection);
+ if ( xSupplyTables != null )
+ {
+ xObjectCollection = xSupplyTables.getTables();
+ // if something went wrong 'til here, then this will be handled in the next state
+
+ // next state: get the object
+ }
+ eState = RETRIEVE_OBJECT;
+ }
+ break;
+
+ case HANDLE_QUERY:
+ {
+ // initial state for handling the tables
+
+ // get the table objects
+ final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection);
+ if ( xSupplyQueries != null )
+ {
+ xObjectCollection = xSupplyQueries.getQueries();
+ // if something went wrong 'til here, then this will be handled in the next state
+
+ // next state: get the object
+ }
+ eState = RETRIEVE_OBJECT;
+ }
+ break;
+
+ case RETRIEVE_OBJECT:
+ // here we should have an object (aka query or table) collection, and are going
+ // to retrieve the desired object
+
+ // next state: default to FAILED
+ eState = FAILED;
+
+ if ( xObjectCollection != null && xObjectCollection.hasByName(command) )
+ {
+ xSupplyColumns = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xObjectCollection.getByName(command));
+
+ // next: go for the columns
+ eState = RETRIEVE_COLUMNS;
+ }
+ break;
+
+ case RETRIEVE_COLUMNS:
+ // next state: default to FAILED
+ eState = FAILED;
+
+ if ( xSupplyColumns != null )
+ {
+ xFields = xSupplyColumns.getColumns();
+ // that's it
+ eState = DONE;
+ }
+ break;
+
+ case HANDLE_SQL:
+ {
+ String sStatementToExecute = command;
+
+ // well, the main problem here is to handle statements which contain a parameter
+ // If we would simply execute a parametrized statement, then this will fail because
+ // we cannot supply any parameter values.
+ // Thus, we try to analyze the statement, and to append a WHERE 0=1 filter criterion
+ // This should cause every driver to not really execute the statement, but to return
+ // an empty result set with the proper structure. We then can use this result set
+ // to retrieve the columns.
+
+ try
+ {
+ final XMultiServiceFactory xComposerFac = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, connection);
+
+ if ( xComposerFac != null )
+ {
+ final XSingleSelectQueryComposer xComposer = (XSingleSelectQueryComposer) UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, xComposerFac.createInstance("com.sun.star.sdb.SingleSelectQueryComposer"));
+ if ( xComposer != null )
+ {
+ xComposer.setQuery(sStatementToExecute);
+
+ // Now set the filter to a dummy restriction which will result in an empty
+ // result set.
+ xComposer.setFilter("0=1");
+
+ sStatementToExecute = xComposer.getQuery();
+ }
+ }
+ } catch ( com.sun.star.uno.Exception ex )
+ {
+ // silent this error, this was just a try. If we're here, we did not change sStatementToExecute,
+ // so it will still be _rCommand, which then will be executed without being touched
+ }
+
+ // now execute
+ XPreparedStatement xStatement = connection.prepareStatement(sStatementToExecute);
+ // transfer ownership of this temporary object to the caller
+ out[0] = (XComponent) UnoRuntime.queryInterface(XComponent.class, xStatement);
+
+ // set the "MaxRows" to 0. This is just in case our attempt to append a 0=1 filter
+ // failed - in this case, the MaxRows restriction should at least ensure that there
+ // is no data returned (which would be potentially expensive)
+ final XPropertySet xStatementProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xStatement);
+ try
+ {
+ if ( xStatementProps != null )
+ {
+ xStatementProps.setPropertyValue("MaxRows", new Integer(0));
+ }
+ } catch ( com.sun.star.uno.Exception ex )
+ {
+ // oh damn. Not much of a chance to recover, we will no retrieve the complete
+ // full blown result set
+ }
+
+ xSupplyColumns = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xStatement.executeQuery());
+ // this should have given us a result set which does not contain any data, but
+ // the structural information we need
+
+ // so the next state is to get the columns
+ eState = RETRIEVE_COLUMNS;
+ }
+ break;
+ default:
+ eState = FAILED;
+ }
+ }
+ } catch ( com.sun.star.uno.Exception ex )
+ {
+ }
+ return xFields;
+ }
+
+ private XSingleSelectQueryComposer getComposer(final XConnectionTools tools,
+ final String command,
+ final int commandType)
+ {
+ final Class[] parameter = new Class[2];
+ parameter[0] = int.class;
+ parameter[1] = String.class;
+ try
+ {
+ final Object[] param = new Object[2];
+ param[0] = new Integer(commandType);
+ param[1] = command;
+ return (XSingleSelectQueryComposer) tools.getClass().getMethod("getComposer", parameter).invoke(tools, param);
+ } catch ( NoSuchMethodException ex )
+ {
+ } catch ( IllegalAccessException ex )
+ {
+ // should not happen
+ // assert False
+ } catch ( java.lang.reflect.InvocationTargetException ex )
+ {
+ // should not happen
+ // assert False
+ }
+ try
+ {
+ final XMultiServiceFactory factory = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, connection);
+ final XSingleSelectQueryComposer out = (XSingleSelectQueryComposer) UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, factory.createInstance("com.sun.star.sdb.SingleSelectQueryAnalyzer"));
+ final String quote = connection.getMetaData().getIdentifierQuoteString();
+ String statement = command;
+ switch ( commandType )
+ {
+ case CommandType.TABLE:
+ statement = "SELECT * FROM " + quote + command + quote;
+ break;
+ case CommandType.QUERY:
+ {
+ final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection);
+ final XNameAccess queries = xSupplyQueries.getQueries();
+ if ( queries.hasByName(command) )
+ {
+ final XPropertySet prop = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, queries.getByName(command));
+ final Boolean escape = (Boolean) prop.getPropertyValue("EscapeProcessing");
+ if (escape.booleanValue())
+ {
+ statement = (String) prop.getPropertyValue(UNO_COMMAND);
+ final XSingleSelectQueryComposer composer = getComposer(tools, statement, CommandType.COMMAND);
+ if (composer != null)
+ {
+ final String order = (String) prop.getPropertyValue(UNO_ORDER);
+ if (order != null && order.length() != 0)
+ {
+ composer.setOrder(order);
+ }
+ final Boolean applyFilter = (Boolean) prop.getPropertyValue(UNO_APPLY_FILTER);
+ if (applyFilter.booleanValue())
+ {
+ final String filter = (String) prop.getPropertyValue(UNO_FILTER);
+ if (filter != null && filter.length() != 0)
+ {
+ composer.setFilter(filter);
+ }
+ }
+ statement = composer.getQuery();
+ }
+ }
+ }
+ }
+ break;
+ case CommandType.COMMAND:
+ statement = command;
+ break;
+ }
+ out.setElementaryQuery(statement);
+ return out;
+ } catch ( Exception e )
+ {
+ }
+ return null;
+ }
+
+ int fillParameter(final Map parameters,
+ final XConnectionTools tools,
+ final String command,
+ final int commandType, final XRowSet rowSet)
+ throws SQLException,
+ UnknownPropertyException,
+ PropertyVetoException,
+ IllegalArgumentException,
+ WrappedTargetException
+ {
+ int oldParameterCount = 0;
+
+ final XSingleSelectQueryComposer composer = getComposer(tools, command, commandType);
+ if ( composer != null )
+ {
+ final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet);
+ if ( ((Boolean)rowSetProp.getPropertyValue(APPLY_FILTER)).booleanValue() )
+ {
+ composer.setFilter((String)rowSetProp.getPropertyValue("Filter"));
+ }
+ // get old parameter count
+ final XParametersSupplier paraSup = (XParametersSupplier) UnoRuntime.queryInterface(XParametersSupplier.class, composer);
+ if ( paraSup != null )
+ {
+ final XIndexAccess params = paraSup.getParameters();
+ if ( params != null )
+ {
+ oldParameterCount = params.getCount();
+ }
+ }
+ final ArrayList masterValues = (ArrayList) parameters.get(MASTER_VALUES);
+ if ( masterValues != null && !masterValues.isEmpty() )
+ {
+ // Vector masterColumns = (Vector) parameters.get("master-columns");
+ final ArrayList detailColumns = (ArrayList) parameters.get(DETAIL_COLUMNS);
+ if ( oldParameterCount < detailColumns.size() )
+ {
+ // create the new filter
+ final String quote = connection.getMetaData().getIdentifierQuoteString();
+ final StringBuffer oldFilter = new StringBuffer();
+ oldFilter.append(composer.getFilter());
+ if ( oldFilter.length() != 0 )
+ {
+ oldFilter.append(" AND ");
+ }
+ int newParamterCounter = 1;
+ for (final Iterator it = detailColumns.iterator(); it.hasNext();
+ ++newParamterCounter)
+ {
+ final String detail = (String) it.next();
+ //String master = (String) masterIt.next();
+ oldFilter.append(quote);
+ oldFilter.append(detail);
+ oldFilter.append(quote);
+ oldFilter.append(" = :link_");
+ oldFilter.append(newParamterCounter);
+ if ( it.hasNext() )
+ {
+ oldFilter.append(" AND ");
+ }
+ }
+
+ composer.setFilter(oldFilter.toString());
+ }
+ else
+ oldParameterCount = 0;
+
+ final String sQuery = composer.getQuery();
+ rowSetProp.setPropertyValue(UNO_COMMAND, sQuery);
+ rowSetProp.setPropertyValue(UNO_COMMAND_TYPE,
+ new Integer(CommandType.COMMAND));
+
+ final XParameters para = (XParameters) UnoRuntime.queryInterface(XParameters.class, rowSet);
+
+ for (int i = 0;
+ i < masterValues.size();
+ i++)
+ {
+ Object object = masterValues.get(i);
+ if ( object instanceof BigDecimal )
+ {
+ object = ((BigDecimal) object).toString();
+ }
+ para.setObject(oldParameterCount + i + 1, object);
+ }
+ }
+ }
+
+ return oldParameterCount;
+ }
+
+ private final XRowSet createRowSet(final String command,
+ final int commandType, final Map parameters)
+ throws Exception
+ {
+ final XRowSet rowSet = (XRowSet) UnoRuntime.queryInterface(XRowSet.class, m_cmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.sdb.RowSet", m_cmpCtx));
+ final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet);
+
+ rowSetProp.setPropertyValue("ActiveConnection", connection);
+ final Boolean escapeProcessing = (Boolean)parameters.get(ESCAPE_PROCESSING);
+ rowSetProp.setPropertyValue("EscapeProcessing", escapeProcessing);
+ rowSetProp.setPropertyValue(UNO_COMMAND_TYPE, new Integer(commandType));
+ rowSetProp.setPropertyValue(UNO_COMMAND, command);
+
+ final String filter = (String) parameters.get(UNO_FILTER);
+ if ( filter != null )
+ {
+ rowSetProp.setPropertyValue("Filter", filter);
+ rowSetProp.setPropertyValue(APPLY_FILTER, Boolean.valueOf(filter.length() != 0));
+ }
+ else
+ {
+ rowSetProp.setPropertyValue(APPLY_FILTER, Boolean.FALSE);
+ }
+ return rowSet;
+ }
+
+ void fillOrderStatement(final String command,
+ final int commandType, final Map parameters,
+ final XConnectionTools tools,
+ final XPropertySet rowSetProp)
+ throws SQLException,
+ UnknownPropertyException,
+ PropertyVetoException,
+ IllegalArgumentException,
+ WrappedTargetException,
+ NoSuchElementException
+ {
+ final StringBuffer order = new StringBuffer(getOrderStatement(commandType, command, (ArrayList) parameters.get(GROUP_EXPRESSIONS)));
+ if ( order.length() > 0 && commandType != CommandType.TABLE )
+ {
+ String statement = command;
+ final XSingleSelectQueryComposer composer = getComposer(tools, command, commandType);
+ if ( composer != null )
+ {
+ statement = composer.getQuery();
+ composer.setQuery(statement);
+ final String sOldOrder = composer.getOrder();
+ if ( sOldOrder.length() > 0 )
+ {
+ order.append(',');
+ order.append(sOldOrder);
+ composer.setOrder("");
+ statement = composer.getQuery();
+ }
+ }
+ else
+ {
+ if ( commandType == CommandType.QUERY )
+ {
+ final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection);
+ final XNameAccess queries = xSupplyQueries.getQueries();
+ if ( queries.hasByName(command) )
+ {
+ final XPropertySet prop = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, queries.getByName(command));
+ final String queryCommand = (String) prop.getPropertyValue(UNO_COMMAND);
+ statement = "SELECT * FROM (" + queryCommand + ")";
+ }
+ }
+ else
+ {
+ statement = "SELECT * FROM (" + command + ")";
+ }
+ }
+ rowSetProp.setPropertyValue(UNO_COMMAND, statement);
+ rowSetProp.setPropertyValue(UNO_COMMAND_TYPE, new Integer(CommandType.COMMAND));
+ }
+ rowSetProp.setPropertyValue("Order", order.toString());
+ }
+}
+
diff --git a/reportdesign/java/com/sun/star/report/function/metadata/MetaDataFunctionCategory.java b/reportdesign/java/com/sun/star/report/function/metadata/MetaDataFunctionCategory.java index f7daee9fdb23..3a5b43aee9fd 100644 --- a/reportdesign/java/com/sun/star/report/function/metadata/MetaDataFunctionCategory.java +++ b/reportdesign/java/com/sun/star/report/function/metadata/MetaDataFunctionCategory.java @@ -1,48 +1,48 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: MetaDataFunctionCategory.java,v $ - * $Revision: 1.2 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.report.function.metadata; - -import org.jfree.formula.function.AbstractFunctionCategory; -import org.jfree.formula.function.FunctionCategory; - -/** - * - * @author Ocke Janssen - */ -public class MetaDataFunctionCategory extends AbstractFunctionCategory -{ - - public static final FunctionCategory CATEGORY = new MetaDataFunctionCategory(); - - private MetaDataFunctionCategory() - { - super("com.sun.star.report.functions.metadata.category"); - } -} +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: MetaDataFunctionCategory.java,v $
+ * $Revision: 1.2 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.report.function.metadata;
+
+import org.jfree.formula.function.AbstractFunctionCategory;
+import org.jfree.formula.function.FunctionCategory;
+
+/**
+ *
+ * @author Ocke Janssen
+ */
+public class MetaDataFunctionCategory extends AbstractFunctionCategory
+{
+
+ public static final FunctionCategory CATEGORY = new MetaDataFunctionCategory();
+
+ private MetaDataFunctionCategory()
+ {
+ super("com.sun.star.report.function.metadata.category");
+ }
+}
diff --git a/reportdesign/java/com/sun/star/report/function/metadata/category.properties b/reportdesign/java/com/sun/star/report/function/metadata/category.properties index 44b7ed1d5e9b..7240967b7d57 100644 --- a/reportdesign/java/com/sun/star/report/function/metadata/category.properties +++ b/reportdesign/java/com/sun/star/report/function/metadata/category.properties @@ -1,33 +1,33 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: category.properties,v $ -# -# $Revision: 1.2 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# <http://www.openoffice.org/license.html> -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -display-name=MetaData -description=Contains functions about meta data
\ No newline at end of file +#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: category.properties,v $
+#
+# $Revision: 1.2 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+display-name=Document Information
+description=Contains functions to access document information.
diff --git a/reportdesign/java/com/sun/star/report/pentaho/layoutprocessor/ObjectOleLayoutController.java b/reportdesign/java/com/sun/star/report/pentaho/layoutprocessor/ObjectOleLayoutController.java index 5ce156c2be09..8cddecd48564 100644 --- a/reportdesign/java/com/sun/star/report/pentaho/layoutprocessor/ObjectOleLayoutController.java +++ b/reportdesign/java/com/sun/star/report/pentaho/layoutprocessor/ObjectOleLayoutController.java @@ -1,125 +1,125 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: ObjectOleLayoutController.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.report.pentaho.layoutprocessor; - -import com.sun.star.report.SDBCReportDataFactory; -import com.sun.star.report.pentaho.OfficeNamespaces; -import com.sun.star.report.OfficeToken; -import com.sun.star.report.pentaho.model.ObjectOleElement; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import org.jfree.report.DataSourceException; -import org.jfree.report.ReportDataFactoryException; -import org.jfree.report.ReportProcessingException; -import org.jfree.report.flow.ReportTarget; -import org.jfree.report.flow.layoutprocessor.LayoutController; -import org.jfree.layouting.util.AttributeMap; -import org.jfree.report.DataFlags; -import org.jfree.report.DataRow; -import org.jfree.report.JFreeReportInfo; -import org.jfree.report.structure.Element; - -/** - * - * @author Ocke Janssen - */ -public class ObjectOleLayoutController extends AbstractReportElementLayoutController -{ - - public ObjectOleLayoutController() - { - } - - protected boolean isValueChanged() - { - final ObjectOleElement element = (ObjectOleElement) getNode(); - final List masterfields = element.getMasterfields(); - final DataRow view = getFlowController().getMasterRow().getGlobalView(); - for (final Iterator iter = masterfields.iterator(); iter.hasNext();) - { - final String master = (String) iter.next(); - try - { - final DataFlags flags = view.getFlags(master); - if (flags != null && flags.isChanged()) - { - return true; - } - } - catch (DataSourceException e) - { - // ignore .. assume that the reference has not changed. - } - } - return false; - } - - protected LayoutController delegateContentGeneration(final ReportTarget target) throws ReportProcessingException, ReportDataFactoryException, DataSourceException - { - final ObjectOleElement element = (ObjectOleElement) getNode(); - final String url = element.getUrl(); - if (url != null) - { - final AttributeMap ole = new AttributeMap(); - ole.setAttribute(JFreeReportInfo.REPORT_NAMESPACE, Element.NAMESPACE_ATTRIBUTE, OfficeNamespaces.INTERNAL_NS); - ole.setAttribute(JFreeReportInfo.REPORT_NAMESPACE, Element.TYPE_ATTRIBUTE, OfficeToken.OBJECT_OLE); - ole.setAttribute(OfficeNamespaces.INTERNAL_NS, "href", url); - ole.setAttribute(OfficeNamespaces.INTERNAL_NS, "class-id", element.getClassid()); - final List masterfields = element.getMasterfields(); - final List values = new ArrayList(); - final DataRow view = getFlowController().getMasterRow().getGlobalView(); - for (final Iterator iter = masterfields.iterator(); iter.hasNext();) - { - final String master = (String) iter.next(); - try - { - final DataFlags flags = view.getFlags(master); - if (flags != null) - { - values.add(flags.getValue()); - } - } - catch (DataSourceException e) - { - // ignore .. assume that the reference has not changed. - } - } - ole.setAttribute(OfficeNamespaces.INTERNAL_NS, "master-columns", masterfields); - ole.setAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_VALUES, values); - ole.setAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.DETAIL_COLUMNS, element.getDetailfields()); - - target.startElement(ole); - target.endElement(ole); - } - - return join(getFlowController()); - } -} +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ObjectOleLayoutController.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.report.pentaho.layoutprocessor;
+
+import com.sun.star.report.SDBCReportDataFactory;
+import com.sun.star.report.pentaho.OfficeNamespaces;
+import com.sun.star.report.OfficeToken;
+import com.sun.star.report.pentaho.model.ObjectOleElement;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import org.jfree.report.DataSourceException;
+import org.jfree.report.ReportDataFactoryException;
+import org.jfree.report.ReportProcessingException;
+import org.jfree.report.flow.ReportTarget;
+import org.jfree.report.flow.layoutprocessor.LayoutController;
+import org.jfree.layouting.util.AttributeMap;
+import org.jfree.report.DataFlags;
+import org.jfree.report.DataRow;
+import org.jfree.report.JFreeReportInfo;
+import org.jfree.report.structure.Element;
+
+/**
+ *
+ * @author Ocke Janssen
+ */
+public class ObjectOleLayoutController extends AbstractReportElementLayoutController
+{
+
+ public ObjectOleLayoutController()
+ {
+ }
+
+ protected boolean isValueChanged()
+ {
+ final ObjectOleElement element = (ObjectOleElement) getNode();
+ final List masterfields = element.getMasterfields();
+ final DataRow view = getFlowController().getMasterRow().getGlobalView();
+ for (final Iterator iter = masterfields.iterator(); iter.hasNext();)
+ {
+ final String master = (String) iter.next();
+ try
+ {
+ final DataFlags flags = view.getFlags(master);
+ if (flags != null && flags.isChanged())
+ {
+ return true;
+ }
+ }
+ catch (DataSourceException e)
+ {
+ // ignore .. assume that the reference has not changed.
+ }
+ }
+ return false;
+ }
+
+ protected LayoutController delegateContentGeneration(final ReportTarget target) throws ReportProcessingException, ReportDataFactoryException, DataSourceException
+ {
+ final ObjectOleElement element = (ObjectOleElement) getNode();
+ final String url = element.getUrl();
+ if (url != null)
+ {
+ final AttributeMap ole = new AttributeMap();
+ ole.setAttribute(JFreeReportInfo.REPORT_NAMESPACE, Element.NAMESPACE_ATTRIBUTE, OfficeNamespaces.INTERNAL_NS);
+ ole.setAttribute(JFreeReportInfo.REPORT_NAMESPACE, Element.TYPE_ATTRIBUTE, OfficeToken.OBJECT_OLE);
+ ole.setAttribute(OfficeNamespaces.INTERNAL_NS, "href", url);
+ ole.setAttribute(OfficeNamespaces.INTERNAL_NS, "class-id", element.getClassid());
+ final List masterfields = element.getMasterfields();
+ final List values = new ArrayList();
+ final DataRow view = getFlowController().getMasterRow().getGlobalView();
+ for (final Iterator iter = masterfields.iterator(); iter.hasNext();)
+ {
+ final String master = (String) iter.next();
+ try
+ {
+ final DataFlags flags = view.getFlags(master);
+ if (flags != null)
+ {
+ values.add(flags.getValue());
+ }
+ }
+ catch (DataSourceException e)
+ {
+ // ignore .. assume that the reference has not changed.
+ }
+ }
+ ole.setAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_COLUMNS, masterfields);
+ ole.setAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_VALUES, values);
+ ole.setAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.DETAIL_COLUMNS, element.getDetailfields());
+
+ target.startElement(ole);
+ target.endElement(ole);
+ }
+
+ return join(getFlowController());
+ }
+}
diff --git a/reportdesign/java/com/sun/star/report/pentaho/output/OfficeDocumentReportTarget.java b/reportdesign/java/com/sun/star/report/pentaho/output/OfficeDocumentReportTarget.java index faaaed0dcd31..623a4a77b610 100644 --- a/reportdesign/java/com/sun/star/report/pentaho/output/OfficeDocumentReportTarget.java +++ b/reportdesign/java/com/sun/star/report/pentaho/output/OfficeDocumentReportTarget.java @@ -1,1636 +1,1636 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: OfficeDocumentReportTarget.java,v $ - * $Revision: 1.9 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.report.pentaho.output; - -import com.sun.star.report.DataSourceFactory; -import java.awt.Image; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Iterator; -import java.util.Map; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.InflaterInputStream; - -import com.sun.star.report.ImageService; -import com.sun.star.report.InputRepository; -import com.sun.star.report.OutputRepository; -import com.sun.star.report.SDBCReportDataFactory; -import com.sun.star.report.pentaho.OfficeNamespaces; -import com.sun.star.report.OfficeToken; -import com.sun.star.report.pentaho.layoutprocessor.ImageElementContext; -import com.sun.star.report.pentaho.model.OfficeDocument; -import com.sun.star.report.pentaho.model.OfficeStyle; -import com.sun.star.report.pentaho.model.OfficeStyles; -import com.sun.star.report.pentaho.model.OfficeStylesCollection; -import com.sun.star.report.pentaho.styles.LengthCalculator; -import com.sun.star.report.pentaho.styles.StyleMapper; -import java.util.ArrayList; -import org.jfree.io.IOUtils; -import org.jfree.layouting.input.style.parser.CSSValueFactory; -import org.jfree.layouting.input.style.parser.StyleSheetParserUtil; -import org.jfree.layouting.input.style.values.CSSNumericValue; -import org.jfree.layouting.layouter.style.CSSValueResolverUtility; -import org.jfree.layouting.namespace.NamespaceDefinition; -import org.jfree.layouting.namespace.Namespaces; -import org.jfree.layouting.util.AttributeMap; -import org.jfree.report.DataFlags; -import org.jfree.report.DataSourceException; -import org.jfree.report.JFreeReportBoot; -import org.jfree.report.JFreeReportInfo; -import org.jfree.report.ReportProcessingException; -import org.jfree.report.flow.AbstractReportTarget; -import org.jfree.report.flow.ReportJob; -import org.jfree.report.flow.ReportStructureRoot; -import org.jfree.report.flow.ReportTargetUtil; -import org.jfree.report.structure.Element; -import org.jfree.report.structure.Section; -import org.jfree.report.util.AttributeNameGenerator; -import org.jfree.report.util.IntegerCache; -import org.jfree.report.util.MemoryByteArrayOutputStream; -import org.jfree.resourceloader.ResourceException; -import org.jfree.resourceloader.ResourceKey; -import org.jfree.resourceloader.ResourceManager; -import org.jfree.util.FastStack; -import org.jfree.util.LineBreakIterator; -import org.jfree.util.Log; -import org.jfree.xmlns.common.AttributeList; -import org.jfree.xmlns.writer.DefaultTagDescription; -import org.jfree.xmlns.writer.XmlWriter; -import org.jfree.xmlns.writer.XmlWriterSupport; -import org.w3c.css.sac.LexicalUnit; - -/** - * Todo: Document me! - * - * @author Thomas Morgner - * @since 08.03.2007 - */ -public abstract class OfficeDocumentReportTarget extends AbstractReportTarget -{ - - public static final String HORIZONTAL_POS = "horizontal-pos"; - public static final String TAG_DEF_PREFIX = "com.sun.star.report.pentaho.output."; - public static final int ROLE_NONE = 0; - public static final int ROLE_REPORT_HEADER = 1; - public static final int ROLE_REPORT_FOOTER = 2; - public static final int ROLE_GROUP_HEADER = 3; - public static final int ROLE_GROUP_FOOTER = 4; - public static final int ROLE_REPEATING_GROUP_HEADER = 5; - public static final int ROLE_REPEATING_GROUP_FOOTER = 6; - public static final int ROLE_PAGE_HEADER = 7; - public static final int ROLE_PAGE_FOOTER = 8; - public static final int ROLE_DETAIL = 9; - public static final int ROLE_VARIABLES = 10; - public static final int ROLE_TEMPLATE = 11; - public static final int ROLE_SPREADSHEET_PAGE_HEADER = 12; - public static final int ROLE_SPREADSHEET_PAGE_FOOTER = 13; - public static final int STATE_IN_DOCUMENT = 0; - public static final int STATE_IN_BODY = 1; - public static final int STATE_IN_CONTENT = 2; - public static final int STATE_IN_GROUP = 3; - public static final int STATE_IN_GROUP_BODY = 4; - public static final int STATE_IN_SECTION = 5; - public static final int STATE_IN_OTHER = 6; - public static final int STATE_IN_GROUP_INSTANCE = 7; - public static final String FAILED = "Failed"; - public static final String VERTICAL_POS = "vertical-pos"; - private static final String ZERO_CM = "0cm"; - - protected static class BufferState - { - - private final XmlWriter xmlWriter; - private final MemoryByteArrayOutputStream xmlBuffer; - private final OfficeStylesCollection stylesCollection; - - protected BufferState(final XmlWriter xmlWriter, - final MemoryByteArrayOutputStream xmlBuffer, - final OfficeStylesCollection stylesCollection) - { - this.stylesCollection = stylesCollection; - this.xmlWriter = xmlWriter; - this.xmlBuffer = xmlBuffer; - } - - public OfficeStylesCollection getStylesCollection() - { - return stylesCollection; - } - - public XmlWriter getXmlWriter() - { - return xmlWriter; - } - - public String getXmlBuffer() throws ReportProcessingException - { - try - { - final byte[] zippedData = xmlBuffer.getRaw(); - final InputStreamReader reader = new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(zippedData, 0, xmlBuffer.getLength())), "UTF-16"); - final StringWriter writer = new StringWriter((zippedData.length / 2) + 1); - IOUtils.getInstance().copyWriter(reader, writer); - return writer.toString(); - } - catch (IOException e) - { - throw new ReportProcessingException("Failed to copy buffer", e); - } - } - - public Reader getXmlAsReader() throws ReportProcessingException - { - try - { - final byte[] zippedData = xmlBuffer.getRaw(); - return new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(zippedData, 0, xmlBuffer.getLength())), "UTF-16"); - } - catch (IOException e) - { - throw new ReportProcessingException("Failed to copy buffer", e); - } - } - } - - protected static class GroupContext - { - - private final GroupContext parent; - private int iterationCount; - private boolean groupWithRepeatingSection; - - protected GroupContext(final GroupContext parent) - { - this.parent = parent; - } - - public GroupContext getParent() - { - return parent; - } - - public int getIterationCount() - { - return iterationCount; - } - - public void setIterationCount(final int iterationCount) - { - this.iterationCount = iterationCount; - } - - public boolean isGroupWithRepeatingSection() - { - return groupWithRepeatingSection; - } - - public void setGroupWithRepeatingSection(final boolean groupWithRepeatingSection) - { - this.groupWithRepeatingSection = groupWithRepeatingSection; - } - - public String toString() - { - return "GroupContext{" + - "parent=" + parent + - ", iterationCount=" + iterationCount + - ", groupWithRepeatingSection=" + groupWithRepeatingSection + - '}'; - } - } - private final FastStack states; - private int currentRole; - private final FastStack xmlWriters; - private XmlWriter rootXmlWriter; - /** - * This styles-collection contains all styles that were predefined in the report definition file. The common styles - * and the master-styles will be written unmodified, the automatic styles will be ignored. - */ - private OfficeStylesCollection predefinedStylesCollection; - /** - * This styles-collection contains all master-styles that have been generated by the report definition process. It - * also contains all automatic styles that have been generated for the page-bands (and the pagebands as well). - */ - private OfficeStylesCollection globalStylesCollection; - /** - * The content styles collection contains all automatic styles that have been generated for the normal-flow content. - */ - private OfficeStylesCollection contentStylesCollection; - private final OutputRepository outputRepository; - private final InputRepository inputRepository; - private final AttributeNameGenerator tableNameGenerator; - private final AttributeNameGenerator frameNameGenerator; - private final AttributeNameGenerator autoStyleNameGenerator; - private final String target; - private static final int INITIAL_BUFFER_SIZE = 40960; - private StyleMapper styleMapper; - private StyleSheetParserUtil styleSheetParserUtil; - private final AttributeNameGenerator imageNames; - private final ImageProducer imageProducer; - private final OleProducer oleProducer; - private GroupContext groupContext; - private static final boolean DEBUG_ELEMENTS = - JFreeReportBoot.getInstance().getExtendedConfig().getBoolProperty("com.sun.star.report.pentaho.output.DebugElements"); - - protected OfficeDocumentReportTarget(final ReportJob reportJob, - final ResourceManager resourceManager, - final ResourceKey baseResource, - final InputRepository inputRepository, - final OutputRepository outputRepository, - final String target, - final ImageService imageService, - final DataSourceFactory datasourcefactory) - throws ReportProcessingException - { - super(reportJob, resourceManager, baseResource); - if (imageService == null) - { - throw new NullPointerException("ImageService must not be null"); - } - if (target == null) - { - throw new NullPointerException("Target-Name must not be null"); - } - - this.target = target; - - this.tableNameGenerator = new AttributeNameGenerator(); - this.frameNameGenerator = new AttributeNameGenerator(); - this.autoStyleNameGenerator = new AttributeNameGenerator(); - this.outputRepository = outputRepository; - this.inputRepository = inputRepository; - this.states = new FastStack(); - this.xmlWriters = new FastStack(); - this.imageNames = new AttributeNameGenerator(); - - this.imageProducer = new ImageProducer(inputRepository, outputRepository, imageService); - this.oleProducer = new OleProducer(inputRepository, outputRepository, imageService, datasourcefactory); - - try - { - final ResourceManager realResourceManager = getResourceManager(); - styleMapper = StyleMapper.loadInstance(realResourceManager); - } - catch (ResourceException e) - { - throw new ReportProcessingException("Failed to load style-mapper", e); - } - } - - protected abstract String getTargetMimeType(); - - protected OutputRepository getOutputRepository() - { - return outputRepository; - } - - protected InputRepository getInputRepository() - { - return inputRepository; - } - - /** - * Starts the output of a new office document. This method writes the generic 'office:document-content' tag along with - * all known namespace declarations. - * - * @param report the report object. - * @throws DataSourceException if there was an error accessing the datasource - * @throws ReportProcessingException if some other error occured. - */ - public void startReport(final ReportStructureRoot report) - throws DataSourceException, ReportProcessingException - { - imageNames.reset(); - this.groupContext = new GroupContext(null); - - final DefaultTagDescription tagDescription = createTagDescription(); - try - { - final OutputStream outputStream = outputRepository.createOutputStream(target, "text/xml"); - final Writer writer = new OutputStreamWriter(outputStream, "UTF-8"); - - this.rootXmlWriter = new XmlWriter(writer, tagDescription); - this.rootXmlWriter.setAlwaysAddNamespace(true); - - final AttributeList rootAttributes = new AttributeList(); - rootAttributes.addNamespaceDeclaration("office", OfficeNamespaces.OFFICE_NS); - rootAttributes.addNamespaceDeclaration("style", OfficeNamespaces.STYLE_NS); - rootAttributes.addNamespaceDeclaration("text", OfficeNamespaces.TEXT_NS); - rootAttributes.addNamespaceDeclaration("table", OfficeNamespaces.TABLE_NS); - rootAttributes.addNamespaceDeclaration("draw", OfficeNamespaces.DRAWING_NS); - rootAttributes.addNamespaceDeclaration("fo", OfficeNamespaces.FO_NS); - rootAttributes.addNamespaceDeclaration("xlink", OfficeNamespaces.XLINK_NS); - rootAttributes.addNamespaceDeclaration("dc", OfficeNamespaces.PURL_NS); - rootAttributes.addNamespaceDeclaration("meta", OfficeNamespaces.META_NS); - rootAttributes.addNamespaceDeclaration("number", OfficeNamespaces.DATASTYLE_NS); - rootAttributes.addNamespaceDeclaration("svg", OfficeNamespaces.SVG_NS); - rootAttributes.addNamespaceDeclaration("chart", OfficeNamespaces.CHART_NS); - rootAttributes.addNamespaceDeclaration("dr3d", OfficeNamespaces.DR3D_NS); - rootAttributes.addNamespaceDeclaration("math", OfficeNamespaces.MATHML_NS); - rootAttributes.addNamespaceDeclaration("form", OfficeNamespaces.FORM_NS); - rootAttributes.addNamespaceDeclaration("script", OfficeNamespaces.SCRIPT_NS); - rootAttributes.addNamespaceDeclaration("ooo", OfficeNamespaces.OO2004_NS); - rootAttributes.addNamespaceDeclaration("ooow", OfficeNamespaces.OOW2004_NS); - rootAttributes.addNamespaceDeclaration("oooc", OfficeNamespaces.OOC2004_NS); - rootAttributes.addNamespaceDeclaration("dom", OfficeNamespaces.XML_EVENT_NS); - rootAttributes.addNamespaceDeclaration("xforms", OfficeNamespaces.XFORMS_NS); - rootAttributes.addNamespaceDeclaration("xsd", OfficeNamespaces.XSD_NS); - rootAttributes.addNamespaceDeclaration("xsi", OfficeNamespaces.XSI_NS); - rootAttributes.setAttribute(OfficeNamespaces.OFFICE_NS, "version", "1.0"); - - this.rootXmlWriter.writeXmlDeclaration("UTF-8"); - this.rootXmlWriter.writeTag(OfficeNamespaces.OFFICE_NS, "document-content", rootAttributes, XmlWriterSupport.OPEN); - - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_DOCUMENT)); - - autoStyleNameGenerator.reset(); - tableNameGenerator.reset(); - frameNameGenerator.reset(); - - final OfficeDocument reportDoc = (OfficeDocument) report; - predefinedStylesCollection = reportDoc.getStylesCollection(); - - final OfficeStyles commonStyles = predefinedStylesCollection.getCommonStyles(); - if (!commonStyles.containsStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS)) - { - final OfficeStyle graphicsDefaultStyle = new OfficeStyle(); - graphicsDefaultStyle.setStyleFamily(OfficeToken.GRAPHIC); - graphicsDefaultStyle.setStyleName(OfficeToken.GRAPHICS); - final Element graphicProperties = produceFirstChild(graphicsDefaultStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES); - graphicProperties.setAttribute(OfficeNamespaces.TEXT_NS, "anchor-type", OfficeToken.PARAGRAPH); - graphicProperties.setAttribute(OfficeNamespaces.SVG_NS, "x", ZERO_CM); - graphicProperties.setAttribute(OfficeNamespaces.SVG_NS, "y", ZERO_CM); - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "wrap", "dynamic"); - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "number-wrapped-paragraphs", "no-limit"); - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "wrap-contour", OfficeToken.FALSE); - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, VERTICAL_POS, "from-top"); // changed for chart - - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "vertical-rel", OfficeToken.PARAGRAPH); - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, HORIZONTAL_POS, "from-left"); // changed for chart - - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "horizontal-rel", OfficeToken.PARAGRAPH); - commonStyles.addStyle(graphicsDefaultStyle); - } - - // Make sure that later generated styles do not overwrite existing styles. - fillStyleNameGenerator(predefinedStylesCollection); - - contentStylesCollection = new OfficeStylesCollection(); - globalStylesCollection = new OfficeStylesCollection(); - - startBuffering(contentStylesCollection, true); - } - catch (IOException e) - { - throw new ReportProcessingException(FAILED, e); - } - } - - protected AttributeNameGenerator getAutoStyleNameGenerator() - { - return autoStyleNameGenerator; - } - - private void fillStyleNameGenerator(final OfficeStylesCollection stylesCollection) - { - final OfficeStyles commonStyles = stylesCollection.getCommonStyles(); - final OfficeStyle[] allCommonStyles = commonStyles.getAllStyles(); - for (int i = 0; i < allCommonStyles.length; i++) - { - final OfficeStyle style = allCommonStyles[i]; - autoStyleNameGenerator.generateName(style.getStyleName()); - } - - final OfficeStyles autoStyles = stylesCollection.getAutomaticStyles(); - final OfficeStyle[] allAutoStyles = autoStyles.getAllStyles(); - for (int i = 0; i < allAutoStyles.length; i++) - { - final OfficeStyle style = allAutoStyles[i]; - autoStyleNameGenerator.generateName(style.getStyleName()); - } - } - - public OfficeStylesCollection getPredefinedStylesCollection() - { - return predefinedStylesCollection; - } - - public OfficeStylesCollection getGlobalStylesCollection() - { - return globalStylesCollection; - } - - public OfficeStylesCollection getContentStylesCollection() - { - return contentStylesCollection; - } - - /** - * Returns the XML-Writer tag description. This description defines whether an element can have character data inside. - * Such element will disable the indention, as in that case the additional whitespaces might alter the meaning of the - * element's contents. - * - * @return the tag description library. - */ - protected DefaultTagDescription createTagDescription() - { - final DefaultTagDescription tagDescription = new DefaultTagDescription(); - tagDescription.configure(JFreeReportBoot.getInstance().getGlobalConfig(), - OfficeDocumentReportTarget.TAG_DEF_PREFIX); - return tagDescription; - } - - /** - * Returns the current processing state. - * - * @return the processing state. - */ - protected int getCurrentState() - { - if (states.isEmpty()) - { - throw new IllegalStateException(); - } - final Integer o = (Integer) states.peek(); - return o.intValue(); - } - - /** - * Starts the processing of an element and updates the processing state. This will select an apropriate handler method - * for the call and will call one of the start* methods. - * - * @param attrs the attribute map for the current element - * @throws DataSourceException - * @throws ReportProcessingException - */ - public final void startElement(final AttributeMap attrs) - throws DataSourceException, ReportProcessingException - { - // todo - if (DEBUG_ELEMENTS) - { - Log.debug("Starting " + getCurrentState() + '/' + states.size() + ' ' + - ReportTargetUtil.getNamespaceFromAttribute(attrs) + " -> " + - ReportTargetUtil.getElemenTypeFromAttribute(attrs)); - } - try - { - switch (getCurrentState()) - { - case OfficeDocumentReportTarget.STATE_IN_DOCUMENT: - { - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OFFICE_NS, "body", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_BODY)); - startBody(attrs); - } - else - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER)); - if (!isFilteredNamespace(ReportTargetUtil.getNamespaceFromAttribute(attrs))) - { - startOther(attrs); - } - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_BODY: - { - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OFFICE_NS, "report", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_CONTENT)); - startContent(attrs); - } - else - { - throw new IllegalStateException("The 'office:body' element must have exactly one child of type 'report'"); - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_CONTENT: - { - // Either a ordinary section or a group .. - // A group. - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "report-body", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_BODY)); - startGroupBody(attrs); - } - else - { - // Either a template-section, page-header, page-footer, report-header, report-footer - // or variables-section - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION)); - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "template", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_TEMPLATE; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "page-header", attrs)) - { - if ("spreadsheet-section".equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "role"))) - { - currentRole = OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_HEADER; - } - else - { - currentRole = OfficeDocumentReportTarget.ROLE_PAGE_HEADER; - } - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "page-footer", attrs)) - { - if ("spreadsheet-section".equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "role"))) - { - currentRole = OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_FOOTER; - } - else - { - currentRole = OfficeDocumentReportTarget.ROLE_PAGE_FOOTER; - } - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "report-header", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_REPORT_HEADER; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "report-footer", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_REPORT_FOOTER; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES; - } - else - { - throw new IllegalStateException("Expected either 'template', 'report-body', " + - "'report-header', 'report-footer', 'variables-section', 'page-header' or 'page-footer'"); - } - startReportSection(attrs, currentRole); - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP_BODY: - { - // We now expect either an other group or a detail band. - - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP)); - groupContext = new GroupContext(groupContext); - startGroup(attrs); - } - else - { - // Either a variables-section, or a detail-band - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION)); - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "detail", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_DETAIL; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES; - } - else - { - throw new IllegalStateException("Expected either 'group', 'detail' or 'variables-section'"); - } - startReportSection(attrs, currentRole); - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP: - { - // A group can carry a repeating group header/footer or a group-instance section. - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "group-instance", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE)); - startGroupInstance(attrs); - } - else - { - // repeating group header/footer, but *no* variables section - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION)); - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-header", attrs) && - OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeated-section"))) - { - currentRole = OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-footer", attrs) && - OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeated-section"))) - { - currentRole = OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER; - } - else - { - throw new IllegalStateException("Expected either 'group-instance', " + - "'repeating group-header' or 'repeating group-footer'"); - } - startReportSection(attrs, currentRole); - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE: - { - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "group-body", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_BODY)); - startGroupBody(attrs); - } - else - { - // Either a group-header or group-footer or variables-section - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION)); - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-header", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_GROUP_HEADER; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-footer", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_GROUP_FOOTER; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES; - } - else - { - throw new IllegalStateException("Expected either 'group-body', 'group-header', 'group-footer' or 'variables-section'"); - } - startReportSection(attrs, currentRole); - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_SECTION: - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER)); - startOther(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_OTHER: - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER)); - startOther(attrs); - break; - } - default: - throw new IllegalStateException("Failure: " + getCurrentState()); - } - } - catch (IOException ioe) - { - Log.error("ReportProcessing failed", ioe); - throw new ReportProcessingException("Failed to write content", ioe); - } -// finally -// { -// Log.debug ("Started " + getNamespaceFromAttribute(attrs) + ":" + -// getElemenTypeFromAttribute(attrs) + " -> " + getCurrentState()); -// } - } - - protected GroupContext getGroupContext() - { - return groupContext; - } - - protected void performStyleProcessing(final AttributeMap attrs) - throws ReportProcessingException - { - final OfficeStylesCollection stylesCollection = getStylesCollection(); - final OfficeStylesCollection predefCollection = getPredefinedStylesCollection(); - final OfficeStylesCollection globalStylesCollection = getGlobalStylesCollection(); - - final String elementNamespace = - ReportTargetUtil.getNamespaceFromAttribute(attrs); - final String elementName = - ReportTargetUtil.getElemenTypeFromAttribute(attrs); - - final String[] namespaces = attrs.getNameSpaces(); - for (int i = 0; i < namespaces.length; i++) - { - final String attrNamespace = namespaces[i]; - if (isFilteredNamespace(attrNamespace)) - { - continue; - } - - final Map attributes = attrs.getAttributes(attrNamespace); - final Iterator iterator = attributes.entrySet().iterator(); - while (iterator.hasNext()) - { - final Map.Entry entry = (Map.Entry) iterator.next(); - final String attrName = (String) entry.getKey(); - final String attrValue = String.valueOf(entry.getValue()); - - final String styleFamily = styleMapper.getStyleFamilyFor(elementNamespace, elementName, attrNamespace, attrName); - if (styleFamily == null) - { - // None of the known style attributes. - continue; - } - - if (styleMapper.isListOfStyles(elementNamespace, elementName, attrNamespace, attrName)) - { - // ignored for now. - Log.warn("List of styles is not yet implemented."); - continue; - } - - // Copy styles is only called once per style. - StyleUtilities.copyStyle(styleFamily, attrValue, stylesCollection, globalStylesCollection, predefCollection); - } - } - } - - protected void startBody(final AttributeMap attrs) - throws IOException - { - getXmlWriter().writeTag(OfficeNamespaces.OFFICE_NS, "body", XmlWriterSupport.OPEN); - } - - private final boolean allowBuffering(final int role) - { - return (role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER || - role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER || - role == OfficeDocumentReportTarget.ROLE_TEMPLATE); - } - - protected void startReportSection(final AttributeMap attrs, final int role) - throws IOException, DataSourceException, ReportProcessingException - { - if (allowBuffering(role)) - { - startBuffering(new OfficeStylesCollection(), true); - } - } - - protected abstract void startContent(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException; - - protected void startGroup(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - final Object repeatingHeaderOrFooter = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeating-header-or-footer"); - if (OfficeToken.TRUE.equals(repeatingHeaderOrFooter)) - { - getGroupContext().setGroupWithRepeatingSection(true); - } - - final Object iterationCount = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "iteration-count"); - if (iterationCount instanceof Number) - { - final Number itNumber = (Number) iterationCount; - getGroupContext().setIterationCount(itNumber.intValue()); - } - } - - protected void startGroupInstance(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - } - - protected void startGroupBody(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - } - - protected abstract void startOther(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException; - - public void processText(final String text) - throws DataSourceException, ReportProcessingException - { - try - { - final XmlWriter xmlWriter = getXmlWriter(); - final LineBreakIterator lb = new LineBreakIterator(text); - while (lb.hasNext()) - { - final String line = (String) lb.next(); - final String normalizedText = XmlWriterSupport.normalize(line, false); - xmlWriter.writeText(normalizedText); - if (lb.hasNext()) - { - xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, "line-break", XmlWriterSupport.CLOSE); - } - } - } - catch (IOException e) - { - throw new ReportProcessingException(FAILED, e); - } - } - - protected boolean isFilteredNamespace(final String namespace) - { - if (Namespaces.LIBLAYOUT_NAMESPACE.equals(namespace)) - { - return true; - } - if (JFreeReportInfo.REPORT_NAMESPACE.equals(namespace)) - { - return true; - } - if (OfficeNamespaces.INTERNAL_NS.equals(namespace)) - { - return true; - } - if (JFreeReportInfo.COMPATIBILITY_NAMESPACE.equals(namespace)) - { - return true; - } - if (OfficeNamespaces.OOREPORT_NS.equals(namespace)) - { - return true; - } - return false; - } - - public void processContent(final DataFlags value) - throws DataSourceException, ReportProcessingException - { - final Object rawvalue = value.getValue(); - if (rawvalue == null) - { - return; - } - - // special handler for image (possibly also for URL ..) - if (rawvalue instanceof Image) - { - // do nothing yet. We should define something for that later .. - return; - } - - final XmlWriter xmlWriter = getXmlWriter(); - final String text = String.valueOf(rawvalue); - try - { - final LineBreakIterator lb = new LineBreakIterator(text); - while (lb.hasNext()) - { - final String line = (String) lb.next(); - final String normalizedText = XmlWriterSupport.normalize(line, false); - xmlWriter.writeText(normalizedText); - if (lb.hasNext()) - { - xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, "line-break", XmlWriterSupport.CLOSE); - } - } - } - catch (IOException e) - { - throw new ReportProcessingException(FAILED, e); - } - } - - public final void endElement(final AttributeMap attrs) - throws DataSourceException, ReportProcessingException - { - // final int oldState = getCurrentState(); - try - { - - switch (getCurrentState()) - { - case OfficeDocumentReportTarget.STATE_IN_OTHER: - { - endOther(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_SECTION: - { - endReportSection(attrs, currentRole); - currentRole = OfficeDocumentReportTarget.ROLE_NONE; - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP: - { - endGroup(attrs); - groupContext = groupContext.getParent(); - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE: - { - endGroupInstance(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP_BODY: - { - endGroupBody(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_CONTENT: - { - endContent(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_BODY: - { - endBody(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_DOCUMENT: - { - throw new IllegalStateException("This cannot be."); - } - default: - { - throw new IllegalStateException("Invalid state encountered."); - } - } - } - catch (IOException ioe) - { - throw new ReportProcessingException("IO Error while writing content", - ioe); - } finally - { - states.pop(); - - if (DEBUG_ELEMENTS) - { - Log.debug("Finished " + getCurrentState() + "/" + states.size() + " " + - ReportTargetUtil.getNamespaceFromAttribute(attrs) + ":" + - ReportTargetUtil.getElemenTypeFromAttribute(attrs)); - } - - } - } - - protected void endGroupBody(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - } - - protected void endGroupInstance(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - } - - public int getCurrentRole() - { - return currentRole; - } - - protected abstract void endOther(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException; - - protected void endReportSection(final AttributeMap attrs, - final int role) - throws IOException, DataSourceException, ReportProcessingException - { - if (allowBuffering(role)) - { - finishBuffering(); - } - } - - protected void endGroup(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - } - - protected abstract void endContent(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException; - - protected void endBody(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - getXmlWriter().writeCloseTag(); - } - - public void endReport(final ReportStructureRoot report) - throws DataSourceException, ReportProcessingException - { - if (xmlWriters.size() != 1) - { - throw new IllegalStateException("Invalid writer-stack state"); - } - - try - { - final StylesWriter inlineStylesWriter = new StylesWriter(rootXmlWriter); - inlineStylesWriter.writeContentStyles(predefinedStylesCollection, contentStylesCollection); - - final BufferState state = finishBuffering(); - this.rootXmlWriter.writeStream(state.getXmlAsReader()); - - final OutputStream stylesOutStream = - outputRepository.createOutputStream("styles.xml", "text/xml"); - final OutputStreamWriter osw = - new OutputStreamWriter(stylesOutStream, "UTF-8"); - final StylesWriter stylesWriter = new StylesWriter(osw); - stylesWriter.writeGlobalStyles(predefinedStylesCollection, globalStylesCollection); - stylesWriter.close(); - - this.rootXmlWriter.writeCloseTag(); - this.rootXmlWriter.close(); - } - catch (IOException e) - { - throw new ReportProcessingException(FAILED, e); - } - } - - public XmlWriter getXmlWriter() - { - final BufferState bufferState = (BufferState) xmlWriters.peek(); - return bufferState.getXmlWriter(); - } - - public OfficeStylesCollection getStylesCollection() - { - final BufferState bufferState = (BufferState) xmlWriters.peek(); - return bufferState.getStylesCollection(); - } - - public void startBuffering(final OfficeStylesCollection stylesCollection, - final boolean indent) throws ReportProcessingException - { - final XmlWriter currentWriter; - if (xmlWriters.isEmpty()) - { - currentWriter = rootXmlWriter; - } - else - { - final BufferState bufferState = (BufferState) xmlWriters.peek(); - currentWriter = bufferState.getXmlWriter(); - } - - try - { - final MemoryByteArrayOutputStream out = - new MemoryByteArrayOutputStream(INITIAL_BUFFER_SIZE, 256 * INITIAL_BUFFER_SIZE); - final DeflaterOutputStream deflateOut = new DeflaterOutputStream(out); - final OutputStreamWriter xmlBuffer = new OutputStreamWriter(deflateOut, "UTF-16"); - // final StringWriter xmlBuffer = new StringWriter - // (OfficeDocumentReportTarget.INITIAL_BUFFER_SIZE); - final XmlWriter contentXmlWriter = new XmlWriter(xmlBuffer, createTagDescription()); - contentXmlWriter.copyNamespaces(currentWriter); - if (indent) - { - contentXmlWriter.setAdditionalIndent(currentWriter.getCurrentIndentLevel()); - contentXmlWriter.setWriteFinalLinebreak(true); - } - else - { - contentXmlWriter.setWriteFinalLinebreak(false); - } - contentXmlWriter.setAlwaysAddNamespace(true); - xmlWriters.push(new BufferState(contentXmlWriter, out, stylesCollection)); - } - catch (IOException ioe) - { - throw new ReportProcessingException("Unable to create the buffer"); - } - } - - public BufferState finishBuffering() throws ReportProcessingException - { - final BufferState state = (BufferState) xmlWriters.pop(); - try - { - state.getXmlWriter().close(); - } - catch (IOException e) - { - Log.error("ReportProcessing failed", e); - } - return state; - } - - public void commit() - throws ReportProcessingException - { - // do not call flush before the report is fully finished. Every flush - // causes the Office-Backend to fully ZIP all contents (it acts like a - // 'Save' call from the UI) and that's expensive like hell - } - - public NamespaceDefinition getNamespaceByUri(final String uri) - { - return null; - } - - protected AttributeList buildAttributeList(final AttributeMap attrs) - { - final AttributeList attrList = new AttributeList(); - final String[] namespaces = attrs.getNameSpaces(); - for (int i = 0; i < namespaces.length; i++) - { - final String attrNamespace = namespaces[i]; - if (isFilteredNamespace(attrNamespace)) - { - continue; - } - - final Map localAttributes = attrs.getAttributes(attrNamespace); - final Iterator entries = localAttributes.entrySet().iterator(); - while (entries.hasNext()) - { - final Map.Entry entry = (Map.Entry) entries.next(); - final String key = String.valueOf(entry.getKey()); - if (OfficeNamespaces.TABLE_NS.equals(attrNamespace) && - "name".equals(key)) - { - final String tableName = String.valueOf(entry.getValue()); - final String saneName = sanitizeName(tableName); - attrList.setAttribute(attrNamespace, key, - tableNameGenerator.generateName(saneName)); - } - else if (OfficeNamespaces.DRAWING_NS.equals(attrNamespace) && - "name".equals(key)) - { - final String objectName = String.valueOf(entry.getValue()); - attrList.setAttribute(attrNamespace, key, - frameNameGenerator.generateName(objectName)); - } - else - { - attrList.setAttribute(attrNamespace, key, String.valueOf(entry.getValue())); - } - } - } - return attrList; - } - - protected String sanitizeName(final String name) - { - // A table name cannot contain spaces and should only contain - // ascii-characters. - if (name == null) - { - return ""; - } - final char[] chars = name.toCharArray(); - final StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < chars.length; i++) - { - final char aChar = chars[i]; - if (Character.isWhitespace(aChar)) - { - buffer.append('_'); - } - else - { - buffer.append(aChar); - } - } - return buffer.toString(); - } - - /** - * Returns the length in point. This method is f**king slow, it eats half of the processing time. I surely should - * replace it with something more efficient later. - * - * @param text - * @return - */ - protected CSSNumericValue parseLength(final String text) - { - if (styleSheetParserUtil == null) - { - styleSheetParserUtil = StyleSheetParserUtil.getInstance(); - } - - final LexicalUnit cssValue = styleSheetParserUtil.parseLexicalStyleValue( - text); - return CSSValueFactory.createLengthValue(cssValue); - } - - protected boolean isRepeatingSection() - { - return (currentRole == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER || - currentRole == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER || - currentRole == OfficeDocumentReportTarget.ROLE_PAGE_FOOTER || - currentRole == OfficeDocumentReportTarget.ROLE_PAGE_HEADER || - currentRole == OfficeDocumentReportTarget.ROLE_VARIABLES); - - } - - protected OfficeStyle deriveStyle(final String styleFamily, final String styleName) - throws ReportProcessingException - { - // autogenerate a style. The style has already been added to the current - // auto-collection. - final OfficeStyle style = StyleUtilities.deriveStyle(styleFamily, styleName, - getStylesCollection(), getGlobalStylesCollection(), - getPredefinedStylesCollection(), getAutoStyleNameGenerator()); - return style; - } - - protected void startImageProcessing(final AttributeMap attrs) - throws ReportProcessingException - { - final Object imageData = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.IMAGE_DATA); - final boolean preserveIRI = OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.PRESERVE_IRI)); - - // for the first shot, do nothing fancy .. - final ImageProducer.OfficeImage image = imageProducer.produceImage(imageData, preserveIRI); - if (image != null) - { - final ImageElementContext imageContext = (ImageElementContext) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "image-context"); - - // When scaling, we have to create an image-style. - final CSSNumericValue width = image.getWidth(); // always in 100th of a mm - - final CSSNumericValue height = image.getHeight(); // always in 100th of a mm - - Log.debug("Image " + imageData + " Width: " + width + ", Height: " + height); - if (width == null || height == null) - { - return; - } - - CSSNumericValue imageAreaWidthVal; - CSSNumericValue imageAreaHeightVal; - String styleName = null; - if (imageContext != null) - { - imageAreaWidthVal = computeImageWidth(imageContext); - imageAreaHeightVal = computeImageHeight(imageContext); - - if (imageAreaWidthVal == null || imageAreaHeightVal == null) - { - Log.debug("Image data returned from context is invalid. Maybe this is not an image?"); - return; - } - else - { - // compute the clip-area .. - final CSSNumericValue normalizedImageWidth = - CSSValueResolverUtility.convertLength(width, imageAreaWidthVal.getType()); - final CSSNumericValue normalizedImageHeight = - CSSValueResolverUtility.convertLength(height, imageAreaHeightVal.getType()); - - final boolean scale = OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.SCALE)); - if (!scale && normalizedImageWidth.getValue() > 0 && normalizedImageHeight.getValue() > 0) - { - final double clipWidth = normalizedImageWidth.getValue() - imageAreaWidthVal.getValue(); - final double clipHeight = normalizedImageHeight.getValue() - imageAreaHeightVal.getValue(); - if (clipWidth > 0 && clipHeight > 0) - { - final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS); - final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES); - final StringBuffer buffer = new StringBuffer(); - buffer.append("rect("); - buffer.append(clipHeight / 2); - buffer.append(imageAreaHeightVal.getType().getType()); - buffer.append(' '); - buffer.append(clipWidth / 2); - buffer.append(imageAreaWidthVal.getType().getType()); - buffer.append(' '); - buffer.append(clipHeight / 2); - buffer.append(imageAreaHeightVal.getType().getType()); - buffer.append(' '); - buffer.append(clipWidth / 2); - buffer.append(imageAreaWidthVal.getType().getType()); - buffer.append(')'); - graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString()); - - styleName = imageStyle.getStyleName(); - getStylesCollection().getAutomaticStyles().addStyle(imageStyle); - } - else if (clipWidth > 0) - { - final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS); - final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES); - final StringBuffer buffer = new StringBuffer(); - buffer.append("rect(0cm "); - buffer.append(clipWidth / 2); - buffer.append(imageAreaWidthVal.getType().getType()); - buffer.append(" 0cm "); - buffer.append(clipWidth / 2); - buffer.append(imageAreaWidthVal.getType().getType()); - buffer.append(')'); - graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString()); - - styleName = imageStyle.getStyleName(); - getStylesCollection().getAutomaticStyles().addStyle(imageStyle); - imageAreaHeightVal = normalizedImageHeight; - } - else if (clipHeight > 0) - { - final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS); - final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES); - final StringBuffer buffer = new StringBuffer(); - buffer.append("rect("); - buffer.append(clipHeight / 2); - buffer.append(imageAreaHeightVal.getType().getType()); - buffer.append(" 0cm "); - buffer.append(clipHeight / 2); - buffer.append(imageAreaHeightVal.getType().getType()); - buffer.append(" 0cm)"); - graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString()); - - styleName = imageStyle.getStyleName(); - getStylesCollection().getAutomaticStyles().addStyle(imageStyle); - imageAreaWidthVal = normalizedImageWidth; - } - else - { - imageAreaWidthVal = normalizedImageWidth; - imageAreaHeightVal = normalizedImageHeight; - } - } - } - // If we do scale, then we simply use the given image-area-size as valid image size and dont - // care about the image itself .. - } - else - { - Log.debug("There is no image-context, so we have to rely on the image's natural bounds. " + - "This may go awfully wrong."); - imageAreaWidthVal = image.getWidth(); - imageAreaHeightVal = image.getHeight(); - } - - final AttributeList frameList = new AttributeList(); - frameList.setAttribute(OfficeNamespaces.DRAWING_NS, "name", imageNames.generateName("Image")); - if (styleName != null) - { - frameList.setAttribute(OfficeNamespaces.DRAWING_NS, OfficeToken.STYLE_NAME, styleName); - } - frameList.setAttribute(OfficeNamespaces.TEXT_NS, "anchor-type", OfficeToken.PARAGRAPH); - frameList.setAttribute(OfficeNamespaces.SVG_NS, "z-index", "0"); - frameList.setAttribute(OfficeNamespaces.SVG_NS, "x", ZERO_CM); - frameList.setAttribute(OfficeNamespaces.SVG_NS, "y", ZERO_CM); - - Log.debug("Image " + imageData + " A-Width: " + imageAreaWidthVal + ", A-Height: " + imageAreaHeightVal); - - if (imageAreaWidthVal != null) - { - frameList.setAttribute(OfficeNamespaces.SVG_NS, - "width", imageAreaWidthVal.getValue() + imageAreaWidthVal.getType().getType()); - } - - if (imageAreaHeightVal != null) - { - frameList.setAttribute(OfficeNamespaces.SVG_NS, - "height", imageAreaHeightVal.getValue() + imageAreaHeightVal.getType().getType()); - } - - - final AttributeList imageList = new AttributeList(); - imageList.setAttribute(OfficeNamespaces.XLINK_NS, "href", image.getEmbeddableLink()); - imageList.setAttribute(OfficeNamespaces.XLINK_NS, "type", "simple"); - imageList.setAttribute(OfficeNamespaces.XLINK_NS, "show", "embed"); - imageList.setAttribute(OfficeNamespaces.XLINK_NS, "actuate", "onLoad"); - - - try - { - getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, "frame", frameList, XmlWriterSupport.OPEN); - getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, OfficeToken.IMAGE, imageList, XmlWriterSupport.CLOSE); - getXmlWriter().writeCloseTag(); - } - catch (IOException ioe) - { - throw new ReportProcessingException(FAILED, ioe); - } - } - } - - private CSSNumericValue computeImageWidth(final ImageElementContext imageElementContext) - { - final LengthCalculator calculator = new LengthCalculator(); - final String[] strings = imageElementContext.getColStyles(); - for (int i = 0; i < strings.length; i++) - { - final String styleName = strings[i]; - final CSSNumericValue value = computeColumnWidth(styleName); - if (value != null) - { - calculator.add(value); - } - } - return calculator.getResult(); - } - - private CSSNumericValue computeImageHeight(final ImageElementContext imageElementContext) - { - final LengthCalculator calculator = new LengthCalculator(); - final String[] strings = imageElementContext.getRowStyles(); - for (int i = 0; i < strings.length; i++) - { - final String styleName = strings[i]; - final CSSNumericValue value = computeRowHeight(styleName); - if (value != null) - { - calculator.add(value); - } - } - return calculator.getResult(); - } - - protected CSSNumericValue computeRowHeight(final String rowStyle) - { - final OfficeStylesCollection contentStyles = getContentStylesCollection(); - final OfficeStyle style = contentStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle); - if (style != null) - { - final Element element = style.getTableRowProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height"); - if (height != null) - { - return parseLength(height); - } - } - - final String styleParent = style.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - - final OfficeStylesCollection globalStyles = getGlobalStylesCollection(); - final OfficeStyle globalStyle = globalStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle); - if (globalStyle != null) - { - final Element element = globalStyle.getTableRowProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height"); - if (height != null) - { - return parseLength(height); - } - } - final String styleParent = globalStyle.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - - final OfficeStylesCollection predefStyles = getPredefinedStylesCollection(); - final OfficeStyle predefStyle = predefStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle); - if (predefStyle != null) - { - final Element element = predefStyle.getTableRowProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height"); - if (height != null) - { - return parseLength(height); - } - } - final String styleParent = predefStyle.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - // not found. - return null; - } - - protected CSSNumericValue computeColumnWidth(final String colStyle) - { - final OfficeStylesCollection contentStyles = getContentStylesCollection(); - final OfficeStyle style = contentStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle); - if (style != null) - { - final Element element = style.getTableColumnProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width"); - if (height != null) - { - return parseLength(height); - } - } - - final String styleParent = style.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - - final OfficeStylesCollection globalStyles = getGlobalStylesCollection(); - final OfficeStyle globalStyle = globalStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle); - if (globalStyle != null) - { - final Element element = globalStyle.getTableColumnProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width"); - if (height != null) - { - return parseLength(height); - } - } - final String styleParent = globalStyle.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - - final OfficeStylesCollection predefStyles = getPredefinedStylesCollection(); - final OfficeStyle predefStyle = predefStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle); - if (predefStyle != null) - { - final Element element = predefStyle.getTableColumnProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width"); - if (height != null) - { - return parseLength(height); - } - } - final String styleParent = predefStyle.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - // not found. - return null; - } - - protected Element produceFirstChild(final Section style, - final String nameSpace, - final String type) - { - Element paragraphProps = style.findFirstChild(nameSpace, type); - if (paragraphProps == null) - { - paragraphProps = new Section(); - paragraphProps.setNamespace(nameSpace); - paragraphProps.setType(type); - style.addNode(paragraphProps); - } - return paragraphProps; - } - - protected void startChartProcessing(final AttributeMap attrs) - throws ReportProcessingException - { - final String classId = (String) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "class-id"); - final String chartUrl = (String) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "href"); - final ArrayList masterColumns = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "master-columns"); - final ArrayList masterValues = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_VALUES); - final ArrayList detailColumns = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.DETAIL_COLUMNS); - final String href = oleProducer.produceOle(chartUrl, masterColumns, masterValues, detailColumns); - - final AttributeList oleList = new AttributeList(); - oleList.setAttribute(OfficeNamespaces.DRAWING_NS, "class-id", classId); - oleList.setAttribute(OfficeNamespaces.XLINK_NS, "href", "./" + href); - oleList.setAttribute(OfficeNamespaces.XLINK_NS, "type", "simple"); - oleList.setAttribute(OfficeNamespaces.XLINK_NS, "show", "embed"); - oleList.setAttribute(OfficeNamespaces.XLINK_NS, "actuate", "onLoad"); - - try - { - getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, OfficeToken.OBJECT_OLE, oleList, XmlWriterSupport.CLOSE); - } - catch (IOException ioe) - { - throw new ReportProcessingException(FAILED, ioe); - } - - - } -} +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeDocumentReportTarget.java,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.report.pentaho.output;
+
+import com.sun.star.report.DataSourceFactory;
+import java.awt.Image;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.zip.DeflaterOutputStream;
+import java.util.zip.InflaterInputStream;
+
+import com.sun.star.report.ImageService;
+import com.sun.star.report.InputRepository;
+import com.sun.star.report.OutputRepository;
+import com.sun.star.report.SDBCReportDataFactory;
+import com.sun.star.report.pentaho.OfficeNamespaces;
+import com.sun.star.report.OfficeToken;
+import com.sun.star.report.pentaho.layoutprocessor.ImageElementContext;
+import com.sun.star.report.pentaho.model.OfficeDocument;
+import com.sun.star.report.pentaho.model.OfficeStyle;
+import com.sun.star.report.pentaho.model.OfficeStyles;
+import com.sun.star.report.pentaho.model.OfficeStylesCollection;
+import com.sun.star.report.pentaho.styles.LengthCalculator;
+import com.sun.star.report.pentaho.styles.StyleMapper;
+import java.util.ArrayList;
+import org.jfree.io.IOUtils;
+import org.jfree.layouting.input.style.parser.CSSValueFactory;
+import org.jfree.layouting.input.style.parser.StyleSheetParserUtil;
+import org.jfree.layouting.input.style.values.CSSNumericValue;
+import org.jfree.layouting.layouter.style.CSSValueResolverUtility;
+import org.jfree.layouting.namespace.NamespaceDefinition;
+import org.jfree.layouting.namespace.Namespaces;
+import org.jfree.layouting.util.AttributeMap;
+import org.jfree.report.DataFlags;
+import org.jfree.report.DataSourceException;
+import org.jfree.report.JFreeReportBoot;
+import org.jfree.report.JFreeReportInfo;
+import org.jfree.report.ReportProcessingException;
+import org.jfree.report.flow.AbstractReportTarget;
+import org.jfree.report.flow.ReportJob;
+import org.jfree.report.flow.ReportStructureRoot;
+import org.jfree.report.flow.ReportTargetUtil;
+import org.jfree.report.structure.Element;
+import org.jfree.report.structure.Section;
+import org.jfree.report.util.AttributeNameGenerator;
+import org.jfree.report.util.IntegerCache;
+import org.jfree.report.util.MemoryByteArrayOutputStream;
+import org.jfree.resourceloader.ResourceException;
+import org.jfree.resourceloader.ResourceKey;
+import org.jfree.resourceloader.ResourceManager;
+import org.jfree.util.FastStack;
+import org.jfree.util.LineBreakIterator;
+import org.jfree.util.Log;
+import org.jfree.xmlns.common.AttributeList;
+import org.jfree.xmlns.writer.DefaultTagDescription;
+import org.jfree.xmlns.writer.XmlWriter;
+import org.jfree.xmlns.writer.XmlWriterSupport;
+import org.w3c.css.sac.LexicalUnit;
+
+/**
+ * Todo: Document me!
+ *
+ * @author Thomas Morgner
+ * @since 08.03.2007
+ */
+public abstract class OfficeDocumentReportTarget extends AbstractReportTarget
+{
+
+ public static final String HORIZONTAL_POS = "horizontal-pos";
+ public static final String TAG_DEF_PREFIX = "com.sun.star.report.pentaho.output.";
+ public static final int ROLE_NONE = 0;
+ public static final int ROLE_REPORT_HEADER = 1;
+ public static final int ROLE_REPORT_FOOTER = 2;
+ public static final int ROLE_GROUP_HEADER = 3;
+ public static final int ROLE_GROUP_FOOTER = 4;
+ public static final int ROLE_REPEATING_GROUP_HEADER = 5;
+ public static final int ROLE_REPEATING_GROUP_FOOTER = 6;
+ public static final int ROLE_PAGE_HEADER = 7;
+ public static final int ROLE_PAGE_FOOTER = 8;
+ public static final int ROLE_DETAIL = 9;
+ public static final int ROLE_VARIABLES = 10;
+ public static final int ROLE_TEMPLATE = 11;
+ public static final int ROLE_SPREADSHEET_PAGE_HEADER = 12;
+ public static final int ROLE_SPREADSHEET_PAGE_FOOTER = 13;
+ public static final int STATE_IN_DOCUMENT = 0;
+ public static final int STATE_IN_BODY = 1;
+ public static final int STATE_IN_CONTENT = 2;
+ public static final int STATE_IN_GROUP = 3;
+ public static final int STATE_IN_GROUP_BODY = 4;
+ public static final int STATE_IN_SECTION = 5;
+ public static final int STATE_IN_OTHER = 6;
+ public static final int STATE_IN_GROUP_INSTANCE = 7;
+ public static final String FAILED = "Failed";
+ public static final String VERTICAL_POS = "vertical-pos";
+ private static final String ZERO_CM = "0cm";
+
+ protected static class BufferState
+ {
+
+ private final XmlWriter xmlWriter;
+ private final MemoryByteArrayOutputStream xmlBuffer;
+ private final OfficeStylesCollection stylesCollection;
+
+ protected BufferState(final XmlWriter xmlWriter,
+ final MemoryByteArrayOutputStream xmlBuffer,
+ final OfficeStylesCollection stylesCollection)
+ {
+ this.stylesCollection = stylesCollection;
+ this.xmlWriter = xmlWriter;
+ this.xmlBuffer = xmlBuffer;
+ }
+
+ public OfficeStylesCollection getStylesCollection()
+ {
+ return stylesCollection;
+ }
+
+ public XmlWriter getXmlWriter()
+ {
+ return xmlWriter;
+ }
+
+ public String getXmlBuffer() throws ReportProcessingException
+ {
+ try
+ {
+ final byte[] zippedData = xmlBuffer.getRaw();
+ final InputStreamReader reader = new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(zippedData, 0, xmlBuffer.getLength())), "UTF-16");
+ final StringWriter writer = new StringWriter((zippedData.length / 2) + 1);
+ IOUtils.getInstance().copyWriter(reader, writer);
+ return writer.toString();
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException("Failed to copy buffer", e);
+ }
+ }
+
+ public Reader getXmlAsReader() throws ReportProcessingException
+ {
+ try
+ {
+ final byte[] zippedData = xmlBuffer.getRaw();
+ return new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(zippedData, 0, xmlBuffer.getLength())), "UTF-16");
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException("Failed to copy buffer", e);
+ }
+ }
+ }
+
+ protected static class GroupContext
+ {
+
+ private final GroupContext parent;
+ private int iterationCount;
+ private boolean groupWithRepeatingSection;
+
+ protected GroupContext(final GroupContext parent)
+ {
+ this.parent = parent;
+ }
+
+ public GroupContext getParent()
+ {
+ return parent;
+ }
+
+ public int getIterationCount()
+ {
+ return iterationCount;
+ }
+
+ public void setIterationCount(final int iterationCount)
+ {
+ this.iterationCount = iterationCount;
+ }
+
+ public boolean isGroupWithRepeatingSection()
+ {
+ return groupWithRepeatingSection;
+ }
+
+ public void setGroupWithRepeatingSection(final boolean groupWithRepeatingSection)
+ {
+ this.groupWithRepeatingSection = groupWithRepeatingSection;
+ }
+
+ public String toString()
+ {
+ return "GroupContext{" +
+ "parent=" + parent +
+ ", iterationCount=" + iterationCount +
+ ", groupWithRepeatingSection=" + groupWithRepeatingSection +
+ '}';
+ }
+ }
+ private final FastStack states;
+ private int currentRole;
+ private final FastStack xmlWriters;
+ private XmlWriter rootXmlWriter;
+ /**
+ * This styles-collection contains all styles that were predefined in the report definition file. The common styles
+ * and the master-styles will be written unmodified, the automatic styles will be ignored.
+ */
+ private OfficeStylesCollection predefinedStylesCollection;
+ /**
+ * This styles-collection contains all master-styles that have been generated by the report definition process. It
+ * also contains all automatic styles that have been generated for the page-bands (and the pagebands as well).
+ */
+ private OfficeStylesCollection globalStylesCollection;
+ /**
+ * The content styles collection contains all automatic styles that have been generated for the normal-flow content.
+ */
+ private OfficeStylesCollection contentStylesCollection;
+ private final OutputRepository outputRepository;
+ private final InputRepository inputRepository;
+ private final AttributeNameGenerator tableNameGenerator;
+ private final AttributeNameGenerator frameNameGenerator;
+ private final AttributeNameGenerator autoStyleNameGenerator;
+ private final String target;
+ private static final int INITIAL_BUFFER_SIZE = 40960;
+ private StyleMapper styleMapper;
+ private StyleSheetParserUtil styleSheetParserUtil;
+ private final AttributeNameGenerator imageNames;
+ private final ImageProducer imageProducer;
+ private final OleProducer oleProducer;
+ private GroupContext groupContext;
+ private static final boolean DEBUG_ELEMENTS =
+ JFreeReportBoot.getInstance().getExtendedConfig().getBoolProperty("com.sun.star.report.pentaho.output.DebugElements");
+
+ protected OfficeDocumentReportTarget(final ReportJob reportJob,
+ final ResourceManager resourceManager,
+ final ResourceKey baseResource,
+ final InputRepository inputRepository,
+ final OutputRepository outputRepository,
+ final String target,
+ final ImageService imageService,
+ final DataSourceFactory datasourcefactory)
+ throws ReportProcessingException
+ {
+ super(reportJob, resourceManager, baseResource);
+ if (imageService == null)
+ {
+ throw new NullPointerException("ImageService must not be null");
+ }
+ if (target == null)
+ {
+ throw new NullPointerException("Target-Name must not be null");
+ }
+
+ this.target = target;
+
+ this.tableNameGenerator = new AttributeNameGenerator();
+ this.frameNameGenerator = new AttributeNameGenerator();
+ this.autoStyleNameGenerator = new AttributeNameGenerator();
+ this.outputRepository = outputRepository;
+ this.inputRepository = inputRepository;
+ this.states = new FastStack();
+ this.xmlWriters = new FastStack();
+ this.imageNames = new AttributeNameGenerator();
+
+ this.imageProducer = new ImageProducer(inputRepository, outputRepository, imageService);
+ this.oleProducer = new OleProducer(inputRepository, outputRepository, imageService, datasourcefactory);
+
+ try
+ {
+ final ResourceManager realResourceManager = getResourceManager();
+ styleMapper = StyleMapper.loadInstance(realResourceManager);
+ }
+ catch (ResourceException e)
+ {
+ throw new ReportProcessingException("Failed to load style-mapper", e);
+ }
+ }
+
+ protected abstract String getTargetMimeType();
+
+ protected OutputRepository getOutputRepository()
+ {
+ return outputRepository;
+ }
+
+ protected InputRepository getInputRepository()
+ {
+ return inputRepository;
+ }
+
+ /**
+ * Starts the output of a new office document. This method writes the generic 'office:document-content' tag along with
+ * all known namespace declarations.
+ *
+ * @param report the report object.
+ * @throws DataSourceException if there was an error accessing the datasource
+ * @throws ReportProcessingException if some other error occured.
+ */
+ public void startReport(final ReportStructureRoot report)
+ throws DataSourceException, ReportProcessingException
+ {
+ imageNames.reset();
+ this.groupContext = new GroupContext(null);
+
+ final DefaultTagDescription tagDescription = createTagDescription();
+ try
+ {
+ final OutputStream outputStream = outputRepository.createOutputStream(target, "text/xml");
+ final Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
+
+ this.rootXmlWriter = new XmlWriter(writer, tagDescription);
+ this.rootXmlWriter.setAlwaysAddNamespace(true);
+
+ final AttributeList rootAttributes = new AttributeList();
+ rootAttributes.addNamespaceDeclaration("office", OfficeNamespaces.OFFICE_NS);
+ rootAttributes.addNamespaceDeclaration("style", OfficeNamespaces.STYLE_NS);
+ rootAttributes.addNamespaceDeclaration("text", OfficeNamespaces.TEXT_NS);
+ rootAttributes.addNamespaceDeclaration("table", OfficeNamespaces.TABLE_NS);
+ rootAttributes.addNamespaceDeclaration("draw", OfficeNamespaces.DRAWING_NS);
+ rootAttributes.addNamespaceDeclaration("fo", OfficeNamespaces.FO_NS);
+ rootAttributes.addNamespaceDeclaration("xlink", OfficeNamespaces.XLINK_NS);
+ rootAttributes.addNamespaceDeclaration("dc", OfficeNamespaces.PURL_NS);
+ rootAttributes.addNamespaceDeclaration("meta", OfficeNamespaces.META_NS);
+ rootAttributes.addNamespaceDeclaration("number", OfficeNamespaces.DATASTYLE_NS);
+ rootAttributes.addNamespaceDeclaration("svg", OfficeNamespaces.SVG_NS);
+ rootAttributes.addNamespaceDeclaration("chart", OfficeNamespaces.CHART_NS);
+ rootAttributes.addNamespaceDeclaration("dr3d", OfficeNamespaces.DR3D_NS);
+ rootAttributes.addNamespaceDeclaration("math", OfficeNamespaces.MATHML_NS);
+ rootAttributes.addNamespaceDeclaration("form", OfficeNamespaces.FORM_NS);
+ rootAttributes.addNamespaceDeclaration("script", OfficeNamespaces.SCRIPT_NS);
+ rootAttributes.addNamespaceDeclaration("ooo", OfficeNamespaces.OO2004_NS);
+ rootAttributes.addNamespaceDeclaration("ooow", OfficeNamespaces.OOW2004_NS);
+ rootAttributes.addNamespaceDeclaration("oooc", OfficeNamespaces.OOC2004_NS);
+ rootAttributes.addNamespaceDeclaration("dom", OfficeNamespaces.XML_EVENT_NS);
+ rootAttributes.addNamespaceDeclaration("xforms", OfficeNamespaces.XFORMS_NS);
+ rootAttributes.addNamespaceDeclaration("xsd", OfficeNamespaces.XSD_NS);
+ rootAttributes.addNamespaceDeclaration("xsi", OfficeNamespaces.XSI_NS);
+ rootAttributes.setAttribute(OfficeNamespaces.OFFICE_NS, "version", "1.0");
+
+ this.rootXmlWriter.writeXmlDeclaration("UTF-8");
+ this.rootXmlWriter.writeTag(OfficeNamespaces.OFFICE_NS, "document-content", rootAttributes, XmlWriterSupport.OPEN);
+
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_DOCUMENT));
+
+ autoStyleNameGenerator.reset();
+ tableNameGenerator.reset();
+ frameNameGenerator.reset();
+
+ final OfficeDocument reportDoc = (OfficeDocument) report;
+ predefinedStylesCollection = reportDoc.getStylesCollection();
+
+ final OfficeStyles commonStyles = predefinedStylesCollection.getCommonStyles();
+ if (!commonStyles.containsStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS))
+ {
+ final OfficeStyle graphicsDefaultStyle = new OfficeStyle();
+ graphicsDefaultStyle.setStyleFamily(OfficeToken.GRAPHIC);
+ graphicsDefaultStyle.setStyleName(OfficeToken.GRAPHICS);
+ final Element graphicProperties = produceFirstChild(graphicsDefaultStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES);
+ graphicProperties.setAttribute(OfficeNamespaces.TEXT_NS, "anchor-type", OfficeToken.PARAGRAPH);
+ graphicProperties.setAttribute(OfficeNamespaces.SVG_NS, "x", ZERO_CM);
+ graphicProperties.setAttribute(OfficeNamespaces.SVG_NS, "y", ZERO_CM);
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "wrap", "dynamic");
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "number-wrapped-paragraphs", "no-limit");
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "wrap-contour", OfficeToken.FALSE);
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, VERTICAL_POS, "from-top"); // changed for chart
+
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "vertical-rel", OfficeToken.PARAGRAPH);
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, HORIZONTAL_POS, "from-left"); // changed for chart
+
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "horizontal-rel", OfficeToken.PARAGRAPH);
+ commonStyles.addStyle(graphicsDefaultStyle);
+ }
+
+ // Make sure that later generated styles do not overwrite existing styles.
+ fillStyleNameGenerator(predefinedStylesCollection);
+
+ contentStylesCollection = new OfficeStylesCollection();
+ globalStylesCollection = new OfficeStylesCollection();
+
+ startBuffering(contentStylesCollection, true);
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException(FAILED, e);
+ }
+ }
+
+ protected AttributeNameGenerator getAutoStyleNameGenerator()
+ {
+ return autoStyleNameGenerator;
+ }
+
+ private void fillStyleNameGenerator(final OfficeStylesCollection stylesCollection)
+ {
+ final OfficeStyles commonStyles = stylesCollection.getCommonStyles();
+ final OfficeStyle[] allCommonStyles = commonStyles.getAllStyles();
+ for (int i = 0; i < allCommonStyles.length; i++)
+ {
+ final OfficeStyle style = allCommonStyles[i];
+ autoStyleNameGenerator.generateName(style.getStyleName());
+ }
+
+ final OfficeStyles autoStyles = stylesCollection.getAutomaticStyles();
+ final OfficeStyle[] allAutoStyles = autoStyles.getAllStyles();
+ for (int i = 0; i < allAutoStyles.length; i++)
+ {
+ final OfficeStyle style = allAutoStyles[i];
+ autoStyleNameGenerator.generateName(style.getStyleName());
+ }
+ }
+
+ public OfficeStylesCollection getPredefinedStylesCollection()
+ {
+ return predefinedStylesCollection;
+ }
+
+ public OfficeStylesCollection getGlobalStylesCollection()
+ {
+ return globalStylesCollection;
+ }
+
+ public OfficeStylesCollection getContentStylesCollection()
+ {
+ return contentStylesCollection;
+ }
+
+ /**
+ * Returns the XML-Writer tag description. This description defines whether an element can have character data inside.
+ * Such element will disable the indention, as in that case the additional whitespaces might alter the meaning of the
+ * element's contents.
+ *
+ * @return the tag description library.
+ */
+ protected DefaultTagDescription createTagDescription()
+ {
+ final DefaultTagDescription tagDescription = new DefaultTagDescription();
+ tagDescription.configure(JFreeReportBoot.getInstance().getGlobalConfig(),
+ OfficeDocumentReportTarget.TAG_DEF_PREFIX);
+ return tagDescription;
+ }
+
+ /**
+ * Returns the current processing state.
+ *
+ * @return the processing state.
+ */
+ protected int getCurrentState()
+ {
+ if (states.isEmpty())
+ {
+ throw new IllegalStateException();
+ }
+ final Integer o = (Integer) states.peek();
+ return o.intValue();
+ }
+
+ /**
+ * Starts the processing of an element and updates the processing state. This will select an apropriate handler method
+ * for the call and will call one of the start* methods.
+ *
+ * @param attrs the attribute map for the current element
+ * @throws DataSourceException
+ * @throws ReportProcessingException
+ */
+ public final void startElement(final AttributeMap attrs)
+ throws DataSourceException, ReportProcessingException
+ {
+ // todo
+ if (DEBUG_ELEMENTS)
+ {
+ Log.debug("Starting " + getCurrentState() + '/' + states.size() + ' ' +
+ ReportTargetUtil.getNamespaceFromAttribute(attrs) + " -> " +
+ ReportTargetUtil.getElemenTypeFromAttribute(attrs));
+ }
+ try
+ {
+ switch (getCurrentState())
+ {
+ case OfficeDocumentReportTarget.STATE_IN_DOCUMENT:
+ {
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OFFICE_NS, "body", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_BODY));
+ startBody(attrs);
+ }
+ else
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER));
+ if (!isFilteredNamespace(ReportTargetUtil.getNamespaceFromAttribute(attrs)))
+ {
+ startOther(attrs);
+ }
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_BODY:
+ {
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OFFICE_NS, "report", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_CONTENT));
+ startContent(attrs);
+ }
+ else
+ {
+ throw new IllegalStateException("The 'office:body' element must have exactly one child of type 'report'");
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_CONTENT:
+ {
+ // Either a ordinary section or a group ..
+ // A group.
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "report-body", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_BODY));
+ startGroupBody(attrs);
+ }
+ else
+ {
+ // Either a template-section, page-header, page-footer, report-header, report-footer
+ // or variables-section
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION));
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "template", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_TEMPLATE;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "page-header", attrs))
+ {
+ if ("spreadsheet-section".equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "role")))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_HEADER;
+ }
+ else
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_PAGE_HEADER;
+ }
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "page-footer", attrs))
+ {
+ if ("spreadsheet-section".equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "role")))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_FOOTER;
+ }
+ else
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_PAGE_FOOTER;
+ }
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "report-header", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_REPORT_HEADER;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "report-footer", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_REPORT_FOOTER;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES;
+ }
+ else
+ {
+ throw new IllegalStateException("Expected either 'template', 'report-body', " +
+ "'report-header', 'report-footer', 'variables-section', 'page-header' or 'page-footer'");
+ }
+ startReportSection(attrs, currentRole);
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP_BODY:
+ {
+ // We now expect either an other group or a detail band.
+
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP));
+ groupContext = new GroupContext(groupContext);
+ startGroup(attrs);
+ }
+ else
+ {
+ // Either a variables-section, or a detail-band
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION));
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "detail", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_DETAIL;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES;
+ }
+ else
+ {
+ throw new IllegalStateException("Expected either 'group', 'detail' or 'variables-section'");
+ }
+ startReportSection(attrs, currentRole);
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP:
+ {
+ // A group can carry a repeating group header/footer or a group-instance section.
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "group-instance", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE));
+ startGroupInstance(attrs);
+ }
+ else
+ {
+ // repeating group header/footer, but *no* variables section
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION));
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-header", attrs) &&
+ OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeated-section")))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-footer", attrs) &&
+ OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeated-section")))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER;
+ }
+ else
+ {
+ throw new IllegalStateException("Expected either 'group-instance', " +
+ "'repeating group-header' or 'repeating group-footer'");
+ }
+ startReportSection(attrs, currentRole);
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE:
+ {
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "group-body", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_BODY));
+ startGroupBody(attrs);
+ }
+ else
+ {
+ // Either a group-header or group-footer or variables-section
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION));
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-header", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_GROUP_HEADER;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-footer", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_GROUP_FOOTER;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES;
+ }
+ else
+ {
+ throw new IllegalStateException("Expected either 'group-body', 'group-header', 'group-footer' or 'variables-section'");
+ }
+ startReportSection(attrs, currentRole);
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_SECTION:
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER));
+ startOther(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_OTHER:
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER));
+ startOther(attrs);
+ break;
+ }
+ default:
+ throw new IllegalStateException("Failure: " + getCurrentState());
+ }
+ }
+ catch (IOException ioe)
+ {
+ Log.error("ReportProcessing failed", ioe);
+ throw new ReportProcessingException("Failed to write content", ioe);
+ }
+// finally
+// {
+// Log.debug ("Started " + getNamespaceFromAttribute(attrs) + ":" +
+// getElemenTypeFromAttribute(attrs) + " -> " + getCurrentState());
+// }
+ }
+
+ protected GroupContext getGroupContext()
+ {
+ return groupContext;
+ }
+
+ protected void performStyleProcessing(final AttributeMap attrs)
+ throws ReportProcessingException
+ {
+ final OfficeStylesCollection stylesCollection = getStylesCollection();
+ final OfficeStylesCollection predefCollection = getPredefinedStylesCollection();
+ final OfficeStylesCollection globalStylesCollection = getGlobalStylesCollection();
+
+ final String elementNamespace =
+ ReportTargetUtil.getNamespaceFromAttribute(attrs);
+ final String elementName =
+ ReportTargetUtil.getElemenTypeFromAttribute(attrs);
+
+ final String[] namespaces = attrs.getNameSpaces();
+ for (int i = 0; i < namespaces.length; i++)
+ {
+ final String attrNamespace = namespaces[i];
+ if (isFilteredNamespace(attrNamespace))
+ {
+ continue;
+ }
+
+ final Map attributes = attrs.getAttributes(attrNamespace);
+ final Iterator iterator = attributes.entrySet().iterator();
+ while (iterator.hasNext())
+ {
+ final Map.Entry entry = (Map.Entry) iterator.next();
+ final String attrName = (String) entry.getKey();
+ final String attrValue = String.valueOf(entry.getValue());
+
+ final String styleFamily = styleMapper.getStyleFamilyFor(elementNamespace, elementName, attrNamespace, attrName);
+ if (styleFamily == null)
+ {
+ // None of the known style attributes.
+ continue;
+ }
+
+ if (styleMapper.isListOfStyles(elementNamespace, elementName, attrNamespace, attrName))
+ {
+ // ignored for now.
+ Log.warn("List of styles is not yet implemented.");
+ continue;
+ }
+
+ // Copy styles is only called once per style.
+ StyleUtilities.copyStyle(styleFamily, attrValue, stylesCollection, globalStylesCollection, predefCollection);
+ }
+ }
+ }
+
+ protected void startBody(final AttributeMap attrs)
+ throws IOException
+ {
+ getXmlWriter().writeTag(OfficeNamespaces.OFFICE_NS, "body", XmlWriterSupport.OPEN);
+ }
+
+ private final boolean allowBuffering(final int role)
+ {
+ return (role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER ||
+ role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER ||
+ role == OfficeDocumentReportTarget.ROLE_TEMPLATE);
+ }
+
+ protected void startReportSection(final AttributeMap attrs, final int role)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ if (allowBuffering(role))
+ {
+ startBuffering(new OfficeStylesCollection(), true);
+ }
+ }
+
+ protected abstract void startContent(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException;
+
+ protected void startGroup(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ final Object repeatingHeaderOrFooter = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeating-header-or-footer");
+ if (OfficeToken.TRUE.equals(repeatingHeaderOrFooter))
+ {
+ getGroupContext().setGroupWithRepeatingSection(true);
+ }
+
+ final Object iterationCount = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "iteration-count");
+ if (iterationCount instanceof Number)
+ {
+ final Number itNumber = (Number) iterationCount;
+ getGroupContext().setIterationCount(itNumber.intValue());
+ }
+ }
+
+ protected void startGroupInstance(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ }
+
+ protected void startGroupBody(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ }
+
+ protected abstract void startOther(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException;
+
+ public void processText(final String text)
+ throws DataSourceException, ReportProcessingException
+ {
+ try
+ {
+ final XmlWriter xmlWriter = getXmlWriter();
+ final LineBreakIterator lb = new LineBreakIterator(text);
+ while (lb.hasNext())
+ {
+ final String line = (String) lb.next();
+ final String normalizedText = XmlWriterSupport.normalize(line, false);
+ xmlWriter.writeText(normalizedText);
+ if (lb.hasNext())
+ {
+ xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, "line-break", XmlWriterSupport.CLOSE);
+ }
+ }
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException(FAILED, e);
+ }
+ }
+
+ protected boolean isFilteredNamespace(final String namespace)
+ {
+ if (Namespaces.LIBLAYOUT_NAMESPACE.equals(namespace))
+ {
+ return true;
+ }
+ if (JFreeReportInfo.REPORT_NAMESPACE.equals(namespace))
+ {
+ return true;
+ }
+ if (OfficeNamespaces.INTERNAL_NS.equals(namespace))
+ {
+ return true;
+ }
+ if (JFreeReportInfo.COMPATIBILITY_NAMESPACE.equals(namespace))
+ {
+ return true;
+ }
+ if (OfficeNamespaces.OOREPORT_NS.equals(namespace))
+ {
+ return true;
+ }
+ return false;
+ }
+
+ public void processContent(final DataFlags value)
+ throws DataSourceException, ReportProcessingException
+ {
+ final Object rawvalue = value.getValue();
+ if (rawvalue == null)
+ {
+ return;
+ }
+
+ // special handler for image (possibly also for URL ..)
+ if (rawvalue instanceof Image)
+ {
+ // do nothing yet. We should define something for that later ..
+ return;
+ }
+
+ final XmlWriter xmlWriter = getXmlWriter();
+ final String text = String.valueOf(rawvalue);
+ try
+ {
+ final LineBreakIterator lb = new LineBreakIterator(text);
+ while (lb.hasNext())
+ {
+ final String line = (String) lb.next();
+ final String normalizedText = XmlWriterSupport.normalize(line, false);
+ xmlWriter.writeText(normalizedText);
+ if (lb.hasNext())
+ {
+ xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, "line-break", XmlWriterSupport.CLOSE);
+ }
+ }
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException(FAILED, e);
+ }
+ }
+
+ public final void endElement(final AttributeMap attrs)
+ throws DataSourceException, ReportProcessingException
+ {
+ // final int oldState = getCurrentState();
+ try
+ {
+
+ switch (getCurrentState())
+ {
+ case OfficeDocumentReportTarget.STATE_IN_OTHER:
+ {
+ endOther(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_SECTION:
+ {
+ endReportSection(attrs, currentRole);
+ currentRole = OfficeDocumentReportTarget.ROLE_NONE;
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP:
+ {
+ endGroup(attrs);
+ groupContext = groupContext.getParent();
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE:
+ {
+ endGroupInstance(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP_BODY:
+ {
+ endGroupBody(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_CONTENT:
+ {
+ endContent(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_BODY:
+ {
+ endBody(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_DOCUMENT:
+ {
+ throw new IllegalStateException("This cannot be.");
+ }
+ default:
+ {
+ throw new IllegalStateException("Invalid state encountered.");
+ }
+ }
+ }
+ catch (IOException ioe)
+ {
+ throw new ReportProcessingException("IO Error while writing content",
+ ioe);
+ } finally
+ {
+ states.pop();
+
+ if (DEBUG_ELEMENTS)
+ {
+ Log.debug("Finished " + getCurrentState() + "/" + states.size() + " " +
+ ReportTargetUtil.getNamespaceFromAttribute(attrs) + ":" +
+ ReportTargetUtil.getElemenTypeFromAttribute(attrs));
+ }
+
+ }
+ }
+
+ protected void endGroupBody(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ }
+
+ protected void endGroupInstance(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ }
+
+ public int getCurrentRole()
+ {
+ return currentRole;
+ }
+
+ protected abstract void endOther(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException;
+
+ protected void endReportSection(final AttributeMap attrs,
+ final int role)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ if (allowBuffering(role))
+ {
+ finishBuffering();
+ }
+ }
+
+ protected void endGroup(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ }
+
+ protected abstract void endContent(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException;
+
+ protected void endBody(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ getXmlWriter().writeCloseTag();
+ }
+
+ public void endReport(final ReportStructureRoot report)
+ throws DataSourceException, ReportProcessingException
+ {
+ if (xmlWriters.size() != 1)
+ {
+ throw new IllegalStateException("Invalid writer-stack state");
+ }
+
+ try
+ {
+ final StylesWriter inlineStylesWriter = new StylesWriter(rootXmlWriter);
+ inlineStylesWriter.writeContentStyles(predefinedStylesCollection, contentStylesCollection);
+
+ final BufferState state = finishBuffering();
+ this.rootXmlWriter.writeStream(state.getXmlAsReader());
+
+ final OutputStream stylesOutStream =
+ outputRepository.createOutputStream("styles.xml", "text/xml");
+ final OutputStreamWriter osw =
+ new OutputStreamWriter(stylesOutStream, "UTF-8");
+ final StylesWriter stylesWriter = new StylesWriter(osw);
+ stylesWriter.writeGlobalStyles(predefinedStylesCollection, globalStylesCollection);
+ stylesWriter.close();
+
+ this.rootXmlWriter.writeCloseTag();
+ this.rootXmlWriter.close();
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException(FAILED, e);
+ }
+ }
+
+ public XmlWriter getXmlWriter()
+ {
+ final BufferState bufferState = (BufferState) xmlWriters.peek();
+ return bufferState.getXmlWriter();
+ }
+
+ public OfficeStylesCollection getStylesCollection()
+ {
+ final BufferState bufferState = (BufferState) xmlWriters.peek();
+ return bufferState.getStylesCollection();
+ }
+
+ public void startBuffering(final OfficeStylesCollection stylesCollection,
+ final boolean indent) throws ReportProcessingException
+ {
+ final XmlWriter currentWriter;
+ if (xmlWriters.isEmpty())
+ {
+ currentWriter = rootXmlWriter;
+ }
+ else
+ {
+ final BufferState bufferState = (BufferState) xmlWriters.peek();
+ currentWriter = bufferState.getXmlWriter();
+ }
+
+ try
+ {
+ final MemoryByteArrayOutputStream out =
+ new MemoryByteArrayOutputStream(INITIAL_BUFFER_SIZE, 256 * INITIAL_BUFFER_SIZE);
+ final DeflaterOutputStream deflateOut = new DeflaterOutputStream(out);
+ final OutputStreamWriter xmlBuffer = new OutputStreamWriter(deflateOut, "UTF-16");
+ // final StringWriter xmlBuffer = new StringWriter
+ // (OfficeDocumentReportTarget.INITIAL_BUFFER_SIZE);
+ final XmlWriter contentXmlWriter = new XmlWriter(xmlBuffer, createTagDescription());
+ contentXmlWriter.copyNamespaces(currentWriter);
+ if (indent)
+ {
+ contentXmlWriter.setAdditionalIndent(currentWriter.getCurrentIndentLevel());
+ contentXmlWriter.setWriteFinalLinebreak(true);
+ }
+ else
+ {
+ contentXmlWriter.setWriteFinalLinebreak(false);
+ }
+ contentXmlWriter.setAlwaysAddNamespace(true);
+ xmlWriters.push(new BufferState(contentXmlWriter, out, stylesCollection));
+ }
+ catch (IOException ioe)
+ {
+ throw new ReportProcessingException("Unable to create the buffer");
+ }
+ }
+
+ public BufferState finishBuffering() throws ReportProcessingException
+ {
+ final BufferState state = (BufferState) xmlWriters.pop();
+ try
+ {
+ state.getXmlWriter().close();
+ }
+ catch (IOException e)
+ {
+ Log.error("ReportProcessing failed", e);
+ }
+ return state;
+ }
+
+ public void commit()
+ throws ReportProcessingException
+ {
+ // do not call flush before the report is fully finished. Every flush
+ // causes the Office-Backend to fully ZIP all contents (it acts like a
+ // 'Save' call from the UI) and that's expensive like hell
+ }
+
+ public NamespaceDefinition getNamespaceByUri(final String uri)
+ {
+ return null;
+ }
+
+ protected AttributeList buildAttributeList(final AttributeMap attrs)
+ {
+ final AttributeList attrList = new AttributeList();
+ final String[] namespaces = attrs.getNameSpaces();
+ for (int i = 0; i < namespaces.length; i++)
+ {
+ final String attrNamespace = namespaces[i];
+ if (isFilteredNamespace(attrNamespace))
+ {
+ continue;
+ }
+
+ final Map localAttributes = attrs.getAttributes(attrNamespace);
+ final Iterator entries = localAttributes.entrySet().iterator();
+ while (entries.hasNext())
+ {
+ final Map.Entry entry = (Map.Entry) entries.next();
+ final String key = String.valueOf(entry.getKey());
+ if (OfficeNamespaces.TABLE_NS.equals(attrNamespace) &&
+ "name".equals(key))
+ {
+ final String tableName = String.valueOf(entry.getValue());
+ final String saneName = sanitizeName(tableName);
+ attrList.setAttribute(attrNamespace, key,
+ tableNameGenerator.generateName(saneName));
+ }
+ else if (OfficeNamespaces.DRAWING_NS.equals(attrNamespace) &&
+ "name".equals(key))
+ {
+ final String objectName = String.valueOf(entry.getValue());
+ attrList.setAttribute(attrNamespace, key,
+ frameNameGenerator.generateName(objectName));
+ }
+ else
+ {
+ attrList.setAttribute(attrNamespace, key, String.valueOf(entry.getValue()));
+ }
+ }
+ }
+ return attrList;
+ }
+
+ protected String sanitizeName(final String name)
+ {
+ // A table name cannot contain spaces and should only contain
+ // ascii-characters.
+ if (name == null)
+ {
+ return "";
+ }
+ final char[] chars = name.toCharArray();
+ final StringBuffer buffer = new StringBuffer();
+ for (int i = 0; i < chars.length; i++)
+ {
+ final char aChar = chars[i];
+ if (Character.isWhitespace(aChar))
+ {
+ buffer.append('_');
+ }
+ else
+ {
+ buffer.append(aChar);
+ }
+ }
+ return buffer.toString();
+ }
+
+ /**
+ * Returns the length in point. This method is f**king slow, it eats half of the processing time. I surely should
+ * replace it with something more efficient later.
+ *
+ * @param text
+ * @return
+ */
+ protected CSSNumericValue parseLength(final String text)
+ {
+ if (styleSheetParserUtil == null)
+ {
+ styleSheetParserUtil = StyleSheetParserUtil.getInstance();
+ }
+
+ final LexicalUnit cssValue = styleSheetParserUtil.parseLexicalStyleValue(
+ text);
+ return CSSValueFactory.createLengthValue(cssValue);
+ }
+
+ protected boolean isRepeatingSection()
+ {
+ return (currentRole == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER ||
+ currentRole == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER ||
+ currentRole == OfficeDocumentReportTarget.ROLE_PAGE_FOOTER ||
+ currentRole == OfficeDocumentReportTarget.ROLE_PAGE_HEADER ||
+ currentRole == OfficeDocumentReportTarget.ROLE_VARIABLES);
+
+ }
+
+ protected OfficeStyle deriveStyle(final String styleFamily, final String styleName)
+ throws ReportProcessingException
+ {
+ // autogenerate a style. The style has already been added to the current
+ // auto-collection.
+ final OfficeStyle style = StyleUtilities.deriveStyle(styleFamily, styleName,
+ getStylesCollection(), getGlobalStylesCollection(),
+ getPredefinedStylesCollection(), getAutoStyleNameGenerator());
+ return style;
+ }
+
+ protected void startImageProcessing(final AttributeMap attrs)
+ throws ReportProcessingException
+ {
+ final Object imageData = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.IMAGE_DATA);
+ final boolean preserveIRI = OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.PRESERVE_IRI));
+
+ // for the first shot, do nothing fancy ..
+ final ImageProducer.OfficeImage image = imageProducer.produceImage(imageData, preserveIRI);
+ if (image != null)
+ {
+ final ImageElementContext imageContext = (ImageElementContext) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "image-context");
+
+ // When scaling, we have to create an image-style.
+ final CSSNumericValue width = image.getWidth(); // always in 100th of a mm
+
+ final CSSNumericValue height = image.getHeight(); // always in 100th of a mm
+
+ Log.debug("Image " + imageData + " Width: " + width + ", Height: " + height);
+ if (width == null || height == null)
+ {
+ return;
+ }
+
+ CSSNumericValue imageAreaWidthVal;
+ CSSNumericValue imageAreaHeightVal;
+ String styleName = null;
+ if (imageContext != null)
+ {
+ imageAreaWidthVal = computeImageWidth(imageContext);
+ imageAreaHeightVal = computeImageHeight(imageContext);
+
+ if (imageAreaWidthVal == null || imageAreaHeightVal == null)
+ {
+ Log.debug("Image data returned from context is invalid. Maybe this is not an image?");
+ return;
+ }
+ else
+ {
+ // compute the clip-area ..
+ final CSSNumericValue normalizedImageWidth =
+ CSSValueResolverUtility.convertLength(width, imageAreaWidthVal.getType());
+ final CSSNumericValue normalizedImageHeight =
+ CSSValueResolverUtility.convertLength(height, imageAreaHeightVal.getType());
+
+ final boolean scale = OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.SCALE));
+ if (!scale && normalizedImageWidth.getValue() > 0 && normalizedImageHeight.getValue() > 0)
+ {
+ final double clipWidth = normalizedImageWidth.getValue() - imageAreaWidthVal.getValue();
+ final double clipHeight = normalizedImageHeight.getValue() - imageAreaHeightVal.getValue();
+ if (clipWidth > 0 && clipHeight > 0)
+ {
+ final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS);
+ final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES);
+ final StringBuffer buffer = new StringBuffer();
+ buffer.append("rect(");
+ buffer.append(clipHeight / 2);
+ buffer.append(imageAreaHeightVal.getType().getType());
+ buffer.append(' ');
+ buffer.append(clipWidth / 2);
+ buffer.append(imageAreaWidthVal.getType().getType());
+ buffer.append(' ');
+ buffer.append(clipHeight / 2);
+ buffer.append(imageAreaHeightVal.getType().getType());
+ buffer.append(' ');
+ buffer.append(clipWidth / 2);
+ buffer.append(imageAreaWidthVal.getType().getType());
+ buffer.append(')');
+ graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString());
+
+ styleName = imageStyle.getStyleName();
+ getStylesCollection().getAutomaticStyles().addStyle(imageStyle);
+ }
+ else if (clipWidth > 0)
+ {
+ final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS);
+ final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES);
+ final StringBuffer buffer = new StringBuffer();
+ buffer.append("rect(0cm ");
+ buffer.append(clipWidth / 2);
+ buffer.append(imageAreaWidthVal.getType().getType());
+ buffer.append(" 0cm ");
+ buffer.append(clipWidth / 2);
+ buffer.append(imageAreaWidthVal.getType().getType());
+ buffer.append(')');
+ graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString());
+
+ styleName = imageStyle.getStyleName();
+ getStylesCollection().getAutomaticStyles().addStyle(imageStyle);
+ imageAreaHeightVal = normalizedImageHeight;
+ }
+ else if (clipHeight > 0)
+ {
+ final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS);
+ final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES);
+ final StringBuffer buffer = new StringBuffer();
+ buffer.append("rect(");
+ buffer.append(clipHeight / 2);
+ buffer.append(imageAreaHeightVal.getType().getType());
+ buffer.append(" 0cm ");
+ buffer.append(clipHeight / 2);
+ buffer.append(imageAreaHeightVal.getType().getType());
+ buffer.append(" 0cm)");
+ graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString());
+
+ styleName = imageStyle.getStyleName();
+ getStylesCollection().getAutomaticStyles().addStyle(imageStyle);
+ imageAreaWidthVal = normalizedImageWidth;
+ }
+ else
+ {
+ imageAreaWidthVal = normalizedImageWidth;
+ imageAreaHeightVal = normalizedImageHeight;
+ }
+ }
+ }
+ // If we do scale, then we simply use the given image-area-size as valid image size and dont
+ // care about the image itself ..
+ }
+ else
+ {
+ Log.debug("There is no image-context, so we have to rely on the image's natural bounds. " +
+ "This may go awfully wrong.");
+ imageAreaWidthVal = image.getWidth();
+ imageAreaHeightVal = image.getHeight();
+ }
+
+ final AttributeList frameList = new AttributeList();
+ frameList.setAttribute(OfficeNamespaces.DRAWING_NS, "name", imageNames.generateName("Image"));
+ if (styleName != null)
+ {
+ frameList.setAttribute(OfficeNamespaces.DRAWING_NS, OfficeToken.STYLE_NAME, styleName);
+ }
+ frameList.setAttribute(OfficeNamespaces.TEXT_NS, "anchor-type", OfficeToken.PARAGRAPH);
+ frameList.setAttribute(OfficeNamespaces.SVG_NS, "z-index", "0");
+ frameList.setAttribute(OfficeNamespaces.SVG_NS, "x", ZERO_CM);
+ frameList.setAttribute(OfficeNamespaces.SVG_NS, "y", ZERO_CM);
+
+ Log.debug("Image " + imageData + " A-Width: " + imageAreaWidthVal + ", A-Height: " + imageAreaHeightVal);
+
+ if (imageAreaWidthVal != null)
+ {
+ frameList.setAttribute(OfficeNamespaces.SVG_NS,
+ "width", imageAreaWidthVal.getValue() + imageAreaWidthVal.getType().getType());
+ }
+
+ if (imageAreaHeightVal != null)
+ {
+ frameList.setAttribute(OfficeNamespaces.SVG_NS,
+ "height", imageAreaHeightVal.getValue() + imageAreaHeightVal.getType().getType());
+ }
+
+
+ final AttributeList imageList = new AttributeList();
+ imageList.setAttribute(OfficeNamespaces.XLINK_NS, "href", image.getEmbeddableLink());
+ imageList.setAttribute(OfficeNamespaces.XLINK_NS, "type", "simple");
+ imageList.setAttribute(OfficeNamespaces.XLINK_NS, "show", "embed");
+ imageList.setAttribute(OfficeNamespaces.XLINK_NS, "actuate", "onLoad");
+
+
+ try
+ {
+ getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, "frame", frameList, XmlWriterSupport.OPEN);
+ getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, OfficeToken.IMAGE, imageList, XmlWriterSupport.CLOSE);
+ getXmlWriter().writeCloseTag();
+ }
+ catch (IOException ioe)
+ {
+ throw new ReportProcessingException(FAILED, ioe);
+ }
+ }
+ }
+
+ private CSSNumericValue computeImageWidth(final ImageElementContext imageElementContext)
+ {
+ final LengthCalculator calculator = new LengthCalculator();
+ final String[] strings = imageElementContext.getColStyles();
+ for (int i = 0; i < strings.length; i++)
+ {
+ final String styleName = strings[i];
+ final CSSNumericValue value = computeColumnWidth(styleName);
+ if (value != null)
+ {
+ calculator.add(value);
+ }
+ }
+ return calculator.getResult();
+ }
+
+ private CSSNumericValue computeImageHeight(final ImageElementContext imageElementContext)
+ {
+ final LengthCalculator calculator = new LengthCalculator();
+ final String[] strings = imageElementContext.getRowStyles();
+ for (int i = 0; i < strings.length; i++)
+ {
+ final String styleName = strings[i];
+ final CSSNumericValue value = computeRowHeight(styleName);
+ if (value != null)
+ {
+ calculator.add(value);
+ }
+ }
+ return calculator.getResult();
+ }
+
+ protected CSSNumericValue computeRowHeight(final String rowStyle)
+ {
+ final OfficeStylesCollection contentStyles = getContentStylesCollection();
+ final OfficeStyle style = contentStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle);
+ if (style != null)
+ {
+ final Element element = style.getTableRowProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+
+ final String styleParent = style.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+
+ final OfficeStylesCollection globalStyles = getGlobalStylesCollection();
+ final OfficeStyle globalStyle = globalStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle);
+ if (globalStyle != null)
+ {
+ final Element element = globalStyle.getTableRowProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+ final String styleParent = globalStyle.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+
+ final OfficeStylesCollection predefStyles = getPredefinedStylesCollection();
+ final OfficeStyle predefStyle = predefStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle);
+ if (predefStyle != null)
+ {
+ final Element element = predefStyle.getTableRowProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+ final String styleParent = predefStyle.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+ // not found.
+ return null;
+ }
+
+ protected CSSNumericValue computeColumnWidth(final String colStyle)
+ {
+ final OfficeStylesCollection contentStyles = getContentStylesCollection();
+ final OfficeStyle style = contentStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle);
+ if (style != null)
+ {
+ final Element element = style.getTableColumnProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+
+ final String styleParent = style.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+
+ final OfficeStylesCollection globalStyles = getGlobalStylesCollection();
+ final OfficeStyle globalStyle = globalStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle);
+ if (globalStyle != null)
+ {
+ final Element element = globalStyle.getTableColumnProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+ final String styleParent = globalStyle.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+
+ final OfficeStylesCollection predefStyles = getPredefinedStylesCollection();
+ final OfficeStyle predefStyle = predefStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle);
+ if (predefStyle != null)
+ {
+ final Element element = predefStyle.getTableColumnProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+ final String styleParent = predefStyle.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+ // not found.
+ return null;
+ }
+
+ protected Element produceFirstChild(final Section style,
+ final String nameSpace,
+ final String type)
+ {
+ Element paragraphProps = style.findFirstChild(nameSpace, type);
+ if (paragraphProps == null)
+ {
+ paragraphProps = new Section();
+ paragraphProps.setNamespace(nameSpace);
+ paragraphProps.setType(type);
+ style.addNode(paragraphProps);
+ }
+ return paragraphProps;
+ }
+
+ protected void startChartProcessing(final AttributeMap attrs)
+ throws ReportProcessingException
+ {
+ final String classId = (String) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "class-id");
+ final String chartUrl = (String) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "href");
+ final ArrayList masterColumns = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_COLUMNS);
+ final ArrayList masterValues = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_VALUES);
+ final ArrayList detailColumns = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.DETAIL_COLUMNS);
+ final String href = oleProducer.produceOle(chartUrl, masterColumns, masterValues, detailColumns);
+
+ final AttributeList oleList = new AttributeList();
+ oleList.setAttribute(OfficeNamespaces.DRAWING_NS, "class-id", classId);
+ oleList.setAttribute(OfficeNamespaces.XLINK_NS, "href", "./" + href);
+ oleList.setAttribute(OfficeNamespaces.XLINK_NS, "type", "simple");
+ oleList.setAttribute(OfficeNamespaces.XLINK_NS, "show", "embed");
+ oleList.setAttribute(OfficeNamespaces.XLINK_NS, "actuate", "onLoad");
+
+ try
+ {
+ getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, OfficeToken.OBJECT_OLE, oleList, XmlWriterSupport.CLOSE);
+ }
+ catch (IOException ioe)
+ {
+ throw new ReportProcessingException(FAILED, ioe);
+ }
+
+
+ }
+}
diff --git a/reportdesign/source/filter/xml/xmlCell.cxx b/reportdesign/source/filter/xml/xmlCell.cxx index 0294839672e6..e4c394622f69 100644 --- a/reportdesign/source/filter/xml/xmlCell.cxx +++ b/reportdesign/source/filter/xml/xmlCell.cxx @@ -171,7 +171,7 @@ SvXMLImportContext* OXMLCell::CreateChildContext( m_nCurrentCount = m_pContainer->getSection()->getCount(); uno::Reference< uno::XInterface> xInt = xFactor->createInstance(SERVICE_FORMATTEDFIELD); Reference< report::XFormattedField > xControl(xInt,uno::UNO_QUERY); - pContext = new OXMLSubDocument( rImport, _nPrefix, _rLocalName,xControl.get(),m_pContainer); + pContext = new OXMLSubDocument( rImport, _nPrefix, _rLocalName,xControl.get(),m_pContainer, this /* give the current cell as parent*/ ); } break; @@ -285,6 +285,11 @@ void OXMLCell::Characters( const ::rtl::OUString& rChars ) } } +void OXMLCell::setContainsShape(bool _bContainsShape) +{ + m_bContainsShape = _bContainsShape; +} + //---------------------------------------------------------------------------- } // namespace rptxml // ----------------------------------------------------------------------------- diff --git a/reportdesign/source/filter/xml/xmlCell.hxx b/reportdesign/source/filter/xml/xmlCell.hxx index 122aac8f8976..2726a50da521 100644 --- a/reportdesign/source/filter/xml/xmlCell.hxx +++ b/reportdesign/source/filter/xml/xmlCell.hxx @@ -68,6 +68,7 @@ namespace rptxml virtual void EndElement(); void setComponent(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent >& _xComponent); + void setContainsShape(bool _bContainsShapes); }; // ----------------------------------------------------------------------------- } // namespace rptxml diff --git a/reportdesign/source/filter/xml/xmlExportDocumentHandler.cxx b/reportdesign/source/filter/xml/xmlExportDocumentHandler.cxx index 086ed401cbe2..6e76f28cdc12 100644 --- a/reportdesign/source/filter/xml/xmlExportDocumentHandler.cxx +++ b/reportdesign/source/filter/xml/xmlExportDocumentHandler.cxx @@ -1,397 +1,396 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: xmlExportDocumentHandler.cxx,v $ - * $Revision: 1.5 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -#include "precompiled_reportdesign.hxx" - -#include "xmlExportDocumentHandler.hxx" -#include <com/sun/star/sdb/CommandType.hpp> -#include <com/sun/star/chart2/data/XDatabaseDataProvider.hpp> -#include <com/sun/star/reflection/XProxyFactory.hpp> -#include <com/sun/star/sdb/CommandType.hpp> -#include <comphelper/sequence.hxx> -#include <comphelper/sequenceashashmap.hxx> -#include <comphelper/documentconstants.hxx> -#include <xmloff/attrlist.hxx> -#include <xmloff/xmltoken.hxx> -#include <xmloff/xmlement.hxx> -#include <xmloff/xmluconv.hxx> -#include <svtools/saveopt.hxx> -#include <rtl/ustrbuf.hxx> -#include <connectivity/dbtools.hxx> -#include <rtl/ustrbuf.hxx> - -namespace rptxml -{ -using namespace ::com::sun::star; -using namespace ::xmloff::token; - -void lcl_exportPrettyPrinting(const uno::Reference< xml::sax::XDocumentHandler >& _xDelegatee) -{ - SvtSaveOptions aSaveOpt; - if ( aSaveOpt.IsPrettyPrinting() ) - { - static const ::rtl::OUString s_sWhitespaces(RTL_CONSTASCII_USTRINGPARAM(" ")); - _xDelegatee->ignorableWhitespace(s_sWhitespaces); - } -} - -::rtl::OUString lcl_createAttribute(const xmloff::token::XMLTokenEnum& _eNamespace,const xmloff::token::XMLTokenEnum& _eAttribute) -{ - ::rtl::OUStringBuffer sQName; - // ...if it's in our map, make the prefix - sQName.append ( xmloff::token::GetXMLToken(_eNamespace) ); - sQName.append ( sal_Unicode(':') ); - sQName.append ( xmloff::token::GetXMLToken(_eAttribute) ); - return sQName.makeStringAndClear(); -} - -void lcl_correctCellAddress(const ::rtl::OUString & _sName, const uno::Reference< xml::sax::XAttributeList > & xAttribs) -{ - SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs); - ::rtl::OUString sCellAddress = pList->getValueByName(_sName); - const sal_Int32 nPos = sCellAddress.lastIndexOf('$'); - if ( nPos != -1 ) - { - sCellAddress = sCellAddress.copy(0,nPos); - sCellAddress += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("$65535")); - pList->RemoveAttribute(_sName); - pList->AddAttribute(_sName,sCellAddress); - } -} - -ExportDocumentHandler::ExportDocumentHandler(uno::Reference< uno::XComponentContext > const & context) : - m_xContext(context) - ,m_nCurrentCellIndex(0) - ,m_bTableRowsStarted(false) - ,m_bFirstRowExported(false) - ,m_bExportChar(false) -{ -} -// ----------------------------------------------------------------------------- -ExportDocumentHandler::~ExportDocumentHandler() -{ - if ( m_xProxy.is() ) - { - m_xProxy->setDelegator( NULL ); - m_xProxy.clear(); - } -} -IMPLEMENT_GET_IMPLEMENTATION_ID(ExportDocumentHandler) -IMPLEMENT_FORWARD_REFCOUNT( ExportDocumentHandler, ExportDocumentHandler_BASE ) -//------------------------------------------------------------------------ -::rtl::OUString SAL_CALL ExportDocumentHandler::getImplementationName( ) throw(uno::RuntimeException) -{ - return getImplementationName_Static(); -} - -//------------------------------------------------------------------------ -sal_Bool SAL_CALL ExportDocumentHandler::supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException) -{ - return ::comphelper::existsValue(ServiceName,getSupportedServiceNames_static()); -} - -//------------------------------------------------------------------------ -uno::Sequence< ::rtl::OUString > SAL_CALL ExportDocumentHandler::getSupportedServiceNames( ) throw(uno::RuntimeException) -{ - uno::Sequence< ::rtl::OUString > aSupported; - if ( m_xServiceInfo.is() ) - aSupported = m_xServiceInfo->getSupportedServiceNames(); - return ::comphelper::concatSequences(getSupportedServiceNames_static(),aSupported); -} - -//------------------------------------------------------------------------ -::rtl::OUString ExportDocumentHandler::getImplementationName_Static( ) throw(uno::RuntimeException) -{ - return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.report.ExportDocumentHandler")); -} - -//------------------------------------------------------------------------ -uno::Sequence< ::rtl::OUString > ExportDocumentHandler::getSupportedServiceNames_static( ) throw(uno::RuntimeException) -{ - uno::Sequence< ::rtl::OUString > aSupported(1); - aSupported[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.report.ExportDocumentHandler")); - return aSupported; -} - -//------------------------------------------------------------------------ -uno::Reference< uno::XInterface > SAL_CALL ExportDocumentHandler::create( const uno::Reference< uno::XComponentContext >& _rxContext ) -{ - return *(new ExportDocumentHandler( _rxContext )); -} -// xml::sax::XDocumentHandler: -void SAL_CALL ExportDocumentHandler::startDocument() throw (uno::RuntimeException, xml::sax::SAXException) -{ - m_xDelegatee->startDocument(); -} - -void SAL_CALL ExportDocumentHandler::endDocument() throw (uno::RuntimeException, xml::sax::SAXException) -{ - m_xDelegatee->endDocument(); -} - -void SAL_CALL ExportDocumentHandler::startElement(const ::rtl::OUString & _sName, const uno::Reference< xml::sax::XAttributeList > & xAttribs) throw (uno::RuntimeException, xml::sax::SAXException) -{ - bool bExport = true; - if ( _sName.equalsAscii("office:chart") ) - { - SvXMLAttributeList* pList = new SvXMLAttributeList(); - uno::Reference< xml::sax::XAttributeList > xNewAttribs = pList; - ::rtl::OUStringBuffer sValue; - static SvXMLEnumMapEntry aXML_CommnadTypeEnumMap[] = - { - { XML_TABLE, sdb::CommandType::TABLE }, - { XML_QUERY, sdb::CommandType::QUERY }, - // { XML_COMMAND, CommandType::COMMAND }, // default - { XML_TOKEN_INVALID, 0 } - }; - if ( SvXMLUnitConverter::convertEnum( sValue, static_cast<sal_uInt16>(m_xDatabaseDataProvider->getCommandType()),aXML_CommnadTypeEnumMap ) ) - { - pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_COMMAND_TYPE),sValue.makeStringAndClear()); - } - ::rtl::OUString sComamnd = m_xDatabaseDataProvider->getCommand(); - if ( sComamnd.getLength() ) - pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_COMMAND),sComamnd); - - ::rtl::OUString sFilter( m_xDatabaseDataProvider->getFilter() ); - if ( sFilter.getLength() ) - pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_FILTER),sFilter); - - sal_Bool bEscapeProcessing( m_xDatabaseDataProvider->getEscapeProcessing() ); - if ( !bEscapeProcessing ) - pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_ESCAPE_PROCESSING),::xmloff::token::GetXMLToken( XML_FALSE )); - - pList->AddAttribute(lcl_createAttribute(XML_NP_OFFICE,XML_MIMETYPE),MIMETYPE_OASIS_OPENDOCUMENT_CHART); - - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_OFFICE,XML_REPORT),xNewAttribs); - - /*const uno::Sequence< ::rtl::OUString > aDetailFields = m_xDatabaseDataProvider->getDetailFields(); - if ( aDetailFields.getLength() ) - { - lcl_exportPrettyPrinting(m_xDelegatee); - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_MASTER_DETAIL_FIELDS),NULL); - const uno::Sequence< ::rtl::OUString > aMasterFields = m_xDatabaseDataProvider->getMasterFields(); - OSL_ENSURE(aDetailFields.getLength() == aMasterFields.getLength(),"not equal length for master and detail fields!"); - const ::rtl::OUString sDetailToken = lcl_createAttribute(XML_NP_RPT, XML_DETAIL); - const ::rtl::OUString sMasterToken = lcl_createAttribute(XML_NP_RPT, XML_MASTER); - const ::rtl::OUString sElementToken = lcl_createAttribute(XML_NP_RPT,XML_MASTER_DETAIL_FIELD); - const ::rtl::OUString* pDetailFieldsIter = aDetailFields.getConstArray(); - const ::rtl::OUString* pIter = aMasterFields.getConstArray(); - const ::rtl::OUString* pEnd = pIter + aMasterFields.getLength(); - for(;pIter != pEnd;++pIter,++pDetailFieldsIter) - { - pList = new SvXMLAttributeList(); - xNewAttribs = pList; - pList->AddAttribute( sMasterToken , *pIter ); - if ( pDetailFieldsIter->getLength() ) - pList->AddAttribute( sDetailToken , *pDetailFieldsIter ); - lcl_exportPrettyPrinting(m_xDelegatee); - m_xDelegatee->startElement(sElementToken,xNewAttribs); - lcl_exportPrettyPrinting(m_xDelegatee); - m_xDelegatee->endElement(sElementToken); - } - lcl_exportPrettyPrinting(m_xDelegatee); - m_xDelegatee->endElement(lcl_createAttribute(XML_NP_RPT,XML_MASTER_DETAIL_FIELDS)); - }*/ - bExport = false; - } - else if ( _sName.equalsAscii("table:table") ) - { - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_DETAIL),NULL); - lcl_exportPrettyPrinting(m_xDelegatee); - } - else if ( _sName.equalsAscii("table:table-rows") ) - m_bTableRowsStarted = true; - else if ( m_bTableRowsStarted && m_bFirstRowExported && (_sName.equalsAscii("table:table-row") || _sName.equalsAscii("table:table-cell")) ) - bExport = false; - else if ( _sName.equalsAscii("chart:plot-area")) - { - SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs); - pList->RemoveAttribute(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("table:cell-range-address"))); - } - else if ( _sName.equalsAscii("chart:categories")) - { - static ::rtl::OUString s_sCellAddress(lcl_createAttribute(XML_NP_TABLE,XML_CELL_RANGE_ADDRESS)); - lcl_correctCellAddress(s_sCellAddress,xAttribs); - } - else if ( _sName.equalsAscii("chart:series")) - { - static ::rtl::OUString s_sCellAddress(lcl_createAttribute(XML_NP_CHART,XML_VALUES_CELL_RANGE_ADDRESS)); - lcl_correctCellAddress(s_sCellAddress,xAttribs); - } - else if ( m_bTableRowsStarted && !m_bFirstRowExported && _sName.equalsAscii("table:table-cell") ) - { - SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs); - static ::rtl::OUString s_sValue(lcl_createAttribute(XML_NP_OFFICE,XML_VALUE)); - pList->RemoveAttribute(s_sValue); - } - else if ( m_bTableRowsStarted && _sName.equalsAscii("text:p") ) - { - if ( !m_bFirstRowExported ) - { - SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs); - pList->RemoveAttribute(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("text:id"))); - m_xDelegatee->startElement(_sName,xAttribs); - pList = new SvXMLAttributeList(); - uno::Reference< xml::sax::XAttributeList > xNewAttribs = pList; - - ::rtl::OUString sFormula; - if( m_nCurrentCellIndex < m_aColumns.getLength() ) - { - sFormula += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("field:[")); - sFormula += m_aColumns[m_nCurrentCellIndex]; - sFormula += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("]")); - } - pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_FORMULA),sFormula); - - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_FORMATTED_TEXT),xNewAttribs); - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_REPORT_ELEMENT),NULL); - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_REPORT_COMPONENT),NULL); - m_bExportChar = true; - - ++m_nCurrentCellIndex; - } - bExport = false; - } - if ( bExport ) - m_xDelegatee->startElement(_sName,xAttribs); -} -// ----------------------------------------------------------------------------- -void SAL_CALL ExportDocumentHandler::endElement(const ::rtl::OUString & _sName) throw (uno::RuntimeException, xml::sax::SAXException) -{ - bool bExport = true; - ::rtl::OUString sNewName = _sName; - if ( _sName.equalsAscii("office:chart") ) - { - sNewName = lcl_createAttribute(XML_NP_OFFICE,XML_REPORT); - } - else if ( _sName.equalsAscii("table:table") ) - { - m_xDelegatee->endElement(_sName); - lcl_exportPrettyPrinting(m_xDelegatee); - sNewName = lcl_createAttribute(XML_NP_RPT,XML_DETAIL); - } - else if ( _sName.equalsAscii("table:table-rows") ) - m_bTableRowsStarted = false; - else if ( m_bTableRowsStarted && m_bFirstRowExported && (_sName.equalsAscii("table:table-row") || _sName.equalsAscii("table:table-cell")) ) - bExport = false; - else if ( m_bTableRowsStarted && _sName.equalsAscii("table:table-row") ) - m_bFirstRowExported = true; - else if ( m_bTableRowsStarted && _sName.equalsAscii("text:p") ) - { - bExport = !m_bFirstRowExported; - if ( bExport ) - { - m_bExportChar = false; - m_xDelegatee->endElement(lcl_createAttribute(XML_NP_RPT,XML_REPORT_COMPONENT)); - m_xDelegatee->endElement(lcl_createAttribute(XML_NP_RPT,XML_REPORT_ELEMENT)); - m_xDelegatee->endElement(lcl_createAttribute(XML_NP_RPT,XML_FORMATTED_TEXT)); - } - } - - if ( bExport ) - m_xDelegatee->endElement(sNewName); -} - -void SAL_CALL ExportDocumentHandler::characters(const ::rtl::OUString & aChars) throw (uno::RuntimeException, xml::sax::SAXException) -{ - if ( !(m_bTableRowsStarted || m_bFirstRowExported) ) - m_xDelegatee->characters(aChars); - else if ( m_bExportChar ) - { - static const ::rtl::OUString s_sZero(RTL_CONSTASCII_USTRINGPARAM("0")); - m_xDelegatee->characters(s_sZero); - } -} - -void SAL_CALL ExportDocumentHandler::ignorableWhitespace(const ::rtl::OUString & aWhitespaces) throw (uno::RuntimeException, xml::sax::SAXException) -{ - m_xDelegatee->ignorableWhitespace(aWhitespaces); -} - -void SAL_CALL ExportDocumentHandler::processingInstruction(const ::rtl::OUString & aTarget, const ::rtl::OUString & aData) throw (uno::RuntimeException, xml::sax::SAXException) -{ - m_xDelegatee->processingInstruction(aTarget,aData); -} - -void SAL_CALL ExportDocumentHandler::setDocumentLocator(const uno::Reference< xml::sax::XLocator > & xLocator) throw (uno::RuntimeException, xml::sax::SAXException) -{ - m_xDelegatee->setDocumentLocator(xLocator); -} -void SAL_CALL ExportDocumentHandler::initialize( const uno::Sequence< uno::Any >& _aArguments ) throw (uno::Exception, uno::RuntimeException) -{ - ::osl::MutexGuard aGuard(m_aMutex); - comphelper::SequenceAsHashMap aArgs(_aArguments); - m_xDelegatee = aArgs.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DocumentHandler")),m_xDelegatee); - m_xModel = aArgs.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Model")),m_xModel); - - OSL_ENSURE(m_xDelegatee.is(),"No document handler avialable!"); - if ( !m_xDelegatee.is() || !m_xModel.is() ) - throw uno::Exception(); - - m_xDatabaseDataProvider.set(m_xModel->getDataProvider(),uno::UNO_QUERY); - if ( !m_xDatabaseDataProvider.is() ) - throw uno::Exception(); - - uno::Reference< reflection::XProxyFactory > xProxyFactory( m_xContext->getServiceManager()->createInstanceWithContext( - ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.reflection.ProxyFactory")),m_xContext), - uno::UNO_QUERY); - m_xProxy = xProxyFactory->createProxy(m_xDelegatee.get()); - ::comphelper::query_aggregation(m_xProxy,m_xDelegatee); - m_xTypeProvider.set(m_xDelegatee,uno::UNO_QUERY); - m_xServiceInfo.set(m_xDelegatee,uno::UNO_QUERY); - - // set ourself as delegator - m_xProxy->setDelegator( *this ); - - const ::rtl::OUString sCommand = m_xDatabaseDataProvider->getCommand(); - if ( sCommand.getLength() ) - m_aColumns = ::dbtools::getFieldNamesByCommandDescriptor(m_xDatabaseDataProvider->getActiveConnection() - ,m_xDatabaseDataProvider->getCommandType() - ,sCommand); -} -// -------------------------------------------------------------------------------- -uno::Any SAL_CALL ExportDocumentHandler::queryInterface( const uno::Type& _rType ) throw (uno::RuntimeException) -{ - uno::Any aReturn = ExportDocumentHandler_BASE::queryInterface(_rType); - return aReturn.hasValue() ? aReturn : (m_xProxy.is() ? m_xProxy->queryAggregation(_rType) : aReturn); -} -// -------------------------------------------------------------------------------- -uno::Sequence< uno::Type > SAL_CALL ExportDocumentHandler::getTypes( ) throw (uno::RuntimeException) -{ - if ( m_xTypeProvider.is() ) - return ::comphelper::concatSequences( - ExportDocumentHandler_BASE::getTypes(), - m_xTypeProvider->getTypes() - ); - return ExportDocumentHandler_BASE::getTypes(); -} - -// ----------------------------------------------------------------------------- -} // namespace rptxml -// ----------------------------------------------------------------------------- +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: xmlExportDocumentHandler.cxx,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#include "precompiled_reportdesign.hxx"
+
+#include "xmlExportDocumentHandler.hxx"
+#include <com/sun/star/sdb/CommandType.hpp>
+#include <com/sun/star/chart2/data/XDatabaseDataProvider.hpp>
+#include <com/sun/star/reflection/XProxyFactory.hpp>
+#include <com/sun/star/sdb/CommandType.hpp>
+#include <comphelper/sequence.hxx>
+#include <comphelper/sequenceashashmap.hxx>
+#include <comphelper/documentconstants.hxx>
+#include <xmloff/attrlist.hxx>
+#include <xmloff/xmltoken.hxx>
+#include <xmloff/xmlement.hxx>
+#include <xmloff/xmluconv.hxx>
+#include <svtools/saveopt.hxx>
+#include <rtl/ustrbuf.hxx>
+#include <connectivity/dbtools.hxx>
+#include <rtl/ustrbuf.hxx>
+
+namespace rptxml
+{
+using namespace ::com::sun::star;
+using namespace ::xmloff::token;
+
+void lcl_exportPrettyPrinting(const uno::Reference< xml::sax::XDocumentHandler >& _xDelegatee)
+{
+ SvtSaveOptions aSaveOpt;
+ if ( aSaveOpt.IsPrettyPrinting() )
+ {
+ static const ::rtl::OUString s_sWhitespaces(RTL_CONSTASCII_USTRINGPARAM(" "));
+ _xDelegatee->ignorableWhitespace(s_sWhitespaces);
+ }
+}
+
+::rtl::OUString lcl_createAttribute(const xmloff::token::XMLTokenEnum& _eNamespace,const xmloff::token::XMLTokenEnum& _eAttribute)
+{
+ ::rtl::OUStringBuffer sQName;
+ // ...if it's in our map, make the prefix
+ sQName.append ( xmloff::token::GetXMLToken(_eNamespace) );
+ sQName.append ( sal_Unicode(':') );
+ sQName.append ( xmloff::token::GetXMLToken(_eAttribute) );
+ return sQName.makeStringAndClear();
+}
+
+void lcl_correctCellAddress(const ::rtl::OUString & _sName, const uno::Reference< xml::sax::XAttributeList > & xAttribs)
+{
+ SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs);
+ ::rtl::OUString sCellAddress = pList->getValueByName(_sName);
+ const sal_Int32 nPos = sCellAddress.lastIndexOf('$');
+ if ( nPos != -1 )
+ {
+ sCellAddress = sCellAddress.copy(0,nPos);
+ sCellAddress += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("$65535"));
+ pList->RemoveAttribute(_sName);
+ pList->AddAttribute(_sName,sCellAddress);
+ }
+}
+
+ExportDocumentHandler::ExportDocumentHandler(uno::Reference< uno::XComponentContext > const & context) :
+ m_xContext(context)
+ ,m_nCurrentCellIndex(0)
+ ,m_bTableRowsStarted(false)
+ ,m_bFirstRowExported(false)
+ ,m_bExportChar(false)
+{
+}
+// -----------------------------------------------------------------------------
+ExportDocumentHandler::~ExportDocumentHandler()
+{
+ if ( m_xProxy.is() )
+ {
+ m_xProxy->setDelegator( NULL );
+ m_xProxy.clear();
+ }
+}
+IMPLEMENT_GET_IMPLEMENTATION_ID(ExportDocumentHandler)
+IMPLEMENT_FORWARD_REFCOUNT( ExportDocumentHandler, ExportDocumentHandler_BASE )
+//------------------------------------------------------------------------
+::rtl::OUString SAL_CALL ExportDocumentHandler::getImplementationName( ) throw(uno::RuntimeException)
+{
+ return getImplementationName_Static();
+}
+
+//------------------------------------------------------------------------
+sal_Bool SAL_CALL ExportDocumentHandler::supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException)
+{
+ return ::comphelper::existsValue(ServiceName,getSupportedServiceNames_static());
+}
+
+//------------------------------------------------------------------------
+uno::Sequence< ::rtl::OUString > SAL_CALL ExportDocumentHandler::getSupportedServiceNames( ) throw(uno::RuntimeException)
+{
+ uno::Sequence< ::rtl::OUString > aSupported;
+ if ( m_xServiceInfo.is() )
+ aSupported = m_xServiceInfo->getSupportedServiceNames();
+ return ::comphelper::concatSequences(getSupportedServiceNames_static(),aSupported);
+}
+
+//------------------------------------------------------------------------
+::rtl::OUString ExportDocumentHandler::getImplementationName_Static( ) throw(uno::RuntimeException)
+{
+ return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.report.ExportDocumentHandler"));
+}
+
+//------------------------------------------------------------------------
+uno::Sequence< ::rtl::OUString > ExportDocumentHandler::getSupportedServiceNames_static( ) throw(uno::RuntimeException)
+{
+ uno::Sequence< ::rtl::OUString > aSupported(1);
+ aSupported[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.report.ExportDocumentHandler"));
+ return aSupported;
+}
+
+//------------------------------------------------------------------------
+uno::Reference< uno::XInterface > SAL_CALL ExportDocumentHandler::create( const uno::Reference< uno::XComponentContext >& _rxContext )
+{
+ return *(new ExportDocumentHandler( _rxContext ));
+}
+// xml::sax::XDocumentHandler:
+void SAL_CALL ExportDocumentHandler::startDocument() throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ m_xDelegatee->startDocument();
+}
+
+void SAL_CALL ExportDocumentHandler::endDocument() throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ m_xDelegatee->endDocument();
+}
+
+void SAL_CALL ExportDocumentHandler::startElement(const ::rtl::OUString & _sName, const uno::Reference< xml::sax::XAttributeList > & xAttribs) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ bool bExport = true;
+ if ( _sName.equalsAscii("office:chart") )
+ {
+ SvXMLAttributeList* pList = new SvXMLAttributeList();
+ uno::Reference< xml::sax::XAttributeList > xNewAttribs = pList;
+ ::rtl::OUStringBuffer sValue;
+ static SvXMLEnumMapEntry aXML_CommnadTypeEnumMap[] =
+ {
+ { XML_TABLE, sdb::CommandType::TABLE },
+ { XML_QUERY, sdb::CommandType::QUERY },
+ // { XML_COMMAND, CommandType::COMMAND }, // default
+ { XML_TOKEN_INVALID, 0 }
+ };
+ if ( SvXMLUnitConverter::convertEnum( sValue, static_cast<sal_uInt16>(m_xDatabaseDataProvider->getCommandType()),aXML_CommnadTypeEnumMap ) )
+ {
+ pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_COMMAND_TYPE),sValue.makeStringAndClear());
+ }
+ const ::rtl::OUString sComamnd = m_xDatabaseDataProvider->getCommand();
+ if ( sComamnd.getLength() )
+ pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_COMMAND),sComamnd);
+
+ const ::rtl::OUString sFilter( m_xDatabaseDataProvider->getFilter() );
+ if ( sFilter.getLength() )
+ pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_FILTER),sFilter);
+
+ const sal_Bool bEscapeProcessing( m_xDatabaseDataProvider->getEscapeProcessing() );
+ if ( !bEscapeProcessing )
+ pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_ESCAPE_PROCESSING),::xmloff::token::GetXMLToken( XML_FALSE ));
+
+ pList->AddAttribute(lcl_createAttribute(XML_NP_OFFICE,XML_MIMETYPE),MIMETYPE_OASIS_OPENDOCUMENT_CHART);
+
+ m_xDelegatee->startElement(lcl_createAttribute(XML_NP_OFFICE,XML_REPORT),xNewAttribs);
+ bExport = false;
+ }
+ else if ( _sName.equalsAscii("table:table") )
+ {
+ m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_DETAIL),NULL);
+ lcl_exportPrettyPrinting(m_xDelegatee);
+ }
+ else if ( _sName.equalsAscii("table:table-rows") )
+ {
+ m_xDelegatee->startElement(_sName,xAttribs);
+ exportTableRows();
+ bExport = false;
+ m_bTableRowsStarted = true;
+ m_bFirstRowExported = true;
+ }
+ else if ( m_bTableRowsStarted && m_bFirstRowExported && (_sName.equalsAscii("table:table-row") || _sName.equalsAscii("table:table-cell")) )
+ bExport = false;
+ else if ( _sName.equalsAscii("chart:plot-area"))
+ {
+ SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs);
+ pList->RemoveAttribute(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("table:cell-range-address")));
+ }
+ else if ( _sName.equalsAscii("chart:categories"))
+ {
+ static ::rtl::OUString s_sCellAddress(lcl_createAttribute(XML_NP_TABLE,XML_CELL_RANGE_ADDRESS));
+ lcl_correctCellAddress(s_sCellAddress,xAttribs);
+ }
+ else if ( _sName.equalsAscii("chart:series"))
+ {
+ static ::rtl::OUString s_sCellAddress(lcl_createAttribute(XML_NP_CHART,XML_VALUES_CELL_RANGE_ADDRESS));
+ lcl_correctCellAddress(s_sCellAddress,xAttribs);
+ }
+ else if ( m_bTableRowsStarted && !m_bFirstRowExported && _sName.equalsAscii("table:table-cell") )
+ {
+ SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs);
+ static ::rtl::OUString s_sValue(lcl_createAttribute(XML_NP_OFFICE,XML_VALUE));
+ pList->RemoveAttribute(s_sValue);
+ }
+ else if ( m_bTableRowsStarted && _sName.equalsAscii("text:p") )
+ {
+ bExport = false;
+ }
+ if ( bExport )
+ m_xDelegatee->startElement(_sName,xAttribs);
+}
+// -----------------------------------------------------------------------------
+void SAL_CALL ExportDocumentHandler::endElement(const ::rtl::OUString & _sName) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ bool bExport = true;
+ ::rtl::OUString sNewName = _sName;
+ if ( _sName.equalsAscii("office:chart") )
+ {
+ sNewName = lcl_createAttribute(XML_NP_OFFICE,XML_REPORT);
+ }
+ else if ( _sName.equalsAscii("table:table") )
+ {
+ m_xDelegatee->endElement(_sName);
+ lcl_exportPrettyPrinting(m_xDelegatee);
+ sNewName = lcl_createAttribute(XML_NP_RPT,XML_DETAIL);
+ }
+ else if ( _sName.equalsAscii("table:table-rows") )
+ m_bTableRowsStarted = false;
+ else if ( m_bTableRowsStarted && m_bFirstRowExported && (_sName.equalsAscii("table:table-row") || _sName.equalsAscii("table:table-cell")) )
+ bExport = false;
+ else if ( m_bTableRowsStarted && _sName.equalsAscii("table:table-row") )
+ m_bFirstRowExported = true;
+ else if ( m_bTableRowsStarted && _sName.equalsAscii("text:p") )
+ {
+ bExport = !m_bFirstRowExported;
+ }
+
+ if ( bExport )
+ m_xDelegatee->endElement(sNewName);
+}
+
+void SAL_CALL ExportDocumentHandler::characters(const ::rtl::OUString & aChars) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ if ( !(m_bTableRowsStarted || m_bFirstRowExported) )
+ m_xDelegatee->characters(aChars);
+ else if ( m_bExportChar )
+ {
+ static const ::rtl::OUString s_sZero(RTL_CONSTASCII_USTRINGPARAM("0"));
+ m_xDelegatee->characters(s_sZero);
+ }
+}
+
+void SAL_CALL ExportDocumentHandler::ignorableWhitespace(const ::rtl::OUString & aWhitespaces) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ m_xDelegatee->ignorableWhitespace(aWhitespaces);
+}
+
+void SAL_CALL ExportDocumentHandler::processingInstruction(const ::rtl::OUString & aTarget, const ::rtl::OUString & aData) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ m_xDelegatee->processingInstruction(aTarget,aData);
+}
+
+void SAL_CALL ExportDocumentHandler::setDocumentLocator(const uno::Reference< xml::sax::XLocator > & xLocator) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ m_xDelegatee->setDocumentLocator(xLocator);
+}
+void SAL_CALL ExportDocumentHandler::initialize( const uno::Sequence< uno::Any >& _aArguments ) throw (uno::Exception, uno::RuntimeException)
+{
+ ::osl::MutexGuard aGuard(m_aMutex);
+ comphelper::SequenceAsHashMap aArgs(_aArguments);
+ m_xDelegatee = aArgs.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DocumentHandler")),m_xDelegatee);
+ m_xModel = aArgs.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Model")),m_xModel);
+
+ OSL_ENSURE(m_xDelegatee.is(),"No document handler avialable!");
+ if ( !m_xDelegatee.is() || !m_xModel.is() )
+ throw uno::Exception();
+
+ m_xDatabaseDataProvider.set(m_xModel->getDataProvider(),uno::UNO_QUERY);
+ if ( !m_xDatabaseDataProvider.is() )
+ throw uno::Exception();
+
+ uno::Reference< reflection::XProxyFactory > xProxyFactory( m_xContext->getServiceManager()->createInstanceWithContext(
+ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.reflection.ProxyFactory")),m_xContext),
+ uno::UNO_QUERY);
+ m_xProxy = xProxyFactory->createProxy(m_xDelegatee.get());
+ ::comphelper::query_aggregation(m_xProxy,m_xDelegatee);
+ m_xTypeProvider.set(m_xDelegatee,uno::UNO_QUERY);
+ m_xServiceInfo.set(m_xDelegatee,uno::UNO_QUERY);
+
+ // set ourself as delegator
+ m_xProxy->setDelegator( *this );
+
+ const ::rtl::OUString sCommand = m_xDatabaseDataProvider->getCommand();
+ if ( sCommand.getLength() )
+ m_aColumns = ::dbtools::getFieldNamesByCommandDescriptor(m_xDatabaseDataProvider->getActiveConnection()
+ ,m_xDatabaseDataProvider->getCommandType()
+ ,sCommand);
+}
+// --------------------------------------------------------------------------------
+uno::Any SAL_CALL ExportDocumentHandler::queryInterface( const uno::Type& _rType ) throw (uno::RuntimeException)
+{
+ uno::Any aReturn = ExportDocumentHandler_BASE::queryInterface(_rType);
+ return aReturn.hasValue() ? aReturn : (m_xProxy.is() ? m_xProxy->queryAggregation(_rType) : aReturn);
+}
+// --------------------------------------------------------------------------------
+uno::Sequence< uno::Type > SAL_CALL ExportDocumentHandler::getTypes( ) throw (uno::RuntimeException)
+{
+ if ( m_xTypeProvider.is() )
+ return ::comphelper::concatSequences(
+ ExportDocumentHandler_BASE::getTypes(),
+ m_xTypeProvider->getTypes()
+ );
+ return ExportDocumentHandler_BASE::getTypes();
+}
+// -----------------------------------------------------------------------------
+void ExportDocumentHandler::exportTableRows()
+{
+ const ::rtl::OUString sRow( lcl_createAttribute(XML_NP_TABLE, XML_TABLE_ROW) );
+ m_xDelegatee->startElement(sRow,NULL);
+
+ const ::rtl::OUString sValueType( lcl_createAttribute(XML_NP_OFFICE, XML_VALUE_TYPE) );
+
+ const static ::rtl::OUString s_sFieldPrefix(RTL_CONSTASCII_USTRINGPARAM("field:["));
+ const static ::rtl::OUString s_sFieldPostfix(RTL_CONSTASCII_USTRINGPARAM("]"));
+ const ::rtl::OUString sCell( lcl_createAttribute(XML_NP_TABLE, XML_TABLE_CELL) );
+ const ::rtl::OUString sP( lcl_createAttribute(XML_NP_TEXT, XML_P) );
+ const ::rtl::OUString sFtext(lcl_createAttribute(XML_NP_RPT,XML_FORMATTED_TEXT) );
+ const ::rtl::OUString sRElement(lcl_createAttribute(XML_NP_RPT,XML_REPORT_ELEMENT) );
+ const ::rtl::OUString sRComponent( lcl_createAttribute(XML_NP_RPT,XML_REPORT_COMPONENT) ) ;
+ const ::rtl::OUString sFormulaAttrib( lcl_createAttribute(XML_NP_RPT,XML_FORMULA) );
+ const static ::rtl::OUString s_sString(RTL_CONSTASCII_USTRINGPARAM("string"));
+ const static ::rtl::OUString s_sFloat(RTL_CONSTASCII_USTRINGPARAM("float"));
+
+ SvXMLAttributeList* pCellAtt = new SvXMLAttributeList();
+ uno::Reference< xml::sax::XAttributeList > xCellAtt = pCellAtt;
+ pCellAtt->AddAttribute(sValueType,s_sString);
+
+ ::rtl::OUString sFormula;
+ const sal_Int32 nCount = m_aColumns.getLength();
+ for(sal_Int32 i = 0; i < nCount ; ++i)
+ {
+ sFormula = s_sFieldPrefix;
+ sFormula += m_aColumns[i];
+ sFormula += s_sFieldPostfix;
+ SvXMLAttributeList* pList = new SvXMLAttributeList();
+ uno::Reference< xml::sax::XAttributeList > xAttribs = pList;
+ pList->AddAttribute(sFormulaAttrib,sFormula);
+
+ m_xDelegatee->startElement(sCell,xCellAtt);
+ if ( i == 0 )
+ {
+ pCellAtt->RemoveAttribute(sValueType);
+ pCellAtt->AddAttribute(sValueType,s_sFloat);
+ }
+ m_xDelegatee->startElement(sP,NULL);
+ m_xDelegatee->startElement(sFtext,xAttribs);
+ m_xDelegatee->startElement(sRElement,NULL);
+ m_xDelegatee->startElement(sRComponent,NULL);
+
+ m_xDelegatee->endElement(sRComponent);
+ m_xDelegatee->endElement(sRElement);
+ m_xDelegatee->endElement(sFtext);
+ m_xDelegatee->endElement(sP);
+ m_xDelegatee->endElement(sCell);
+ } // for(sal_Int32 i = 0; i < nCount ; ++i)
+
+ m_xDelegatee->endElement(sRow);
+}
+// -----------------------------------------------------------------------------
+} // namespace rptxml
+// -----------------------------------------------------------------------------
diff --git a/reportdesign/source/filter/xml/xmlExportDocumentHandler.hxx b/reportdesign/source/filter/xml/xmlExportDocumentHandler.hxx index cfb78c62df46..be97bdc030f7 100644 --- a/reportdesign/source/filter/xml/xmlExportDocumentHandler.hxx +++ b/reportdesign/source/filter/xml/xmlExportDocumentHandler.hxx @@ -1,105 +1,106 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: xmlExportDocumentHandler.hxx,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -#ifndef RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED -#define RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED - -#include "sal/config.h" -#include "com/sun/star/uno/XComponentContext.hpp" -#include <cppuhelper/implbase3.hxx> -#include "com/sun/star/xml/sax/XDocumentHandler.hpp" -#include <com/sun/star/lang/XInitialization.hpp> -#include <com/sun/star/lang/XServiceInfo.hpp> -#include <com/sun/star/lang/XTypeProvider.hpp> -#include <com/sun/star/chart2/XChartDocument.hpp> -#include "com/sun/star/chart2/data/XDatabaseDataProvider.hpp" -#include <comphelper/uno3.hxx> - -namespace rptxml -{ -typedef ::cppu::WeakAggImplHelper3< ::com::sun::star::xml::sax::XDocumentHandler - , ::com::sun::star::lang::XInitialization - , ::com::sun::star::lang::XServiceInfo> ExportDocumentHandler_BASE; - -class ExportDocumentHandler : public ExportDocumentHandler_BASE -{ -public: - // XServiceInfo - static versions - static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException); - static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_static( ) throw(::com::sun::star::uno::RuntimeException); - static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL - create(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >&); -public: - explicit ExportDocumentHandler(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & context); - -private: - // XServiceInfo - virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); - virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); - virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); - - DECLARE_XINTERFACE( ) - DECLARE_XTYPEPROVIDER( ) - - // ::com::sun::star::xml::sax::XDocumentHandler: - virtual void SAL_CALL startDocument() throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL endDocument() throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL startElement(const ::rtl::OUString & aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttribs) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL endElement(const ::rtl::OUString & aName) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL characters(const ::rtl::OUString & aChars) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL ignorableWhitespace(const ::rtl::OUString & aWhitespaces) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL processingInstruction(const ::rtl::OUString & aTarget, const ::rtl::OUString & aData) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL setDocumentLocator(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > & xLocator) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - - virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); - -private: - ExportDocumentHandler(ExportDocumentHandler &); // not defined - void operator =(ExportDocumentHandler &); // not defined - - virtual ~ExportDocumentHandler(); - - ::osl::Mutex m_aMutex; - ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; - ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > m_xDelegatee; - ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation > m_xProxy; - ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider > m_xTypeProvider; - ::com::sun::star::uno::Reference< ::com::sun::star::lang::XServiceInfo > m_xServiceInfo; - ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument > m_xModel; - ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDatabaseDataProvider > m_xDatabaseDataProvider; - ::com::sun::star::uno::Sequence< ::rtl::OUString > m_aColumns; - sal_Int32 m_nCurrentCellIndex; - bool m_bTableRowsStarted; - bool m_bFirstRowExported; - bool m_bExportChar; -}; -// ----------------------------------------------------------------------------- -} // namespace rptxml -// ----------------------------------------------------------------------------- -#endif // RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: xmlExportDocumentHandler.hxx,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#ifndef RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED
+#define RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED
+
+#include "sal/config.h"
+#include "com/sun/star/uno/XComponentContext.hpp"
+#include <cppuhelper/implbase3.hxx>
+#include "com/sun/star/xml/sax/XDocumentHandler.hpp"
+#include <com/sun/star/lang/XInitialization.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XTypeProvider.hpp>
+#include <com/sun/star/chart2/XChartDocument.hpp>
+#include "com/sun/star/chart2/data/XDatabaseDataProvider.hpp"
+#include <comphelper/uno3.hxx>
+
+namespace rptxml
+{
+typedef ::cppu::WeakAggImplHelper3< ::com::sun::star::xml::sax::XDocumentHandler
+ , ::com::sun::star::lang::XInitialization
+ , ::com::sun::star::lang::XServiceInfo> ExportDocumentHandler_BASE;
+
+class ExportDocumentHandler : public ExportDocumentHandler_BASE
+{
+public:
+ // XServiceInfo - static versions
+ static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException);
+ static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_static( ) throw(::com::sun::star::uno::RuntimeException);
+ static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
+ create(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >&);
+public:
+ explicit ExportDocumentHandler(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & context);
+
+private:
+ // XServiceInfo
+ virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);
+
+ DECLARE_XINTERFACE( )
+ DECLARE_XTYPEPROVIDER( )
+
+ // ::com::sun::star::xml::sax::XDocumentHandler:
+ virtual void SAL_CALL startDocument() throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL endDocument() throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL startElement(const ::rtl::OUString & aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttribs) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL endElement(const ::rtl::OUString & aName) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL characters(const ::rtl::OUString & aChars) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL ignorableWhitespace(const ::rtl::OUString & aWhitespaces) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL processingInstruction(const ::rtl::OUString & aTarget, const ::rtl::OUString & aData) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL setDocumentLocator(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > & xLocator) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+
+ virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+ void exportTableRows();
+private:
+ ExportDocumentHandler(ExportDocumentHandler &); // not defined
+ void operator =(ExportDocumentHandler &); // not defined
+
+ virtual ~ExportDocumentHandler();
+
+ ::osl::Mutex m_aMutex;
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
+ ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > m_xDelegatee;
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation > m_xProxy;
+ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider > m_xTypeProvider;
+ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XServiceInfo > m_xServiceInfo;
+ ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument > m_xModel;
+ ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDatabaseDataProvider > m_xDatabaseDataProvider;
+ ::com::sun::star::uno::Sequence< ::rtl::OUString > m_aColumns;
+ sal_Int32 m_nCurrentCellIndex;
+ bool m_bTableRowsStarted;
+ bool m_bFirstRowExported;
+ bool m_bExportChar;
+};
+// -----------------------------------------------------------------------------
+} // namespace rptxml
+// -----------------------------------------------------------------------------
+#endif // RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED
diff --git a/reportdesign/source/filter/xml/xmlSubDocument.cxx b/reportdesign/source/filter/xml/xmlSubDocument.cxx index b561499728bc..4ad6b9a2ec28 100644 --- a/reportdesign/source/filter/xml/xmlSubDocument.cxx +++ b/reportdesign/source/filter/xml/xmlSubDocument.cxx @@ -29,6 +29,7 @@ ************************************************************************/ #include "precompiled_reportdesign.hxx" #include "xmlSubDocument.hxx" +#include "xmlCell.hxx" #include "xmlfilter.hxx" #include <xmloff/xmltoken.hxx> #include <xmloff/xmlnmspe.hxx> @@ -52,9 +53,11 @@ OXMLSubDocument::OXMLSubDocument( ORptFilter& rImport, sal_uInt16 nPrfx ,const ::rtl::OUString& rLName ,const Reference< XReportComponent > & _xComponent - ,OXMLTable* _pContainer) : + ,OXMLTable* _pContainer + ,OXMLCell* _pCellParent) : OXMLReportElementBase( rImport, nPrfx, rLName,_xComponent.get(),_pContainer) ,m_xFake(_xComponent) +,m_pCellParent(_pCellParent) ,m_nCurrentCount(0) ,m_bContainsShape(false) { @@ -95,6 +98,11 @@ SvXMLImportContext* OXMLSubDocument::_CreateChildContext( uno::Reference< drawing::XShapes > xShapes = m_pContainer->getSection().get(); pContext = xShapeImportHelper->CreateGroupChildContext(GetImport(),_nPrefix,_rLocalName,xAttrList,xShapes); m_bContainsShape = true; + if (m_pCellParent) + { + // #i94115 say to the parent Cell it contains shapes + m_pCellParent->setContainsShape(true); + } } break; default: @@ -114,7 +122,8 @@ void OXMLSubDocument::EndElement() m_xComponent.set(m_pContainer->getSection()->getByIndex(m_nCurrentCount),uno::UNO_QUERY); if ( m_xComponent.is() ) { - m_pContainer->addCell(m_xComponent.get()); + // #i94115# this is no longer need. + // m_pContainer->addCell(m_xComponent.get()); if ( !m_aMasterFields.empty() ) m_xComponent->setMasterFields(Sequence< ::rtl::OUString>(&*m_aMasterFields.begin(),m_aMasterFields.size())); diff --git a/reportdesign/source/filter/xml/xmlSubDocument.hxx b/reportdesign/source/filter/xml/xmlSubDocument.hxx index 4f91d13e41a5..5d0bc900b146 100644 --- a/reportdesign/source/filter/xml/xmlSubDocument.hxx +++ b/reportdesign/source/filter/xml/xmlSubDocument.hxx @@ -37,12 +37,14 @@ namespace rptxml { class ORptFilter; + class OXMLCell; class OXMLSubDocument : public OXMLReportElementBase, public IMasterDetailFieds { ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> m_xComponent; ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> m_xFake; ::std::vector< ::rtl::OUString> m_aMasterFields; ::std::vector< ::rtl::OUString> m_aDetailFields; + OXMLCell* m_pCellParent; sal_Int32 m_nCurrentCount; bool m_bContainsShape; @@ -58,7 +60,8 @@ namespace rptxml ,sal_uInt16 nPrfx ,const ::rtl::OUString& rLName ,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent >& _xComponent - ,OXMLTable* _pContainer); + ,OXMLTable* _pContainer + ,OXMLCell* _pCellParent); virtual ~OXMLSubDocument(); virtual void EndElement(); diff --git a/reportdesign/source/ui/report/DesignView.cxx b/reportdesign/source/ui/report/DesignView.cxx index b7dedea9f2e4..933e7766fa40 100644 --- a/reportdesign/source/ui/report/DesignView.cxx +++ b/reportdesign/source/ui/report/DesignView.cxx @@ -34,6 +34,7 @@ #include "ReportController.hxx" #include <comphelper/types.hxx> #include <svtools/syslocale.hxx> +#include <svtools/viewoptions.hxx> #include "RptDef.hxx" #include "UITools.hxx" #include "RptObject.hxx" @@ -48,6 +49,7 @@ #include "ScrollHelper.hxx" #include "Navigator.hxx" #include "SectionWindow.hxx" +#include "RptResId.hrc" #include <vcl/svapp.hxx> namespace rptui @@ -204,12 +206,16 @@ ODesignView::~ODesignView() } if ( m_pAddField ) { + SvtViewOptions aDlgOpt( E_WINDOW, String::CreateFromInt32( UID_RPT_RPT_APP_VIEW ) );
+ aDlgOpt.SetWindowState( ::rtl::OUString::createFromAscii( m_pAddField->GetWindowState((WINDOWSTATE_MASK_X | WINDOWSTATE_MASK_Y | WINDOWSTATE_MASK_STATE | WINDOWSTATE_MASK_MINIMIZED)).GetBuffer() ) );
notifySystemWindow(this,m_pAddField,::comphelper::mem_fun(&TaskPaneList::RemoveWindow)); ::std::auto_ptr<Window> aTemp2(m_pAddField); m_pAddField = NULL; } if ( m_pReportExplorer ) { + SvtViewOptions aDlgOpt( E_WINDOW, String::CreateFromInt32( RID_NAVIGATOR ) );
+ aDlgOpt.SetWindowState( ::rtl::OUString::createFromAscii( m_pReportExplorer->GetWindowState((WINDOWSTATE_MASK_X | WINDOWSTATE_MASK_Y | WINDOWSTATE_MASK_STATE | WINDOWSTATE_MASK_MINIMIZED)).GetBuffer() ) ); notifySystemWindow(this,m_pReportExplorer,::comphelper::mem_fun(&TaskPaneList::RemoveWindow)); ::std::auto_ptr<Window> aTemp2(m_pReportExplorer); m_pReportExplorer = NULL; @@ -560,6 +566,9 @@ void ODesignView::toggleReportExplorer() { OReportController& rReportController = getController(); m_pReportExplorer = new ONavigator(this,rReportController); + SvtViewOptions aDlgOpt( E_WINDOW, String::CreateFromInt32( RID_NAVIGATOR ) ); + if ( aDlgOpt.Exists() )
+ m_pReportExplorer->SetWindowState( ByteString( aDlgOpt.GetWindowState().getStr(), RTL_TEXTENCODING_ASCII_US ) ); m_pReportExplorer->AddEventListener(LINK(&rReportController,OReportController,EventLstHdl)); notifySystemWindow(this,m_pReportExplorer,::comphelper::mem_fun(&TaskPaneList::AddWindow)); } @@ -592,6 +601,9 @@ void ODesignView::toggleAddField() xReport = xSection->getReportDefinition(); } m_pAddField = new OAddFieldWindow(rReportController,this); + SvtViewOptions aDlgOpt( E_WINDOW, String::CreateFromInt32( UID_RPT_RPT_APP_VIEW ) );
+ if ( aDlgOpt.Exists() )
+ m_pAddField->SetWindowState( ByteString( aDlgOpt.GetWindowState().getStr(), RTL_TEXTENCODING_ASCII_US ) );
m_pAddField->Update(); m_pAddField->AddEventListener(LINK(&rReportController,OReportController,EventLstHdl)); notifySystemWindow(this,m_pAddField,::comphelper::mem_fun(&TaskPaneList::AddWindow)); diff --git a/reportdesign/source/ui/report/ReportController.cxx b/reportdesign/source/ui/report/ReportController.cxx index 2bb3d3d5dbc8..0cfad2e26341 100644 --- a/reportdesign/source/ui/report/ReportController.cxx +++ b/reportdesign/source/ui/report/ReportController.cxx @@ -2952,7 +2952,6 @@ void OReportController::createControl(const Sequence< PropertyValue >& _aArgs,co ,NULL,NULL,_nObjectId,::rtl::OUString(),ReportInventor,OBJ_DLG_FIXEDTEXT, NULL,pSectionWindow->getReportSection().getPage(),m_aReportModel.get(), pLabel,pControl); - delete pLabel; pNewControl = pControl; @@ -2975,7 +2974,11 @@ void OReportController::createControl(const Sequence< PropertyValue >& _aArgs,co { if ( xInfo->hasPropertyByName(sProps[i]) && xShapeInfo->hasPropertyByName(sProps[i]) ) xUnoProp->setPropertyValue(sProps[i],xShapeProp->getPropertyValue(sProps[i])); - } + } // for(size_t i = 0; i < sizeof(sProps)/sizeof(sProps[0]);++i) + + if ( xInfo->hasPropertyByName(PROPERTY_BORDER) && xShapeInfo->hasPropertyByName(PROPERTY_CONTROLBORDER) ) + xUnoProp->setPropertyValue(PROPERTY_BORDER,xShapeProp->getPropertyValue(PROPERTY_CONTROLBORDER)); + if ( xInfo->hasPropertyByName(PROPERTY_DATAFIELD) && _sFunction.getLength() ) { @@ -3279,7 +3282,10 @@ void OReportController::addPairControls(const Sequence< PropertyValue >& aArgs) ReportFormula aFormula( ReportFormula::Field, sName ); xUnoProp->setPropertyValue( PROPERTY_DATAFIELD, uno::makeAny( aFormula.getCompleteFormula() ) ); - } + } // if ( xInfo->hasPropertyByName(PROPERTY_DATAFIELD) ) + + if ( xInfo->hasPropertyByName(PROPERTY_BORDER) && xShapeInfo->hasPropertyByName(PROPERTY_CONTROLBORDER) ) + xUnoProp->setPropertyValue(PROPERTY_BORDER,xShapeProp->getPropertyValue(PROPERTY_CONTROLBORDER)); pObjs[i]->CreateMediator(sal_True); // need SectionView from the above or follow Section diff --git a/reportdesign/source/ui/report/ReportSection.cxx b/reportdesign/source/ui/report/ReportSection.cxx index cf462c8b1456..570574e4c51d 100644 --- a/reportdesign/source/ui/report/ReportSection.cxx +++ b/reportdesign/source/ui/report/ReportSection.cxx @@ -50,6 +50,7 @@ #include <svx/svditer.hxx> #include <svx/dbaexchange.hxx> +#include <vcl/svapp.hxx> #include <com/sun/star/datatransfer/clipboard/XClipboard.hpp> #include <toolkit/helper/convert.hxx> @@ -69,6 +70,7 @@ #include <svtools/itempool.hxx> #include <svtools/extcolorcfg.hxx> #include <unotools/confignode.hxx> +#include <framework/imageproducer.hxx> // ============================================================================= namespace rptui @@ -460,6 +462,39 @@ void OReportSection::SelectAll(const sal_uInt16 _nObjectType) } } } +void lcl_insertMenuItemImages(PopupMenu& rContextMenu,OReportController& rController,const uno::Reference< report::XReportDefinition>& _xReportDefinition,uno::Reference<frame::XFrame>& _rFrame,BOOL _bHiContrast) +{ + const USHORT nCount = rContextMenu.GetItemCount(); + for (USHORT i = 0; i < nCount; ++i) + { + if ( MENUITEM_SEPARATOR != rContextMenu.GetItemType(i)) + { + const USHORT nId = rContextMenu.GetItemId(i); + PopupMenu* pPopupMenu = rContextMenu.GetPopupMenu( nId ); + if ( pPopupMenu ) + { + lcl_insertMenuItemImages(*pPopupMenu,rController,_xReportDefinition,_rFrame,_bHiContrast); + } + else + { + const ::rtl::OUString sCommand = rContextMenu.GetItemCommand(nId); + rContextMenu.SetItemImage(nId,framework::GetImageFromURL(_rFrame,sCommand,FALSE,_bHiContrast)); + if ( nId == SID_PAGEHEADERFOOTER ) + { + String sText = String(ModuleRes((_xReportDefinition.is() && _xReportDefinition->getPageHeaderOn()) ? RID_STR_PAGEHEADERFOOTER_DELETE : RID_STR_PAGEHEADERFOOTER_INSERT)); + rContextMenu.SetItemText(nId,sText); + } + else if ( nId == SID_REPORTHEADERFOOTER ) + { + String sText = String(ModuleRes((_xReportDefinition.is() && _xReportDefinition->getReportHeaderOn()) ? RID_STR_REPORTHEADERFOOTER_DELETE : RID_STR_REPORTHEADERFOOTER_INSERT)); + rContextMenu.SetItemText(nId,sText); + } + } + rContextMenu.CheckItem(nId,rController.isCommandChecked(nId)); + rContextMenu.EnableItem(nId,rController.isCommandEnabled(nId)); + } + } // for (USHORT i = 0; i < nCount; ++i) +} //---------------------------------------------------------------------------- void OReportSection::Command( const CommandEvent& _rCEvt ) { @@ -468,29 +503,15 @@ void OReportSection::Command( const CommandEvent& _rCEvt ) { case COMMAND_CONTEXTMENU: { + const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings(); + BOOL bHiContrast = rSettings.GetMenuColor().IsDark(); OReportController& rController = m_pParent->getViewsWindow()->getView()->getReportView()->getController(); + uno::Reference<frame::XFrame> xFrame = rController.getFrame(); PopupMenu aContextMenu( ModuleRes( RID_MENU_REPORT ) ); uno::Reference< report::XReportDefinition> xReportDefinition = getSection()->getReportDefinition(); - const USHORT nCount = aContextMenu.GetItemCount(); - for (USHORT i = 0; i < nCount; ++i) - { - if ( MENUITEM_SEPARATOR != aContextMenu.GetItemType(i)) - { - const USHORT nId = aContextMenu.GetItemId(i); - if ( nId == SID_PAGEHEADERFOOTER ) - { - String sText = String(ModuleRes((xReportDefinition.is() && xReportDefinition->getPageHeaderOn()) ? RID_STR_PAGEHEADERFOOTER_DELETE : RID_STR_PAGEHEADERFOOTER_INSERT)); - aContextMenu.SetItemText(nId,sText); - } - else if ( nId == SID_REPORTHEADERFOOTER ) - { - String sText = String(ModuleRes((xReportDefinition.is() && xReportDefinition->getReportHeaderOn()) ? RID_STR_REPORTHEADERFOOTER_DELETE : RID_STR_REPORTHEADERFOOTER_INSERT)); - aContextMenu.SetItemText(nId,sText); - } - aContextMenu.CheckItem(nId,rController.isCommandChecked(nId)); - aContextMenu.EnableItem(nId,rController.isCommandEnabled(nId)); - } - } // for (USHORT i = 0; i < nCount; ++i) + + lcl_insertMenuItemImages(aContextMenu,rController,xReportDefinition,xFrame,bHiContrast); + Point aPos = _rCEvt.GetMousePosPixel(); m_pView->EndAction(); const USHORT nId = aContextMenu.Execute(this, aPos); diff --git a/reportdesign/util/makefile.mk b/reportdesign/util/makefile.mk index 293fb8691873..10f0836710e6 100644 --- a/reportdesign/util/makefile.mk +++ b/reportdesign/util/makefile.mk @@ -131,6 +131,7 @@ SHL2STDLIBS= \ $(COMPHELPERLIB) \ $(CPPUHELPERLIB) \ $(CPPULIB) \ + $(FWELIB) \ $(SO2LIB) \ $(I18NISOLANGLIB) \ $(SALLIB) |