Search in sources :

Example 1 with ReportParameter

use of au.com.vaadinutils.jasper.parameter.ReportParameter in project VaadinUtils by rlsutton1.

the class ReportEmailRunnerImpl method runReport.

// Logger logger = org.apache.logging.log4j.LogManager.getLogger();
@Override
public boolean runReport(ReportEmailSchedule schedule, Date scheduledTime, JasperEmailSettings emailSettings) throws InterruptedException, IOException, EmailException, InstantiationException, IllegalAccessException, AddressException, ClassNotFoundException, URISyntaxException {
    Preconditions.checkNotNull(schedule.getSendersEmailAddress(), "Missing senders email address.");
    Preconditions.checkNotNull(schedule.getRecipients(), "Missing recipient email address");
    Preconditions.checkArgument(schedule.getRecipients().size() > 0, "Missing recipient email address");
    Class<? extends JasperReportProperties> jrpClass = schedule.getJasperReportPropertiesClass();
    jasperReportProperties = jrpClass.newInstance();
    this.schedule = schedule;
    jasperReportProperties = new JasperReportPropertiesAlternateFile(schedule.getReportTitle(), schedule.getReportFileName(), jasperReportProperties);
    Collection<ReportParameter<?>> params = buildParams(schedule, scheduledTime);
    JasperManager manager = new JasperManager(this);
    if (manager.checkQueueSize() > 0) {
        return false;
    }
    JasperEmailBuilder builder = new JasperEmailBuilder(emailSettings);
    OutputFormat outputFormat = schedule.getOutputFormat();
    RenderedReport export = manager.export(outputFormat, params);
    try {
        AttachmentType attachementType = outputFormat.getAttachementType();
        builder.setFrom(schedule.getSendersEmailAddress().toString()).setSubject(schedule.subject()).setHtmlBody(schedule.message()).addAttachement(export.getBodyAsDataSource(schedule.getReportTitle() + attachementType.getFileExtension(), attachementType));
        for (ReportEmailRecipient address : schedule.getRecipients()) {
            switch(address.getVisibility()) {
                case TO:
                    builder.addTo(address.getEmail());
                    break;
                case CC:
                    builder.addCC(address.getEmail());
                    break;
                case BCC:
                    builder.addBCC(address.getEmail());
                    break;
            }
        }
        builder.send(false);
    } finally {
        export.close();
    }
    return true;
}
Also used : AttachmentType(au.com.vaadinutils.jasper.AttachmentType) ReportParameter(au.com.vaadinutils.jasper.parameter.ReportParameter) ReportEmailRecipient(au.com.vaadinutils.jasper.scheduler.entities.ReportEmailRecipient) JasperManager(au.com.vaadinutils.jasper.JasperManager) OutputFormat(au.com.vaadinutils.jasper.JasperManager.OutputFormat) RenderedReport(au.com.vaadinutils.jasper.RenderedReport) JasperEmailBuilder(au.com.vaadinutils.jasper.JasperEmailBuilder) JasperReportPropertiesAlternateFile(au.com.vaadinutils.jasper.ui.JasperReportPropertiesAlternateFile)

Example 2 with ReportParameter

use of au.com.vaadinutils.jasper.parameter.ReportParameter in project VaadinUtils by rlsutton1.

the class JasperReportLayout method createFavouriteButton.

