Not able to plot Date values in json graph using Struts 2 jquery chart plugin 3.4.0 - struts2

I am using Struts2 jquery chart plugin 3.4.0. I am getting blank chart when i use json for getting date values from the Action class.If i use simple action then same code works fine.
Here is my jsp code.
<s:url id="chartDataUrl" action="jsonChartData"/>
<sjc:chart
id="chartDate"
xaxisMode="time"
xaxisTimeformat="%m.%Y"
xaxisMin="%{minTime}"
xaxisMax="%{maxTime}"
xaxisColor="#666"
xaxisTickSize="[3, 'month']"
xaxisTickColor="#aaa"
xaxisPosition="top"
yaxisPosition="right"
yaxisTickSize="10"
cssStyle="width: 600px; height: 400px;"
>
<sjc:chartData
id="chartAjaxData1"
label="Map -Double, Double-"
href="%{chartDataUrl}" // when i remove json call then it works fine
list="dateFromMap"
reloadTopics="reloadMap"
lines="{show : true}"
/>
</sjc:chart>
struts.xml code
<action name="jsonChartData"
class="com.ebhasin.fitnessbliss.actions.GraphsAction">
<result type="json" name="success"></result>
</action>
Action class code:
public class GraphsAction extends ActionSupport {
private String currentDate;
private Map<Date, Float> dateFromMap;
HomeService homeService = new HomeService();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
#Override
public String execute() {
System.out.println("execute");
float weight;
Date date = new Date();
Map session = ActionContext.getContext().getSession();
Integer loginId = (Integer) session.get("loginId");
if (loginId != null) {
dateFromMap = new TreeMap<Date, Float>();
List list = homeService.getWeightGraphData(loginId);
if (list.size() > 0) {
Iterator itr = list.iterator();
while (itr.hasNext()) {
UserStats userStats = (UserStats) itr.next();
weight = userStats.getWeight();
date = userStats.getCreatedDate();
//currentDate = formatter.format(date);
dateFromMap.put(date, weight);
}
} else {
// dateFromMap.put("my",2F );
}
} else {
}
return SUCCESS;
}
public String getCurrentDate() {
return currentDate;
}
public void setCurrentDate(String currentDate) {
this.currentDate = currentDate;
}
public Map<Date, Float> getDateFromMap() {
return dateFromMap;
}
public void setDateFromMap(Map<Date, Float> dateFromMap) {
this.dateFromMap = dateFromMap;
}
}

EDIT:
Please put a System.out.println("something"); on every if / else block to see exactly where are you passing;
As a note, the preferred way to get the session object is to implement SessionAware, instead of using ActionContext;
Does your JSON Action looks like this ? :
http://struts.jgeppert.com/struts2-jquery-showcase/index.action
(go to More Widgets -> Charts -> JSON Action, in the bottom right tab.
#ParentPackage(value = "showcase")
public class JsonChartData extends ActionSupport {
private static final long serialVersionUID = 6659512910595305843L;
private List<ListValue> objList;
private Map<Double, Double> doubleMap;
#Actions( {
#Action(value = "/json-chart-data", results = {
#Result(name = "success", type = "json")
})
})
public String execute()
{
objList = new ArrayList<ListValue>();
doubleMap = new TreeMap<Double, Double>();
Random generator = new Random();
for (int i = 1; i <= 24; i++)
{
doubleMap.put(Double.valueOf("" + i), generator.nextDouble() * 10.0);
}
for (int i = 1; i <= 24; i++)
{
objList.add(new ListValue("" + i, "" + generator.nextInt(30)));
}
return SUCCESS;
}
public String getJSON()
{
return execute();
}
public List<ListValue> getObjList()
{
return objList;
}
public void setObjList(List<ListValue> objList)
{
this.objList = objList;
}
public Map<Double, Double> getDoubleMap()
{
return doubleMap;
}
public void setDoubleMap(Map<Double, Double> doubleMap)
{
this.doubleMap = doubleMap;
}
}

Related

How do I programmatically add records to an Umbraco v8 form?

