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;
}
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);
}
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();
}
});
}
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();
}
});
}
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();
}
}
}
Aggregations