private void createFavouriteButton(String buttonHeight, HorizontalLayout buttonContainer) {
    favouriteButton = new Button();
    Resource favouriteButtonIcon = reportProperties.getFavouriteButtonIconResource();
    if (favouriteButtonIcon == null) {
        favouriteButtonIcon = new ExternalResource("images/favourite.png");
    }
    favouriteButton.setDescription("Favourite");
    favouriteButton.setIcon(favouriteButtonIcon);
    favouriteButton.setWidth("" + BUTTON_WIDTH);
    favouriteButton.setDisableOnClick(true);
    favouriteButton.setHeight(buttonHeight);
    favouriteButton.addStyleName(ValoTheme.BUTTON_ICON_ONLY);
    favouriteButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);
    favouriteButton.addClickListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            new InputDialog(UI.getCurrent(), "Save Favourite", "Provide a name for the faviourite", new Recipient() {

                @Override
                public boolean onOK(String input) {
                    if (StringUtils.length(input) >= 500) {
                        Notification.show("The name must be less than 500 characters", Type.ERROR_MESSAGE);
                        return false;
                    }
                    Collection<ReportParameter<?>> params = builder.getReportParameters();
                    ReportSave reportSave = new ReportSave();
                    reportSave.setReportClass(reportProperties.getReportClass().getName());
                    reportSave.setUserDescription(input);
                    reportSave.setUser(reportProperties.getUsername());
                    reportSave.setSaveType(SaveType.FAVOURITES);
                    for (ReportParameter<?> param : params) {
                        for (String pname : param.getParameterNames()) {
                            if (StringUtils.isNotBlank(param.getLabel(pname))) {
                                ReportSaveParameter reportSaveparam = new ReportSaveParameter();
                                reportSaveparam.setParameterName(param.getLabel(pname));
                                reportSaveparam.setTextualRepresentation(param.getDisplayValue(pname));
                                reportSaveparam.setParameterValue(param.getValue(pname).toString());
                                reportSaveparam.setMetaData(param.getSaveMetaData());
                                reportSaveparam.setMetaDataComment(param.getMetaDataComment());
                                reportSave.addParameter(reportSaveparam);
                                JpaBaseDao.getEntityManager().persist(reportSaveparam);
                            }
                        }
                    }
                    JpaBaseDao.getEntityManager().persist(reportSave);
                    return true;
                }

                @Override
                public boolean onCancel() {
                    return true;
                }
            });
        }
    });
    buttonContainer.addComponent(favouriteButton);
}
Also used : InputDialog(au.com.vaadinutils.editors.InputDialog) ReportParameter(au.com.vaadinutils.jasper.parameter.ReportParameter) ClickEvent(com.vaadin.ui.Button.ClickEvent) ExternalResource(com.vaadin.server.ExternalResource) StreamResource(com.vaadin.server.StreamResource) Resource(com.vaadin.server.Resource) Recipient(au.com.vaadinutils.editors.Recipient) ExternalResource(com.vaadin.server.ExternalResource) Button(com.vaadin.ui.Button) ClickListener(com.vaadin.ui.Button.ClickListener) ReportSave(au.com.vaadinutils.jasper.scheduler.entities.ReportSave) ReportSaveParameter(au.com.vaadinutils.jasper.scheduler.entities.ReportSaveParameter)

Example 3 with ReportParameter

use of au.com.vaadinutils.jasper.parameter.ReportParameter in project VaadinUtils by rlsutton1.

the class JasperReportLayout method addButtonListener.