I'm looking to add records to an Umbraco v8 form. I know I need the form guid. Is this how I'd do it? Something like this?
public void PostFormData()
{
Guid FormGuid = new Guid("8494a8f0-94da-490e-bd61-7e658c226142");
var form = _formService.Get(FormGuid);
//place for field data into fieldDic
var fieldDic = new Dictionary<Guid, RecordField>();
var firstName = form.AllFields.First(f => f.Alias == "firstName");
var firstNameRecord = new RecordField(firstName);
firstNameRecord.Values = new List<object>() { "Mad Max" };
fieldDic.Add(firstName.Id, firstNameRecord);
var record = new Record()
{
Created = DateTime.Now,
Form = form.Id,
RecordFields = fieldDic,
State = FormState.Submitted,
};
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
}
Here's how I do it. Note, I'm hard-coding the Record.UmbracoPageId to -1 while you might want to actually pass in the correct page ID.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Forms.Core.Data.Storage;
using Umbraco.Forms.Core.Models;
using Umbraco.Forms.Core.Persistence.Dtos;
using Umbraco.Forms.Core.Services;
namespace myProject.Services
{
public class FormServiceComposer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register<IFormService, FormService>(Lifetime.Request);
}
}
public interface IFormService
{
void InsertFormData(Guid formGuid, object formModel, string ipAddress);
}
public class FormService : IFormService
{
private readonly ILogger _logger;
private readonly Umbraco.Forms.Core.Services.IFormService _formService;
private readonly IRecordStorage _recordStorage;
private readonly IRecordFieldStorage _recordFieldStorage;
private readonly IWorkflowService _workflowService;
public FormService(ILogger logger, Umbraco.Forms.Core.Services.IFormService formService, IRecordStorage recordStorage, IRecordFieldStorage recordFieldStorage, IWorkflowService workflowService)
{
_logger = logger;
_formService = formService;
_recordStorage = recordStorage;
_recordFieldStorage = recordFieldStorage;
_workflowService = workflowService;
}
#region IFormService
public void InsertFormData(Guid formGuid, object formModel, string ipAddress)
{
try
{
Form form = _formService.GetForm(formGuid);
Record record = new Record();
foreach (Field field in form.AllFields)
{
string caption = CleanCaption(field.Caption);
if (formModel.GetType().GetProperty(caption) == null) continue;
var propertyValue = formModel.GetType().GetProperty(caption).GetValue(formModel, null);
if (propertyValue != null)
{
List<object> values = ExtractValues(propertyValue);
RecordField recordField = new RecordField
{
Alias = field.Alias,
FieldId = field.Id,
Field = field,
Key = Guid.NewGuid(),
Record = record.Id,
Values = values
};
_recordFieldStorage.InsertRecordField(recordField);
record.RecordFields.Add(recordField.Key, recordField);
}
}
record.Form = formGuid;
record.IP = ipAddress;
record.UmbracoPageId = -1;
record.State = Umbraco.Forms.Core.Enums.FormState.Approved;
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
_recordStorage.DisposeIfDisposable();
}
catch (Exception ex)
{
_logger.Error<FormService>(ex, "Failed inserting Umbraco Forms data for {formGuid}");
}
}
#endregion IFormService
#region Private
private string CleanCaption(string caption)
{
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
return rgx.Replace(caption.Trim().Replace(" ", ""), "");
}
private List<object> ExtractValues(object propertyValue)
{
List<object> result = new List<object>();
if (propertyValue is string == false && propertyValue.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
IEnumerable<object> _propertyValue = (IEnumerable<object>)propertyValue;
if (_propertyValue.Any())
{
if (_propertyValue.First().GetType().GetProperties().Count() > 1)
{
JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));
foreach (JToken item in _properties)
{
string _value = string.Empty;
foreach (var _property in _propertyValue.First().GetType().GetProperties())
{
string _key = _property.Name;
_value = _value + (_value == "" ? "" : " - ") + item[_key].ToString();
}
result.Add(_value);
}
}
else
{
string _key = _propertyValue.First().GetType().GetProperties().First().Name;
JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));
foreach (JToken item in _properties)
{
result.Add(item[_key].ToString());
}
}
}
}
else
{
result.Add(propertyValue);
}
return result;
}
#endregion Private
}
}

