Source Code Cross Referenced for JFreeReportPublishOnServerExporter.java in  » Report » pentaho-report » org » pentaho » reportdesigner » crm » report » reportexporter » jfreereport » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Report » pentaho report » org.pentaho.reportdesigner.crm.report.reportexporter.jfreereport 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Copyright 2006-2007 Pentaho Corporation.  All rights reserved.
003:         * This software was developed by Pentaho Corporation and is provided under the terms
004:         * of the Mozilla Public License, Version 1.1, or any later version. You may not use
005:         * this file except in compliance with the license. If you need a copy of the license,
006:         * please go to http://www.mozilla.org/MPL/MPL-1.1.txt.
007:         *
008:         * Software distributed under the Mozilla Public License is distributed on an "AS IS"
009:         * basis, WITHOUT WARRANTY OF ANY KIND, either express or  implied. Please refer to
010:         * the license for the specific language governing your rights and limitations.
011:         *
012:         * Additional Contributor(s): Martin Schmid gridvision engineering GmbH
013:         */
014:        package org.pentaho.reportdesigner.crm.report.reportexporter.jfreereport;
015:
016:        import org.apache.commons.httpclient.Credentials;
017:        import org.apache.commons.httpclient.HttpClient;
018:        import org.apache.commons.httpclient.HttpStatus;
019:        import org.apache.commons.httpclient.UsernamePasswordCredentials;
020:        import org.apache.commons.httpclient.auth.AuthScope;
021:        import org.apache.commons.httpclient.methods.PostMethod;
022:        import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
023:        import org.apache.commons.httpclient.methods.multipart.FilePart;
024:        import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
025:        import org.apache.commons.httpclient.methods.multipart.Part;
026:        import org.apache.commons.lang.StringUtils;
027:        import org.gjt.xpp.XmlPullNode;
028:        import org.gjt.xpp.XmlPullParser;
029:        import org.gjt.xpp.XmlPullParserFactory;
030:        import org.jetbrains.annotations.NonNls;
031:        import org.jetbrains.annotations.NotNull;
032:        import org.jetbrains.annotations.Nullable;
033:        import org.jfree.report.AbstractReportDefinition;
034:        import org.jfree.report.DataFactory;
035:        import org.jfree.report.DataRow;
036:        import org.jfree.report.JFreeReport;
037:        import org.jfree.report.ReportDataFactoryException;
038:        import org.jfree.report.modules.parser.ext.factory.base.ArrayClassFactory;
039:        import org.jfree.report.modules.parser.ext.factory.base.URLClassFactory;
040:        import org.jfree.report.modules.parser.ext.factory.datasource.DefaultDataSourceFactory;
041:        import org.jfree.report.modules.parser.ext.factory.elements.DefaultElementFactory;
042:        import org.jfree.report.modules.parser.ext.factory.objects.BandLayoutClassFactory;
043:        import org.jfree.report.modules.parser.ext.factory.objects.DefaultClassFactory;
044:        import org.jfree.report.modules.parser.ext.factory.stylekey.DefaultStyleKeyFactory;
045:        import org.jfree.report.modules.parser.ext.factory.stylekey.PageableLayoutStyleKeyFactory;
046:        import org.jfree.report.modules.parser.ext.factory.templates.DefaultTemplateCollection;
047:        import org.jfree.report.modules.parser.extwriter.ReportWriter;
048:        import org.jfree.report.util.ReportConfiguration;
049:        import org.jfree.xmlns.parser.AbstractXmlResourceFactory;
050:        import org.pentaho.reportdesigner.crm.report.ReportDialogConstants;
051:        import org.pentaho.reportdesigner.crm.report.datasetplugin.multidataset.JNDISource;
052:        import org.pentaho.reportdesigner.crm.report.datasetplugin.multidataset.MultiDataSetReportElement;
053:        import org.pentaho.reportdesigner.crm.report.model.Report;
054:        import org.pentaho.reportdesigner.crm.report.model.ReportElement;
055:        import org.pentaho.reportdesigner.crm.report.model.StaticImageReportElement;
056:        import org.pentaho.reportdesigner.crm.report.model.SubReport;
057:        import org.pentaho.reportdesigner.crm.report.model.dataset.DataSetsReportElement;
058:        import org.pentaho.reportdesigner.crm.report.reportelementinfo.ReportElementInfoFactory;
059:        import org.pentaho.reportdesigner.crm.report.reportexporter.ReportExporter;
060:        import org.pentaho.reportdesigner.crm.report.util.XMLContextKeys;
061:        import org.pentaho.reportdesigner.lib.client.i18n.TranslationManager;
062:        import org.pentaho.reportdesigner.lib.client.util.IOUtil;
063:        import org.pentaho.reportdesigner.lib.client.util.UncaughtExcpetionsModel;
064:        import org.pentaho.reportdesigner.lib.common.xml.XMLConstants;
065:        import org.pentaho.reportdesigner.lib.common.xml.XMLContext;
066:        import org.pentaho.reportdesigner.lib.common.xml.XMLWriter;
067:
068:        import javax.swing.table.TableModel;
069:        import java.io.BufferedReader;
070:        import java.io.ByteArrayInputStream;
071:        import java.io.ByteArrayOutputStream;
072:        import java.io.File;
073:        import java.io.FileFilter;
074:        import java.io.FileInputStream;
075:        import java.io.FileNotFoundException;
076:        import java.io.FileOutputStream;
077:        import java.io.IOException;
078:        import java.io.InputStream;
079:        import java.io.InputStreamReader;
080:        import java.io.OutputStreamWriter;
081:        import java.lang.reflect.Field;
082:        import java.net.URL;
083:        import java.net.URLEncoder;
084:        import java.security.MessageDigest;
085:        import java.util.ArrayList;
086:        import java.util.Arrays;
087:        import java.util.Properties;
088:        import java.util.logging.Level;
089:        import java.util.logging.Logger;
090:
091:        /**
092:         * User: Martin Date: 28.10.2005 Time: 08:37:52
093:         */
094:        public class JFreeReportPublishOnServerExporter extends ReportExporter {
095:            @NonNls
096:            @NotNull
097:            private static final Logger LOG = Logger
098:                    .getLogger(JFreeReportPublishOnServerExporter.class
099:                            .getName());
100:
101:            @NotNull
102:            private String reportNameString;
103:
104:            @NotNull
105:            private String publishLocation;
106:
107:            @NotNull
108:            private String type;
109:
110:            @NotNull
111:            private String webPublishURL;
112:
113:            private boolean publishXActionFile;
114:
115:            @NotNull
116:            private char[] publishPassword;
117:
118:            @NotNull
119:            private String serverUserId;
120:
121:            @NotNull
122:            private char[] serverPassword;
123:
124:            private boolean useJNDIName;
125:
126:            @NotNull
127:            private String message = "";
128:
129:            public JFreeReportPublishOnServerExporter(@NotNull
130:            String reportNameString, @NotNull
131:            String publishLocation, @NotNull
132:            String type, @NotNull
133:            String webPublishURL, boolean publishXActionFile, @NotNull
134:            char[] publishPassword, @NotNull
135:            String serverUserId, @NotNull
136:            char[] serverPassword, boolean useJNDIName) {
137:                //noinspection ConstantConditions
138:                if (reportNameString == null) {
139:                    throw new IllegalArgumentException(
140:                            "reportNameString must not be null");
141:                }
142:                //noinspection ConstantConditions
143:                if (publishLocation == null) {
144:                    throw new IllegalArgumentException(
145:                            "publishLocation must not be null");
146:                }
147:                //noinspection ConstantConditions
148:                if (type == null) {
149:                    throw new IllegalArgumentException("type must not be null");
150:                }
151:                //noinspection ConstantConditions
152:                if (webPublishURL == null) {
153:                    throw new IllegalArgumentException(
154:                            "webPublishURL must not be null");
155:                }
156:                //noinspection ConstantConditions
157:                if (publishPassword == null) {
158:                    throw new IllegalArgumentException(
159:                            "publishPassword must not be null");
160:                }
161:                //noinspection ConstantConditions
162:                if (serverUserId == null) {
163:                    throw new IllegalArgumentException(
164:                            "serverUserId must not be null");
165:                }
166:                //noinspection ConstantConditions
167:                if (serverPassword == null) {
168:                    throw new IllegalArgumentException(
169:                            "serverPassword must not be null");
170:                }
171:
172:                this .reportNameString = reportNameString;
173:                this .publishLocation = publishLocation;
174:                this .type = type;
175:                this .webPublishURL = webPublishURL;
176:                this .publishXActionFile = publishXActionFile;
177:                this .publishPassword = publishPassword;
178:                this .serverUserId = serverUserId;
179:                this .serverPassword = serverPassword;
180:                this .useJNDIName = useJNDIName;
181:            }
182:
183:            @NotNull
184:            public Report loadReport(@NotNull
185:            File reportFile) {
186:                Report report = ReportElementInfoFactory.getInstance()
187:                        .getReportReportElementInfo().createReportElement();
188:                try {
189:                    BufferedReader bufferedReader;
190:                    XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory
191:                            .newInstance();
192:                    XmlPullParser xmlPullParser = xmlPullParserFactory
193:                            .newPullParser();
194:                    // noinspection IOResourceOpenedButNotSafelyClosed
195:                    bufferedReader = new BufferedReader(new InputStreamReader(
196:                            new FileInputStream(reportFile),
197:                            XMLConstants.ENCODING));
198:                    xmlPullParser.setInput(bufferedReader);
199:                    XMLContext xmlContext = new XMLContext();
200:                    XMLContextKeys.CONTEXT_PATH.putObject(xmlContext,
201:                            reportFile.getParentFile());
202:                    XmlPullNode node;
203:                    xmlPullParser.next(); // get first start tag
204:                    node = xmlPullParserFactory.newPullNode(xmlPullParser);
205:                    // Thread.sleep(15000);//for testing purposes only
206:                    if (XMLConstants.REPORT.equals(node.getRawName())) {
207:                        report.readObject(node, xmlContext);
208:                    }
209:                    node.resetPullNode();
210:                } catch (Exception e) {
211:                    if (LOG.isLoggable(Level.FINE))
212:                        LOG
213:                                .log(
214:                                        Level.FINE,
215:                                        "JFreeReportPublishOnServerExporter.loadReport ",
216:                                        e);
217:                }
218:                return report;
219:            }
220:
221:            public void exportReport(boolean isSubReport, @NotNull
222:            Report report) throws PublishException {
223:                if (report == null) {
224:                    throw new IllegalArgumentException(
225:                            "report must not be null");
226:                }
227:                try {
228:                    // create a copy, so we can modify names, some paths and so on without affecting the original report displayed in
229:                    // the designer
230:                    Report newReport = createDeepCopy(report);
231:                    newReport.setName(reportNameString);
232:                    ArrayList<File> filesToCopyToServer = new ArrayList<File>();
233:                    File reportDirectory = new File(System
234:                            .getProperty(ReportDialogConstants.USER_HOME),
235:                            ReportDialogConstants.REPORT_DIRECTORY);
236:                    File tempDirectory = new File(reportDirectory, "temp");// NON-NLS
237:                    tempDirectory.mkdir();
238:                    //
239:                    // MB - Publish Location should NOT start with a leading "/"
240:                    // PRD-113
241:                    //
242:                    String correctedPublishLocation = publishLocation;
243:                    if (correctedPublishLocation.startsWith("/")) {
244:                        correctedPublishLocation = correctedPublishLocation
245:                                .substring(1);
246:                    }
247:                    if (!correctedPublishLocation.endsWith("/")) {
248:                        correctedPublishLocation = correctedPublishLocation
249:                                + "/";
250:                    }
251:                    // write the images out first, because we will be updating the image elements
252:                    // this must be done before the report is written (or it will not be updated when saved)
253:
254:                    //ArrayList<SubReportElement> subReportElements = new ArrayList<SubReportElement>();
255:                    //getSubReportElements(newReport, subReportElements);
256:                    //for (int i = 0; i < subReportElements.size(); i++)
257:                    //{
258:                    //    SubReportElement subReportElement = subReportElements.get(i);
259:                    //    // System.out.println(subReportElement.getFilePath().getPath());
260:                    //}
261:
262:                    byte[] buffer = new byte[8192];
263:                    try {
264:                        ArrayList<StaticImageReportElement> imageElements = new ArrayList<StaticImageReportElement>();
265:                        getImageElements(newReport, imageElements);
266:                        URL serverURL = new URL(webPublishURL);
267:                        for (int i = 0; i < imageElements.size(); i++) {
268:                            // roll through all images
269:                            StaticImageReportElement imageElement = imageElements
270:                                    .get(i);
271:                            if (!"http".equals(imageElement.getUrl()
272:                                    .getProtocol()))// NON-NLS
273:                            {
274:                                // for all file urls, update them to the new location and write their contents as well to the
275:                                // "tempDirectory" from above
276:                                InputStream is = imageElement.getUrl()
277:                                        .openStream();
278:                                FileOutputStream fos = null;
279:                                File destFile = new File(
280:                                        tempDirectory,
281:                                        newReport.getName().replace(' ', '_')
282:                                                + "_staticImage"
283:                                                + i
284:                                                + imageElement
285:                                                        .getUrl()
286:                                                        .getFile()
287:                                                        .substring(
288:                                                                imageElement
289:                                                                        .getUrl()
290:                                                                        .getFile()
291:                                                                        .lastIndexOf(
292:                                                                                '.')));// NON-NLS
293:                                try {
294:                                    // noinspection IOResourceOpenedButNotSafelyClosed
295:                                    fos = new FileOutputStream(destFile);
296:                                    int len;
297:                                    while ((len = is.read(buffer)) != -1) {
298:                                        fos.write(buffer, 0, len);
299:                                    }
300:                                    filesToCopyToServer.add(destFile);
301:                                } finally {
302:                                    IOUtil.closeStream(is);
303:                                    IOUtil.closeStream(fos);
304:                                }
305:                                // create the URL the best we can, taking advantage of the platform putting in parser-config settings
306:                                // the setting we are targetting is ${hostColonPort}
307:                                URL url = new URL(
308:                                        serverURL.getProtocol()
309:                                                + "://${hostColonPort}/pentaho/GetResource?resource="
310:                                                + correctedPublishLocation
311:                                                + destFile.getName());// NON-NLS
312:                                imageElement.setUrl(url);
313:                            }
314:                        }
315:                    } catch (Throwable e) {
316:                        if (LOG.isLoggable(Level.FINE))
317:                            LOG
318:                                    .log(
319:                                            Level.FINE,
320:                                            "JFreeReportPublishOnServerExporter.exportReport ",
321:                                            e);
322:                    }
323:                    JFreeReportVisitor reportVisitor = new JFreeReportVisitor();
324:                    newReport.accept(null, reportVisitor);
325:                    JFreeReport jFreeReport = reportVisitor.getJFreeReport();
326:                    final ReportConfiguration config = new ReportConfiguration(
327:                            jFreeReport.getReportConfiguration());
328:                    config.setConfigProperty(
329:                            AbstractXmlResourceFactory.CONTENTBASE_KEY,
330:                            new File(".").toURI().toURL().toExternalForm());
331:                    jFreeReport.getReportConfiguration().setConfigProperty(
332:                            "org.jfree.report.NoPrinterAvailable",
333:                            Boolean.TRUE.toString());
334:                    // MB - 6/9/07 - Hack Alert PRD-144
335:                    //
336:                    // There is a bug in the JFreeReport writer for the XML that causes an
337:                    // empty <data-factory/> tag to be written to the exported XML. As a
338:                    // result, the report cannot be read in and parsed by the platform. So,
339:                    // I put in the following hack which needs to be removed when the JFreeReport
340:                    // engine has been properly fixed.
341:                    //
342:                    hackReport(jFreeReport);
343:
344:                    if (newReport.isUseMaxCharBounds()) {
345:                        config
346:                                .setConfigProperty(
347:                                        "org.jfree.report.layout.fontrenderer.UseMaxCharBounds",
348:                                        Boolean.TRUE.toString());// NON-NLS
349:                    }
350:                    final ReportWriter writer = new ReportWriter(jFreeReport,
351:                            XMLConstants.ENCODING, config);
352:                    writer.addClassFactoryFactory(new URLClassFactory());
353:                    writer.addClassFactoryFactory(new DefaultClassFactory());
354:                    writer.addClassFactoryFactory(new BandLayoutClassFactory());
355:                    writer.addClassFactoryFactory(new ArrayClassFactory());
356:                    writer.addStyleKeyFactory(new DefaultStyleKeyFactory());
357:                    writer
358:                            .addStyleKeyFactory(new PageableLayoutStyleKeyFactory());
359:                    writer
360:                            .addTemplateCollection(new DefaultTemplateCollection());
361:                    writer.addElementFactory(new DefaultElementFactory());
362:                    writer.addDataSourceFactory(new DefaultDataSourceFactory());
363:                    // export the JFreeReport xml
364:                    File jFreeReportFile = new File(tempDirectory, newReport
365:                            .getName()
366:                            + ReportDialogConstants.XML_FILE_ENDING);// NON-NLS
367:                    OutputStreamWriter outputStreamWriter = null;
368:                    try {
369:                        // noinspection IOResourceOpenedButNotSafelyClosed
370:                        outputStreamWriter = new OutputStreamWriter(
371:                                new FileOutputStream(jFreeReportFile),
372:                                XMLConstants.ENCODING);
373:                        writer.write(outputStreamWriter);
374:                    } finally {
375:                        IOUtil.closeStream(outputStreamWriter);
376:                    }
377:                    // export the xaction xml
378:                    File xactionFile = new File(tempDirectory, newReport
379:                            .getName()
380:                            + ReportDialogConstants.XACTION_FILE_ENDING);// NON-NLS
381:                    try {
382:                        // noinspection IOResourceOpenedButNotSafelyClosed
383:                        outputStreamWriter = new OutputStreamWriter(
384:                                new FileOutputStream(xactionFile),
385:                                XMLConstants.ENCODING);
386:                        DataSetsReportElement dataSetsReportElement = newReport
387:                                .getDataSetsReportElement();
388:
389:                        String publishSolutionLocation = correctedPublishLocation
390:                                .substring(0, correctedPublishLocation
391:                                        .indexOf('/'));
392:
393:                        String xactionContent = XActionHelper.getXActionFile(
394:                                xactionFile.getName(), publishSolutionLocation,
395:                                newReport.getName(), "", type, jFreeReportFile
396:                                        .getName(), useJNDIName,
397:                                dataSetsReportElement);
398:                        outputStreamWriter.write(xactionContent);
399:                    } finally {
400:                        IOUtil.closeStream(outputStreamWriter);
401:                    }
402:
403:                    // export all mondrian cube files and xquery data files
404:                    for (ReportElement reportElement : newReport
405:                            .getDataSetsReportElement().getChildren()) {
406:                        if (reportElement instanceof  MultiDataSetReportElement) {
407:                            MultiDataSetReportElement multiDataSetReportElement = (MultiDataSetReportElement) reportElement;
408:                            if (!StringUtils.isEmpty(multiDataSetReportElement
409:                                    .getMondrianCubeDefinitionFile())) {
410:                                filesToCopyToServer
411:                                        .add(new File(
412:                                                multiDataSetReportElement
413:                                                        .getMondrianCubeDefinitionFile()));
414:                            }
415:                            if (!StringUtils.isEmpty(multiDataSetReportElement
416:                                    .getXQueryDataFile())) {
417:                                filesToCopyToServer.add(new File(
418:                                        multiDataSetReportElement
419:                                                .getXQueryDataFile()));
420:                            }
421:                        }
422:                    }
423:                    // export the properties
424:                    Properties properties = new Properties();
425:                    properties.setProperty("title", newReport.getName());// NON-NLS
426:                    properties.setProperty("description", "");// NON-NLS
427:                    ArrayList<ReportElement> resourceElements = new ArrayList<ReportElement>();
428:                    getResourceElements(newReport, resourceElements);
429:                    FileFilter bundleFilter = new FileFilter() {
430:                        public boolean accept(@NotNull
431:                        File pathname) {
432:                            return pathname.getName().endsWith(".properties");// NON-NLS
433:                        }
434:                    };
435:                    if (newReport.getResourceBundleClasspath() != null) {
436:                        File folder = new File(newReport
437:                                .getResourceBundleClasspath().toURI());
438:                        // give me a list of *ALL* resource files for this guys resource base
439:                        File[] propertiesFiles = folder.listFiles(bundleFilter);
440:                        if (propertiesFiles != null) {
441:                            filesToCopyToServer.addAll(Arrays
442:                                    .asList(propertiesFiles));
443:                        }
444:
445:                    }
446:                    File propertiesFile = new File(tempDirectory, URLEncoder
447:                            .encode(newReport.getName(), "UTF-8")
448:                            + ".properties");// NON-NLS
449:                    FileOutputStream out = null;
450:                    try {
451:                        // noinspection IOResourceOpenedButNotSafelyClosed
452:                        out = new FileOutputStream(propertiesFile);
453:                        properties.store(out, null);
454:                    } finally {
455:                        IOUtil.closeStream(out);
456:                    }
457:                    // prepare the XQuery data file
458:                    // prepare the mondrian definition file
459:                    // prepare the local image files
460:                    filesToCopyToServer.add(jFreeReportFile);
461:                    if (publishXActionFile) {
462:                        filesToCopyToServer.add(xactionFile);
463:                    }
464:                    filesToCopyToServer.add(propertiesFile);
465:                    // copy everyting to the server
466:                    publish(webPublishURL, correctedPublishLocation,
467:                            filesToCopyToServer
468:                                    .toArray(new File[filesToCopyToServer
469:                                            .size()]), null);
470:                } catch (Exception e) {
471:                    throw new PublishException(e.getMessage(), e);
472:                }
473:            }
474:
475:            @NotNull
476:            public String getMessage() {
477:                return message;
478:            }
479:
480:            @NotNull
481:            private Report createDeepCopy(@NotNull
482:            Report report) throws Exception {
483:                // this IO stuff needs no native resources, so don't bother closing streams
484:                ByteArrayOutputStream baos = new ByteArrayOutputStream(
485:                        50 * 1024);// 50 KB
486:                XMLContext xmlContext = new XMLContext();
487:                XMLWriter xmlWriter = new XMLWriter(baos, true);
488:                xmlWriter.writeDefaultProlog();
489:                if (report instanceof  SubReport) {
490:                    xmlWriter.startElement(XMLConstants.SUBREPORT);
491:                    report.externalizeObject(xmlWriter, xmlContext);
492:                    xmlWriter.closeElement(XMLConstants.SUBREPORT);
493:                } else {
494:                    xmlWriter.startElement(XMLConstants.REPORT);
495:                    report.externalizeObject(xmlWriter, xmlContext);
496:                    xmlWriter.closeElement(XMLConstants.REPORT);
497:                }
498:                xmlWriter.close();
499:                XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory
500:                        .newInstance();
501:                XmlPullParser xmlPullParser = xmlPullParserFactory
502:                        .newPullParser();
503:                // noinspection IOResourceOpenedButNotSafelyClosed
504:                BufferedReader bufferedReader = new BufferedReader(
505:                        new InputStreamReader(new ByteArrayInputStream(baos
506:                                .toByteArray()), XMLConstants.ENCODING));
507:                xmlPullParser.setInput(bufferedReader);
508:                xmlPullParser.next(); // get first start tag
509:                XmlPullNode node = xmlPullParserFactory
510:                        .newPullNode(xmlPullParser);
511:                Report newReport = ReportElementInfoFactory.getInstance()
512:                        .getReportReportElementInfo().createReportElement();
513:                if (XMLConstants.REPORT.equals(node.getRawName())) {
514:                    newReport.readObject(node, xmlContext);
515:                }
516:                node.resetPullNode();
517:                return newReport;
518:            }
519:
520:            private void publish(@NotNull
521:            String publishURL, @NotNull
522:            String publishPath, @NotNull
523:            File[] publishFiles, @Nullable
524:            JNDISource dataSource) throws PublishException {
525:                String fullURL = publishURL + "?publishPath=" + publishPath;// NON-NLS
526:                fullURL += "&publishKey=" + getPasswordKey(new String(publishPassword)); //$NON-NLS-1$
527:                fullURL += "&overwrite=true"; //$NON-NLS-1$
528:                if (dataSource != null) {
529:                    fullURL = fullURL + "&jndiName=" + dataSource.getJndiName();// NON-NLS
530:                    fullURL = fullURL + "&jdbcDriver="
531:                            + dataSource.getDriverClass();// NON-NLS
532:                    fullURL = fullURL + "&jdbcUrl="
533:                            + dataSource.getConnectionString();// NON-NLS
534:                    fullURL = fullURL + "&jdbcUserId="
535:                            + dataSource.getUsername();// NON-NLS
536:                    fullURL = fullURL + "&jdbcPassword="
537:                            + dataSource.getPassword();// NON-NLS
538:                }
539:                PostMethod filePost = new PostMethod(fullURL);
540:                ArrayList<Part> parts = new ArrayList<Part>();
541:                try {
542:                    String[] imagesInJars = new String[] {
543:                            "PentahoReporting.png", "PentahoReportingMDX.png",
544:                            "PentahoReportingXQuery.png" };// NON-NLS
545:                    for (String imageName : imagesInJars) {
546:                        parts
547:                                .add(new FilePart(imageName,
548:                                        new ByteArrayPartSource(imageName,
549:                                                getImageData("/res/icons/"
550:                                                        + imageName))));// NON-NLS
551:                    }
552:                    for (File publishFile : publishFiles) {
553:                        parts.add(new FilePart(publishFile.getName(),
554:                                publishFile));
555:                    }
556:                } catch (FileNotFoundException e) {
557:                    // file is not existing or not readable, this should not happen
558:                    UncaughtExcpetionsModel.getInstance().addException(e);
559:                } catch (IOException e) {
560:                    UncaughtExcpetionsModel.getInstance().addException(e);
561:                }
562:                filePost
563:                        .setRequestEntity(new MultipartRequestEntity(parts
564:                                .toArray(new Part[parts.size()]), filePost
565:                                .getParams()));
566:                HttpClient client = new HttpClient();
567:                // If server userid/password was supplied, use basic authentication to
568:                // authenticate with the server.
569:                if (serverUserId.length() > 0 && serverPassword.length > 0) {
570:                    Credentials creds = new UsernamePasswordCredentials(
571:                            serverUserId, new String(serverPassword));
572:                    client.getState().setCredentials(AuthScope.ANY, creds);
573:                    client.getParams().setAuthenticationPreemptive(true);
574:                }
575:                int status;
576:                try {
577:                    status = client.executeMethod(filePost);
578:                } catch (IOException e) {
579:                    throw new PublishException(e.getMessage(), e);
580:                }
581:                if (status != HttpStatus.SC_OK) {
582:                    if (status == HttpStatus.SC_MOVED_TEMPORARILY) {
583:                        throw new PublishException(
584:                                TranslationManager
585:                                        .getInstance()
586:                                        .getTranslation("R",
587:                                                "JFreeReportPublishOnServerExporter.InvalidUsernameOrPassword"));
588:                    } else {
589:                        throw new PublishException(
590:                                "Unknown server error: HTTP status code "
591:                                        + status);
592:                    }
593:                } else {
594:                    try {
595:                        String postResult = filePost.getResponseBodyAsString();
596:                        int rtn = Integer.parseInt(postResult.trim());
597:                        if (rtn == 3) {
598:                            message = TranslationManager
599:                                    .getInstance()
600:                                    .getTranslation("R",
601:                                            "JFreeReportPublishOnServerExporter.Successful");
602:                        } else if (rtn == 2) {
603:                            message = TranslationManager
604:                                    .getInstance()
605:                                    .getTranslation("R",
606:                                            "JFreeReportPublishOnServerExporter.Failed");
607:                        } else if (rtn == 4) {
608:                            message = TranslationManager
609:                                    .getInstance()
610:                                    .getTranslation("R",
611:                                            "JFreeReportPublishOnServerExporter.InvalidPassword");
612:                        } else if (rtn == 5) {
613:                            message = TranslationManager
614:                                    .getInstance()
615:                                    .getTranslation("R",
616:                                            "JFreeReportPublishOnServerExporter.InvalidUsernameOrPassword");
617:                        } else if (rtn == 1) {
618:                            message = TranslationManager
619:                                    .getInstance()
620:                                    .getTranslation("R",
621:                                            "JFreeReportPublishOnServerExporter.FileExistsOverride");
622:                        }
623:                    } catch (IOException e) {
624:                        throw new PublishException(e);
625:                    }
626:                }
627:            }
628:
629:            /**
630:             * Utility for getting the MD5 hash from the provided key for sending the publishPassword.
631:             *
632:             * @param passWord The password to get an MD5 hash of
633:             * @return zero-padded MD5 hash of the password
634:             */
635:            @Nullable
636:            public static String getPasswordKey(@NotNull
637:            String passWord) {
638:                try {
639:                    MessageDigest md = MessageDigest.getInstance("MD5");// NON-NLS
640:                    md.reset();
641:                    md.update(passWord.getBytes("UTF-8"));// NON-NLS
642:                    byte[] digest = md.digest("P3ntah0Publ1shPa55w0rd"
643:                            .getBytes("UTF-8"));// NON-NLS
644:                    StringBuilder buf = new StringBuilder(digest.length + 1);
645:                    String s;
646:                    for (byte aDigest : digest) {
647:                        s = Integer.toHexString(0xFF & aDigest);
648:                        buf.append((s.length() == 1) ? "0" : "").append(s);
649:                    }
650:                    return buf.toString();
651:                } catch (Exception ex) {
652:                    UncaughtExcpetionsModel.getInstance().addException(ex);
653:                }
654:                return null;
655:            }
656:
657:            @NotNull
658:            private byte[] getImageData(@NotNull
659:            String imageName) throws IOException, PublishException {
660:                InputStream resourceAsStream = null;
661:                try {
662:                    resourceAsStream = getClass()
663:                            .getResourceAsStream(imageName);
664:                    if (resourceAsStream == null) {
665:                        throw new PublishException("Resource is missing "
666:                                + imageName);
667:                    }
668:                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
669:                    byte[] buffer = new byte[8192];
670:                    int len;
671:                    while ((len = resourceAsStream.read(buffer)) != -1) {
672:                        baos.write(buffer, 0, len);
673:                    }
674:                    return baos.toByteArray();
675:                } finally {
676:                    IOUtil.closeStream(resourceAsStream);
677:                }
678:            }
679:
680:            /*
681:             * MB - 6/9/07
682:             *
683:             * This method is temporary, and clearly a hack. The goal is to satisfy a bug in the writer for the report spec - essentially, the two conditions that must be satisfied fort the writer to not write out an empty data-factory tag. The bug
684:             * is in org.jfree.report.modules.parser.reportwriter.DataFactoryWriter, and it has the following flawed logic:
685:             *
686:             * Line 119: if (query == null && dataFactoryClass == null)
687:             *
688:             * should be
689:             *
690:             * if (query == null || dataFactoryClass == null)
691:             *
692:             * As soon as this gets fixed, the hack can be removed. Until then, I have to be sure that the dataFactoryClass is null AND the query is null. The setter for dataFactory now prevents a null set (unlike 0.8.8_01). But, I can satisfy this
693:             * part of the bug by setting a DataFactory that doesn't have a public constructor.
694:             *
695:             * The next part of the hack is that the report.query must be null. Well, the API prevents me from calling report.setQuery(null). The only way to satisfy the problem is to set the field to null. I use reflection below to fix this - first,
696:             * I get the query field, then I force it to be a public variable (setAccessible), and then I set the value to null.
697:             *
698:             * Once these steps are done, then when the report gets written out as XML, the bug will be worked around.
699:             *
700:             */
701:            private void hackReport(@NotNull
702:            JFreeReport report) {
703:                try {
704:                    // First part of the hack - set the data factory to a class that
705:                    // has no public constructor.
706:                    report.setDataFactory(new PlatformDataFactory());
707:
708:                    // Second part of the hack - I need to make sure the query
709:                    // field is null so that an empty data-factory tag doesn't get
710:                    // written to the xml file. This is such a hack, but it shouldn't
711:                    // last for very long.
712:                    Class<AbstractReportDefinition> c2 = AbstractReportDefinition.class;
713:                    Field query = c2.getDeclaredField("query"); //$NON-NLS-1$
714:                    query.setAccessible(true);
715:                    query.set(report, null);
716:
717:                } catch (Exception ex) {
718:                    if (LOG.isLoggable(Level.FINE))
719:                        LOG
720:                                .log(
721:                                        Level.FINE,
722:                                        "JFreeReportPublishOnServerExporter.hackReport ",
723:                                        ex);
724:                }
725:            }
726:
727:            public static class PlatformDataFactory implements  DataFactory {
728:                @Nullable
729:                public TableModel queryData(@Nullable
730:                final String query, @Nullable
731:                final DataRow parameters) throws ReportDataFactoryException {
732:                    return null;
733:                }
734:
735:                @Nullable
736:                public DataFactory derive() throws ReportDataFactoryException {
737:                    return null;
738:                }
739:
740:                public void open() {
741:                }
742:
743:                public void close() {
744:
745:                }
746:
747:                private PlatformDataFactory() {
748:                    super();
749:                }
750:            }
751:
752:        }
w___w___w__.___j__a__va_2___s._co_m_ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.