private void addButtonListener(Button button, final OutputFormat format) {
    button.addClickListener(new ClickEventLogged.ClickListener() {

        private static final long serialVersionUID = 1L;

        @Override
        public void clicked(ClickEvent event) {
            try {
                createFrequentlyUsed();
                createHistory();
                printButton.setEnabled(false);
                exportButton.setEnabled(false);
                showButton.setEnabled(false);
                for (ExpanderComponent componet : components) {
                    componet.getComponent().setEnabled(false);
                }
                generateReport(format, JasperReportLayout.this.builder.getReportParameters());
            } catch (Exception e) {
                printButton.setEnabled(true);
                exportButton.setEnabled(true);
                showButton.setEnabled(true);
                for (ExpanderComponent componet : components) {
                    componet.getComponent().setEnabled(true);
                }
                Notification.show(e.getMessage(), Type.ERROR_MESSAGE);
                logger.error(e, e);
            } finally {
            }
        }

        private void createHistory() {
            Collection<ReportParameter<?>> params = builder.getReportParameters();
            ReportSave reportSave = new ReportSave();
            reportSave.setReportClass(reportProperties.getReportClass().getName());
            reportSave.setUserDescription("");
            reportSave.setUser(reportProperties.getUsername());
            reportSave.setSaveType(SaveType.HISTORY);
            JpaBaseDao.getEntityManager().persist(reportSave);
            for (ReportParameter<?> param : params) {
                for (String pname : param.getParameterNames()) {
                    if (StringUtils.isNotBlank(param.getLabel(pname))) {
                        ReportSaveParameter reportSaveparam = new ReportSaveParameter();
                        reportSaveparam.setParameterName(param.getLabel(pname));
                        reportSaveparam.setTextualRepresentation(param.getDisplayValue(pname));
                        reportSaveparam.setParameterValue(param.getValue(pname).toString());
                        reportSaveparam.setMetaData(param.getSaveMetaData());
                        reportSaveparam.setMetaDataComment(param.getMetaDataComment());
                        reportSave.addParameter(reportSaveparam);
                        JpaBaseDao.getEntityManager().persist(reportSaveparam);
                    }
                }
            }
            // remove excess history
            JpaDslBuilder<ReportSave> q = new JpaBaseDao<>(ReportSave.class).select();
            List<ReportSave> history = q.where(q.eq(ReportSave_.user, reportProperties.getUsername()).and(q.eq(ReportSave_.saveType, SaveType.HISTORY))).orderBy(ReportSave_.lastUsed, true).getResultList();
            if (history.size() > 50) {
                ReportSave old = history.get(0);
                for (ReportSaveParameter param : old.getParameters()) {
                    EntityManagerProvider.remove(param);
                }
                EntityManagerProvider.remove(old);
            }
        }

        private void createFrequentlyUsed() {
            JpaDslBuilder<ReportSave> q = new JpaBaseDao<>(ReportSave.class).select();
            ReportSave reportSave = q.where(q.eq(ReportSave_.reportClass, reportProperties.getReportClass().getName()).and(q.eq(ReportSave_.user, reportProperties.getUsername()).and(q.eq(ReportSave_.saveType, SaveType.FREQUENTLY_USED)))).getSingleResultOrNull();
            if (reportSave == null) {
                reportSave = new ReportSave();
                reportSave.setReportClass(reportProperties.getReportClass().getName());
                reportSave.setUserDescription("Frequently used");
                reportSave.setUser(reportProperties.getUsername());
                reportSave.setSaveType(SaveType.FREQUENTLY_USED);
                JpaBaseDao.getEntityManager().persist(reportSave);
            }
            reportSave.incrementRunCounter();
        }
    });
}
Also used : JpaDslBuilder(au.com.vaadinutils.dao.JpaDslBuilder) ClickEventLogged(au.com.vaadinutils.listener.ClickEventLogged) ExpanderComponent(au.com.vaadinutils.jasper.filter.ExpanderComponent) ReportParameter(au.com.vaadinutils.jasper.parameter.ReportParameter) JpaBaseDao(au.com.vaadinutils.dao.JpaBaseDao) ClickEvent(com.vaadin.ui.Button.ClickEvent) ParseException(java.text.ParseException) ConversionException(com.vaadin.data.util.converter.Converter.ConversionException) ReadOnlyException(com.vaadin.data.Property.ReadOnlyException) Collection(java.util.Collection) List(java.util.List) LinkedList(java.util.LinkedList) ReportSave(au.com.vaadinutils.jasper.scheduler.entities.ReportSave) ReportSaveParameter(au.com.vaadinutils.jasper.scheduler.entities.ReportSaveParameter)

Example 4 with ReportParameter

use of au.com.vaadinutils.jasper.parameter.ReportParameter in project VaadinUtils by rlsutton1.

the class JasperReportLayout method getStreamConnectorRefreshListener.