Listview Filter with SearchView Using Base Adapter in Xamarin android Error

I am try to filter listview with searchview using Base Adapter in in xamarin Android, My listView Bind in sql server using restfull web service i am stuck in PublishResults which is given an error
Here Is My Code:-
GetHospNames.cs
public class GetHospNames
{
public string HospID { get; set; }
public string HospName { get; set; }
public GetHospNames(string HospID, string HospName)
{
this.HospID = HospID;
this.HospName = HospName;
//this.HospLogo = HospLogo;
}
}
ContListViewHospNameClass.cs
using System.Collections.Generic;
using Android.App;
using Android.Views;
using Android.Widget;
using System;
using Android.Graphics;
using Android.Graphics.Drawables;
using System.IO;
using Android.Content;
using Java.Lang;
using Android.Text;
using Java.Util;
using Oject = Java.Lang.Object;
namespace HSAPP
{
public class ContListViewHospNameClass : BaseAdapter<GetHospNames>, IFilterable
{
public List<GetHospNames> objList;
Activity objActivity;
List<GetHospNames> filterList;
public ContListViewHospNameClass(Activity objMyAct, List<GetHospNames> objMyList) : base()
{
this.objActivity = objMyAct;
objList = objMyList;
this.filterList = objList;
Filter = new CustomFilter(this);
}
public override GetHospNames this[int position]
{
get
{
return objList[position];
}
}
public override int Count
{
get
{
return objList.Count;
}
}
public Filter Filter { get; set; }
public override void NotifyDataSetChanged()
{
base.NotifyDataSetChanged();
}
//This is Inner Class
public class CustomFilter : Filter
{
ContListViewHospNameClass CustomAdapter;
public CustomFilter(ContListViewHospNameClass adapter) : base()
{
this.CustomAdapter = adapter;
}
protected override FilterResults PerformFiltering(ICharSequence constraint)
{
FilterResults result = new FilterResults();
if (constraint != null && constraint.Length() > 0)
{
//Contraint To Upper
List<GetHospNames> filter = new List<GetHospNames>();
foreach (GetHospNames name in CustomAdapter.objList)
{
if (name.HospName.ToUpper().Contains(constraint.ToString().ToUpper()))
{
filter.Add(name);
}
}
Oject[] Name;
Name = new Oject[filter.Count];
for (int i = 0; i < filter.Count; i++)
{
Name[i] = filter[i].HospName.ToString();
}
result.Count = filter.Count;
result.Values = Name;
}
return result;
}
protected override void PublishResults(ICharSequence constraint, Filter.FilterResults result)
{
List<GetHospNames> filteredList = new List<GetHospNames>();
for (int i = 0; i < ((Oject[])result.Values).Length; i++)
{
filteredList.Add((Oject[])result.Values[i]);//Here Is An Error *****Cannot apply indexing with [] to an expression of type 'Object'****
}
CustomAdapter.objList = filteredList;
CustomAdapter.NotifyDataSetChanged();
}
}
public override long GetItemId(int position)
{
return position;
}
public Bitmap getBitmap(byte[] getByte)
{
if (getByte.Length != 0)
{
return BitmapFactory.DecodeByteArray(getByte, 0, getByte.Length);
}
else
{
return null;
}
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = objList[position];
if (convertView == null)
{
convertView = objActivity.LayoutInflater.Inflate(Resource.Layout.ContListViewHospName, null);
}
convertView.FindViewById<TextView>(Resource.Id.tvHospID).Text = item.HospID;
convertView.FindViewById<TextView>(Resource.Id.tvHospName).Text = item.HospName;
return convertView;
}
}
public static class ObjectTypeHelper
{
public static T Cast<T>(this Java.Lang.Object obj) where T : class
{
var propertyInfo = obj.GetType().GetProperty("Instance");
return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}
}
}
This is my MainActivity Code
private void BindControl_BindHospCompleted(object sender, BindControl.BindHospCompletedEventArgs e)
{
jsonValue = e.Result.ToString();
try
{
if (jsonValue == null)
{
Toast.MakeText(this, "No Data For Bind", ToastLength.Long).Show();
return;
}
JArrayValue = JArray.Parse(jsonValue);
list = new List<GetHospNames>();
int count = 0;
while (count < JArrayValue.Count)
{
GetHospNames getHospName = new GetHospNames(JArrayValue[count]["HospID"].ToString(), JArrayValue[count]["HospName"].ToString());
list.Add(getHospName);
count++;
}
if (count == 0)
{
Toast.MakeText(this, "No List Of Hospitals", ToastLength.Long).Show();
}
adapter = new ContListViewHospNameClass(this, list);
listView.Adapter = adapter;
search.QueryTextChange += (s, e) =>
{
adapter.Filter.InvokeFilter(e.NewText);
};
listView.ItemClick += ListView_ItemClick;
pBar.Dismiss();
}
catch (Java.Lang.Exception ex)
{
pBar.Dismiss();
//Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
Finish();
Intent intent = new Intent(this, typeof(ChkIntConnActivity));
StartActivity(intent);
}
}
Please Help...Thank You

