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/java | |
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/java')
5 files changed, 2479 insertions, 2481 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);
+ }
+
+
+ }
+}
|