private void getStreamConnectorRefreshListener(final JasperManager.OutputFormat outputFormat) {
    UI.getCurrent().setPollInterval(500);
    UI.getCurrent().addPollListener(new PollListener() {

        private static final long serialVersionUID = -5641305025399715756L;

        @Override
        public void poll(PollEvent event) {
            logger.warn("Checking if report is ready...");
            if (streamReady && !streamConnected) {
                // jasper manager is ready, so get the report stream and set
                // it as the source for the display panel
                streamConnected = true;
                StreamResource resource = new StreamResource(getReportStream(), "report");
                resource.setMIMEType(outputFormat.getMimeType());
                resource.setCacheTime(-1);
                resource.setFilename(exportFileName(outputFormat));
                if (outputFormat == OutputFormat.CSV) {
                    csv.setSource(resource);
                    showCsvSplash();
                } else {
                    getDisplayPanel().setSource(resource);
                }
                UI.getCurrent().removePollListener(this);
            }
        }

        private String exportFileName(final JasperManager.OutputFormat outputFormat) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String name = reportProperties.getReportTitle() + "At" + sdf.format(new Date());
            for (ReportParameter<?> param : builder.getReportParameters()) {
                if (param.showFilter()) {
                    name += "-" + param.getLabel("");
                    for (String parameterName : param.getParameterNames()) {
                        name += "-" + param.getDisplayValue(parameterName);
                    }
                }
            }
            if (name.length() > MAX_FILENAME_LENGTH) {
                name = name.substring(0, MAX_FILENAME_LENGTH);
            }
            name = name.replace("/", "-");
            return name + outputFormat.getFileExtension();
        }
    });
}
Also used : StreamResource(com.vaadin.server.StreamResource) ReportParameter(au.com.vaadinutils.jasper.parameter.ReportParameter) OutputFormat(au.com.vaadinutils.jasper.JasperManager.OutputFormat) JasperManager(au.com.vaadinutils.jasper.JasperManager) PollListener(com.vaadin.event.UIEvents.PollListener) SimpleDateFormat(java.text.SimpleDateFormat) PollEvent(com.vaadin.event.UIEvents.PollEvent) Date(java.util.Date)

Example 5 with ReportParameter

use of au.com.vaadinutils.jasper.parameter.ReportParameter in project VaadinUtils by rlsutton1.

the class JasperManager method run.