C# find cost, calculate the cost of item and include 10% GST

I am studying C# and have been asked to create a grocery program. I am stuck and can't seem to find anything on the net to help me. I have created a grocery item class with properties containing Name and Price. I have also created a subclass of purchasedItem which has an integer of quantity. I now need to create a method which finds Price, calculates the Price and adds 10% GST. Any ideas of how to do this.
This is what I have so far - any help would be appreciated:
namespace Groceries1
{
class Program
{
static void Main(string[] args)
{
groceryItem mygroceryItem = new groceryItem();
mygroceryItem.play();
purchasedItem mypurchasedItem = new purchasedItem();
}
class groceryItem
{
private string myName = 0;
private int myPrice = 0;
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public int Price
{
get
{
return myPrice;
}
set
{
myPrice = value;
}
}
}
class purchasedItem
{
private int myquantity = 0;
public int quantity
{
get
{
return myquantity;
}
set
{
myquantity = Price*quantity*1.1;
}
}
}
}
}
You can try this,
using System;
using System.Collections.Generic;
namespace Groceries
{
public class Program
{
public static void Main(string[] args)
{
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = "Fresh grocery";
freshGrocery.Price = 30;
freshGrocery.Weight = 0.5;
Grocery grocery = new Grocery();
grocery.Name = "Grocery";
grocery.Price = 50;
grocery.Quantity = 2;
ShoppingCart cart = new ShoppingCart();
cart.Orders = new List<GroceryItem>();
cart.Orders.Add(freshGrocery);
cart.Orders.Add(grocery);
double price = cart.Calculate();
Console.WriteLine("Price: {0}", price);
}
}
abstract class GroceryItem
{
private string name;
private double price = 0;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public abstract double Calculate();
}
class FreshGrocery: GroceryItem
{
private double weight = 0;
public double Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}
public override double Calculate() {
return this.Price * this.Weight;
}
}
class Grocery: GroceryItem
{
private int quantity = 0;
private double gst = 10; // In Percentage
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
public override double Calculate() {
double calculatedPrice = this.Price * this.Quantity;
// VAT
if(calculatedPrice > 0)
{
calculatedPrice += calculatedPrice * (gst/100);
}
return calculatedPrice;
}
}
class ShoppingCart
{
private List<GroceryItem> orders;
public List<GroceryItem> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
public double Calculate()
{
double price = 0;
if(this.Orders != null)
{
foreach(GroceryItem order in this.Orders)
{
price += order.Calculate();
}
}
return price;
}
}
}

How to select combobox by id or value using with BeanItemContainer?

