динамический отчет и джасперотчет в ваадин стримресурсе - PullRequest
1 голос
/ 05 июля 2010

STACKOVERFLOW - мой конечный пункт назначения для моих вопросов.Форум Vaadin очень тихий, и в динамических отчетах нет форума.

У меня проблема с интеграцией динамических отчетов, основанных на jasperreport, с классом vaadin с именем "Embedded".Класс "Embedded" нуждается в объекте StreamResource, и все будет завершено с помощью функции getStream (), которая в моем случае никогда не будет вызвана.

Вот мой код:

//
//
//
public void build(Application app) throws IOException, DRException {

    final JasperReportBuilder report = DynamicReports.report();
    report.addColumn(Columns.column("Item",       "item",      DataTypes.stringType()));
    report.addColumn(Columns.column("Quantity",   "quantity",  DataTypes.integerType()));
    report.addColumn(Columns.column("Unit price", "unitprice", DataTypes.bigDecimalType()));
    report.addTitle(Components.text("Getting started"));
    report.addPageFooter(Components.pageXofY());
    report.setDataSource(createDataSource());

    StreamResource.StreamSource resstream = new filePDF(report);
    StreamResource ress = new StreamResource(resstream, "abc.pdf", app);

    //
    ress.setMIMEType("application/pdf");

    //
    Embedded c = new Embedded("Title", ress);
    c.setSource(ress);
    c.setMimeType("application/pdf");
    c.setType(Embedded.TYPE_BROWSER);
    c.setSizeFull();
    c.setHeight("800px");
    c.setParameter("Content-Disposition", "attachment; filename=" + ress.getFilename());

    //
    app.getMainWindow().removeAllComponents();
    app.getMainWindow().addComponent(c);
}

//
//
//
private JRDataSource createDataSource() {
    DataSource dataSource = new DataSource("item", "quantity", "unitprice");

    dataSource.add("Notebook", 1, new BigDecimal(500));
    dataSource.add("DVD", 5, new BigDecimal(30));
    dataSource.add("DVD", 1, new BigDecimal(28));
    dataSource.add("DVD", 5, new BigDecimal(32));
    dataSource.add("Book", 3, new BigDecimal(11));
    dataSource.add("Book", 1, new BigDecimal(15));
    dataSource.add("Book", 5, new BigDecimal(10));
    dataSource.add("Book", 8, new BigDecimal(9));
    return (JRDataSource) dataSource;
}

это класс "filePDF":

/**
 * 
 */
package com.example.postgrekonek;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;

import com.vaadin.Application;
import com.vaadin.terminal.StreamResource;

/**
 * @author hehehe
 *
 */
public class filePDF implements StreamResource.StreamSource {

    private JasperReportBuilder report;

    //
    public filePDF(final JasperReportBuilder rpt) {
        report = rpt;
    }

    @Override
    public InputStream getStream() {
        //
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        //
        //os.write(JasperRunManager.runReportToPdf(report.toJasperReport(), new HashMap()));
        try {
            report.toPdf(os);
            try {
                os.flush();
            } catch (IOException e) {
                //
                e.printStackTrace();
            }
        } catch (DRException e) {
            //
            e.printStackTrace();
        }
        return new ByteArrayInputStream(os.toByteArray());
    }

}

А это класс "Источник данных":

/* Dynamic reports - Free Java reporting library for creating reports dynamically
 *
 * (C) Copyright 2010 Ricardo Mariaca
 *
 * http://dynamicreports.sourceforge.net
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
 * USA. 
 */
package net.sf.dynamicreports.examples;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

/**
 * @author Ricardo Mariaca (dynamicreports@gmail.com)
 */
public class DataSource implements JRDataSource {
    private String[] columns;
    private List<Map<String, Object>> values;
    private Iterator<Map<String, Object>> iterator;
    private Map<String, Object> currentRecord;

    public DataSource(String ...columns) {  
        this.columns = columns;
        this.values = new ArrayList<Map<String, Object>>();     
    }

    public void add(Object ...values) {
        Map<String, Object> row = new HashMap<String, Object>();
        for (int i = 0; i < values.length; i++) {
            row.put(columns[i], values[i]);
        }
        this.values.add(row);
    }

    public Object getFieldValue(JRField field) throws JRException {
        return currentRecord.get(field.getName());
    }

    public boolean next() throws JRException {
        if (iterator == null) {
            this.iterator = values.iterator();
        }
        boolean hasNext = iterator.hasNext();           
        if (hasNext) {
            currentRecord = iterator.next();
        }
        return hasNext;
    }       
}

1 Ответ

1 голос
/ 06 июля 2010

Возможно, это проблема кеша браузера.Вы пробовали использовать ress.setCacheTime (1)?

Для более эффективной потоковой передачи вы должны взглянуть на http://ostermiller.org/convert_java_outputstream_inputstream.html Коротко добавить поток производителя для обработки вывода отчета и использовать циклический буфер для размещения его в качестве ввода.

...