@Override
public void run() {
    JRSwapFileVirtualizer fileVirtualizer = null;
    CleanupCallback cleanupCallback = null;
    boolean initialized = false;
    try {
        logger.warn("{} permits are available", concurrentLimit.availablePermits());
        concurrentLimit.acquire();
        initialized = true;
        inQueue = false;
        queueEntry.setStatus("Gathering report data phase 1");
        reportProperties.initDBConnection();
        cleanupCallback = reportProperties.getCleanupCallback();
        List<ReportParameter<?>> extraParams = reportProperties.prepareData(params, reportProperties.getReportFileName(), cleanupCallback);
        compileReport();
        if (reportProperties.getCustomReportParameterMap() != null) {
            boundParams.putAll(reportProperties.getCustomReportParameterMap());
        }
        if (extraParams != null) {
            params.removeAll(extraParams);
            params.addAll(extraParams);
        }
        logger.info("Running report " + reportProperties.getReportFileName());
        for (ReportParameter<?> param : params) {
            for (String parameterName : param.getParameterNames()) {
                bindParameter(param, parameterName);
                if (param.displayInreport()) {
                    // populate dynamically added parameters to display user
                    // friendly parameters on the report
                    boundParams.put("ParamDisplay-" + parameterName, param.getDisplayValue(parameterName));
                }
                logger.info(parameterName + " " + param.getValue(parameterName));
            }
        }
        reportProperties.prepareForOutputFormat(exportMethod);
        queueEntry.setStatus("Gathering report data phase 2");
        // use file virtualizer to prevent out of heap
        String fileName = "/tmp";
        JRSwapFile file = new JRSwapFile(fileName, 100, 10);
        fileVirtualizer = new JRSwapFileVirtualizer(500, file);
        boundParams.put(JRParameter.REPORT_VIRTUALIZER, fileVirtualizer);
        if (stop) {
            return;
        }
        if (exportMethod == OutputFormat.CSV) {
            boundParams.put(JRParameter.IS_IGNORE_PAGINATION, true);
        }
        JasperPrint jasper_print = fillReport(exportMethod);
        queueEntry.setStatus("Waiting for browser to start streaming");
        if (stop) {
            return;
        }
        logger.warn("Output stream is ready");
        progressListener.outputStreamReady();
        logger.warn("Waiting for reader stream");
        if (readerReady.await(10, TimeUnit.SECONDS)) {
            outputStream = new PipedOutputStream(inputStream);
            writerReady.countDown();
            exportMethod.export(jasper_print, outputStream, getPageMonitorConfig(exportMethod.getConfig()), images);
            imagesrcs = (images.size() <= 0) ? null : new DataSource[images.size()];
            if (imagesrcs != null) {
                int xi = 0;
                for (Map.Entry<String, byte[]> entry : images.entrySet()) {
                    ByteArrayDataSource image = new ByteArrayDataSource(entry.getValue(), "image/gif");
                    image.setName(entry.getKey());
                    imagesrcs[xi++] = image;
                }
            }
        } else {
            logger.error("Couldn't attach to reader stream");
        }
        Thread.sleep(750);
        queueEntry.setStatus("Cleaning up");
    } catch (Exception e) {
        logger.error(e, e);
    } finally {
        if (queueEntry != null) {
            jobQueue.remove(queueEntry);
            queueEntry = null;
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            logger.error(e, e);
        }
        if (cleanupCallback != null) {
            try {
                cleanupCallback.cleanup();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        if (fileVirtualizer != null) {
            try {
                fileVirtualizer.cleanup();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        if (initialized) {
            concurrentLimit.release();
            try {
                reportProperties.closeDBConnection();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        completeBarrier.countDown();
        if (progressListener != null) {
            progressListener.completed();
        }
    }
}
Also used : ReportParameter(au.com.vaadinutils.jasper.parameter.ReportParameter) JRSwapFileVirtualizer(net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer) JasperPrint(net.sf.jasperreports.engine.JasperPrint) JRSwapFile(net.sf.jasperreports.engine.util.JRSwapFile) PipedOutputStream(java.io.PipedOutputStream) IOException(java.io.IOException) JasperPrint(net.sf.jasperreports.engine.JasperPrint) FileNotFoundException(java.io.FileNotFoundException) JRException(net.sf.jasperreports.engine.JRException) IOException(java.io.IOException) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) CleanupCallback(au.com.vaadinutils.jasper.ui.CleanupCallback) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Aggregations

ReportParameter (au.com.vaadinutils.jasper.parameter.ReportParameter)5 JasperManager (au.com.vaadinutils.jasper.JasperManager)2 OutputFormat (au.com.vaadinutils.jasper.JasperManager.OutputFormat)2 ReportSave (au.com.vaadinutils.jasper.scheduler.entities.ReportSave)2 ReportSaveParameter (au.com.vaadinutils.jasper.scheduler.entities.ReportSaveParameter)2 StreamResource (com.vaadin.server.StreamResource)2 ClickEvent (com.vaadin.ui.Button.ClickEvent)2 JpaBaseDao (au.com.vaadinutils.dao.JpaBaseDao)1 JpaDslBuilder (au.com.vaadinutils.dao.JpaDslBuilder)1 InputDialog (au.com.vaadinutils.editors.InputDialog)1 Recipient (au.com.vaadinutils.editors.Recipient)1 AttachmentType (au.com.vaadinutils.jasper.AttachmentType)1 JasperEmailBuilder (au.com.vaadinutils.jasper.JasperEmailBuilder)1 RenderedReport (au.com.vaadinutils.jasper.RenderedReport)1 ExpanderComponent (au.com.vaadinutils.jasper.filter.ExpanderComponent)1 ReportEmailRecipient (au.com.vaadinutils.jasper.scheduler.entities.ReportEmailRecipient)1 CleanupCallback (au.com.vaadinutils.jasper.ui.CleanupCallback)1 JasperReportPropertiesAlternateFile (au.com.vaadinutils.jasper.ui.JasperReportPropertiesAlternateFile)1 ClickEventLogged (au.com.vaadinutils.listener.ClickEventLogged)1 ReadOnlyException (com.vaadin.data.Property.ReadOnlyException)1