I am using BeanItemContainer for my comboboxes to satisfy key-value pairs.
#SuppressWarnings("serial")
public class ComboBoxItem implements Serializable {
private String id;
private String description;
public ComboBoxItem(final String id, final String description) {
this.id = id;
this.description = description;
}
public final void setId(final String id) {
this.id = id;
}
public final void setDescription(final String description) {
this.description = description;
}
public final String getId() {
return id;
}
public final String getDescription() {
return description;
}
}
I created a sample combobox as below
List<ComboBoxItem> lstAuctionDateList = new ArrayList<ComboBoxItem>();
lstAuctionDateList.add(new ComboBoxItem("all", "All"));
BeanItemContainer<ComboBoxItem> auctionDateItems = new BeanItemContainer<ComboBoxItem>(ComboBoxItem.class,
lstAuctionDateList);
final ComboBox cbAuctionDate = new ComboBox("Auction Date", auctionDateItems);
cbAuctionDate.addStyleName("small");
cbAuctionDate.setNullSelectionAllowed(false);
cbAuctionDate.setTextInputAllowed(false);
cbAuctionDate.setItemCaptionPropertyId("description");
cbAuctionDate.addValueChangeListener(new ValueChangeListener() {
public void valueChange(final ValueChangeEvent event) {
if (cbAuctionDate.getValue() != null) {
System.out.println(((ComboBoxItem) cbAuctionDate.getValue()).getId());
System.out.println(((ComboBoxItem) cbAuctionDate.getValue()).getDescription());
}
}
});
It is fine but I can't select any of combobox items by using below codes
cbAuctionDate.select("all");
cbAuctionDate.select("All");
cbAuctionDate.setValue("all");
cbAuctionDate.setValue("All");
What am I wrong ? How can I select my comboxes by programmatically ?
when using a (bean) container and adding items, the identity of the item itself is used as the itemId in the container. E.g. cbActionDate.select(lstAuctionDateList[0]) should work.
You either have yo make your objects immutable or use ways to tell the container, what it has to use for an id (E.g. setBeanIdProperty("id") or setBeanIdResolver).
Making the object immutable should be easy right now (make the class and the private attributes final, drop the setters and let your IDE generate equals and hashCode for you)
You don't need the cbAuctionDate.addItem("All") call, you already have such a item in your collection
I would try it that way:
List<ComboBoxItem> lstAuctionDateList = new ArrayList<ComboBoxItem>();
ComboBoxItem allItems= new ComboBoxItem("all", "All");
lstAuctionDateList.add(allItems);
....
...
cbAuctionDate.select(allItems);
Now I created custom ComboBox component for my problem
public class ComboBox extends CustomComponent implements Serializable {
private com.vaadin.ui.ComboBox comboBox;
private BeanItemContainer<ComboBoxItem> entries = new BeanItemContainer<ComboBoxItem>(ComboBoxItem.class);
public ComboBox() {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCompositionRoot(comboBox);
}
public ComboBox(final String caption) {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCaption(caption);
setCompositionRoot(comboBox);
}
public ComboBox(final String caption, final List<ComboBoxItem> items) {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCaption(caption);
if (items != null && items.size() > 0) {
entries.addAll(items);
comboBox.setContainerDataSource(entries);
comboBox.setItemCaptionMode(ItemCaptionMode.PROPERTY);
addItems(entries);
comboBox.select(items.get(0));
comboBox.setItemCaptionPropertyId("description");
}
setCompositionRoot(comboBox);
}
public final void addItems(final List<ComboBoxItem> items) {
if (items != null && items.size() > 0) {
entries.addAll(items);
comboBox.setContainerDataSource(entries);
comboBox.setItemCaptionMode(ItemCaptionMode.PROPERTY);
addItems(entries);
comboBox.select(items.get(0));
comboBox.setItemCaptionPropertyId("description");
}
}
private void addItems(final BeanItemContainer<ComboBoxItem> items) {
comboBox.addItems(items);
}
public final void addItem(final ComboBoxItem item) {
if (item != null) {
comboBox.setContainerDataSource(entries);
comboBox.addItem(item);
comboBox.setItemCaptionPropertyId("description");
}
}
public final void selectByIndex(final int index) {
Object[] ids = comboBox.getItemIds().toArray();
comboBox.select(((ComboBoxItem) ids[index]));
}
public final void selectById(final String id) {
Object[] ids = comboBox.getItemIds().toArray();
for (int i = 0; i < ids.length; i++) {
if (((ComboBoxItem) ids[i]).getId().equals(id)) {
selectByIndex(i);
break;
}
}
}
public final void selectByItemText(final String description) {
Object[] ids = comboBox.getItemIds().toArray();
for (int i = 0; i < ids.length; i++) {
if (((ComboBoxItem) ids[i]).getDescription().equals(description)) {
selectByIndex(i);
break;
}
}
}
public final int getItemCount() {
return comboBox.getItemIds().toArray().length;
}
public final String getSelectedId() {
return ((ComboBoxItem) comboBox.getValue()).getId();
}
public final String getSelectedItemText() {
return ((ComboBoxItem) comboBox.getValue()).getDescription();
}
public final void addValueChangeListener(final ValueChangeListener listener) {
comboBox.addValueChangeListener(listener);
}
}
and below is test codes
final ComboBox combo = new ComboBox("My ComboBox");
combo.addItem(new ComboBoxItem("all", "All"));
// Add with list
List<ComboBoxItem> items = new ArrayList<ComboBoxItem>();
items.add(new ComboBoxItem("one", "One"));
items.add(new ComboBoxItem("two", "Two"));
items.add(new ComboBoxItem("three", "Three"));
combo.addItems(items);
combo.addItem(new ComboBoxItem("four", "Four"));
combo.addItem(new ComboBoxItem("five", "five"));
combo.selectByIndex(3);
combo.addValueChangeListener(new ValueChangeListener() {
public void valueChange(final ValueChangeEvent event) {
System.out.println(combo.getSelectedId() + " --- " + combo.getSelectedItemText());
}
});

PrimeFaces Export data from a Lazyloading DataTable

I want to export a dataTable (with Pagination) having LazyLoad DataModel during Report Generation.
Problem :
When I export, the report is getting generated page by page from Database and then getting exported to Excel/PDF that consumes more time. I would like to get it in a single database access by skipping the page by page generation of dataset.
I'm producing my code snippet as follows:
JSF:
<p:dataTable id="dTable" var="dev" value="#{ReportAction.lazyModel}"
styleClass ="table_paginator" rowKey="#{device.macAddress}" paginatorPosition="bottom"
paginator="true" rowsPerPageTemplate="10,20,30" rows="10" lazy="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
emptyMessage="Select appropriate conditions and click 'Generate Report'">
<f:facet name="header">
<h:commandLink actionListener="#{ReportAction.doExport}">
<p:graphicImage value="../../../resources/images/excel.png"
alt="XLS" style="float:right;width:32px;height:32px" />
<p:dataExporter type="xls" target="dTable" fileName="#{ReportAction.fileName}"
preProcessor="#{ReportAction.preProcess}"
postProcessor="#{ReportAction.postProcessXLS}" />
</h:commandLink>
</f:facet>
<!-- All the columns in Data Table -->
</p:dataTable>
Managed Bean:
public class ReportAction {
private ConfigurationReportDataModel mediumConfigModel;
private List<FieldReportModel> configModelList;
private String fileName;
private LazyDataModel<ConfigurationReportModel> lazyModel;
private boolean export;
public ReportAction() {
configModelList = new ArrayList<ConfigurationReportModel>();
export = false;
mediumConfigModel = new ReportDataModel();
}
public void generateFieldReport() {
lazyFieldModel = new ConfigurationReportDataModel(day, fromDate,
location,store,engineer, status, toDate, export);
}
public void preProcess(Object document) {
export = true;
log.info("preProcess::Lazy model : Page Sizing");
if(lazyFieldModel != null) {
lazyFieldModel.setPageSize(1000000);
}
log.info("preProcess::Export All Details");
mediumConfigModel.setExport(true);
}
public void postProcessXLS(Object document) {
HSSFWorkbook wb = (HSSFWorkbook) document;
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow header = sheet.getRow(0);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GREEN.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
HSSFCell cell = header.getCell(i);
cell.setCellValue(cell.getStringCellValue().toUpperCase());
cell.setCellStyle(cellStyle);
sheet.autoSizeColumn(i);
}
export = false;
mediumConfigModel.setExport(false);
}
public List<ConfigurationReportModel> getConfigModelList() {
return configModelList;
}
public void setConfigModelList(
ArrayList<ConfigurationReportModel> configModelList) {
this.configModelList = configModelList;
}
public String getFileName() {
SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy_HHmmss");
fileName = "Config_Report_".concat(formatter.format(new Date()));
return fileName;
}
public void setMediumConfigModel(
ConfigurationReportDataModel mediumConfigModel) {
this.mediumConfigModel = mediumConfigModel;
}
public void setConfigModelList(
List<ConfigurationReportModel> configModelList) {
this.configModelList = configModelList;
}
public LazyDataModel<ConfigurationReportModel> getLazyFieldModel() {
log.info("##########getLazyFieldModel###########");
if(export) {
log.info("getLazyFieldModel::Will get Exported........");
lazyFieldModel = new ConfigurationReportDataModel(day, fromDate,
location, store, engineer, status, toDate, true);
lazyFieldModel.load(1, 1000000000, null, null, null);
}
return lazyFieldModel;
}
public void setLazyFieldModel(
LazyDataModel<ConfigurationReportModel> lazyFieldModel) {
this.lazyFieldModel = lazyFieldModel;
}
}
DataModel:
public class ConfigurationReportDataModel extends
LazyDataModel<ConfigurationReportModel> {
private List<ConfigurationReportModel> configReport;
private boolean export;
public ConfigurationReportDataModel() {
this.export = false;
}
public List<ConfigurationReportModel> load(int first, int pageSize,
String sortField, SortOrder sortOrder, Map<String, String> filters) {
UIClient client = new UIClient();
ReportData data = null;
// ///////////////////
if(export) {
log.info("Do Export....");
first = 1;
pageSize = 1000000000;
}
deviceList = new ArrayList<DeviceGlobal>();
// Retrieves data from Database with the number of record (page size)
data = client.generateFieldReport(first, pageSize,
Integer.parseInt(location), Integer.parseInt(store),
engineer, getTimeToBeginningOfDay(), getTimeToEndofDay(),
status);
log.info("Obtained data : " + data);
if (data != null) {
log.info("Got devices : " + data.getRecords().size());
deviceList = (ArrayList<DeviceGlobal>) data.getRecords();
// ///////////////////
int record = first + 1;
ConfigurationReportModel storeModel = null;
DeviceGlobal deviceGlobal = null;
configReport = new ArrayList<ConfigurationReportModel>();
for (Iterator<DeviceGlobal> iterator = deviceList.iterator(); iterator
.hasNext();) {
deviceGlobal = (DeviceGlobal) iterator.next();
storeModel = new ConfigurationReportModel(deviceGlobal,
record++);
configReport.add(storeModel);
}
log.info("Total Config Report : " + configReport.size());
// rowCount
int dataSize = data.getReportCount();
this.setRowCount(dataSize);
log.info("Report Count: " + data.getReportCount());
if(export) {
return configReport;
}
else {
// paginate
if (dataSize > pageSize) {
try {
return configReport;
} catch (IndexOutOfBoundsException e) {
return configReport;
}
} else {
return configReport;
}
}
} else {
log.info("Got no devices");
deviceList = new ArrayList<DeviceGlobal>();
configReport = new ArrayList<ConfigurationReportModel>();
this.setRowCount(0);
return configReport;
}
}
}
Note:
There's no syntax error.
All the custom type classes are defined.
How do I get the Excel report by skipping the page by page generation of records?
You have to add pageOnly="false" to dataExporter
for zero devision issue just override an extra LaztDataModel method as given below.
#Override
public void setRowIndex(int rowIndex) {
// TODO Auto-generated method stub
if (rowIndex == -1 || getPageSize() == 0) {
super.setRowIndex(-1);
}
else
super.setRowIndex(rowIndex % getPageSize());
}

Resources