Dynamic datatable for columns and rows jsf (JSF2) - jsf

I actually followed below link added columns and row data as dynamic, little confused on how to show on xhtml. any help
http://balusc.blogspot.com/2006/06/using-datatables.html#PopulateDynamicDatatable
List<String> strlist = new ArrayList<String>();
List<List<String>> dynamicListynamicList = new ArrayList<List<String>>();
strlist.add("Name");
strlist.add("SSN");
for(String columnName : columnNamesList){
strlist.add(columnName);
}
List<String> rowData = new ArrayList<String>();
for(String otherList : listData){
try {
rowData.add(otherList.getName());
rowData.add(otherList.getId());
if(otherList.getAmount() != null){
for(BigDecimal amount : otherList.getAmount()){
if(amount != null){
rowData.add(amount.toString());
}else{
rowData.add("");
}
}
}else{
for(String s : strlist){
rowData.add("");
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
dynamicListynamicList.add(Arrays.asList(rowData.toArray(new String[rowData.size()] )));
}
String[] strarray = new String[strlist.size()];
dynamicHeaders = strlist.toArray(strarray );
populateDynamicDataTable(dynamicListynamicList);
private void populateDynamicDataTable(List<List<String>> dynamicList2){
HtmlDataTable dynamicDataTable = new HtmlDataTable();
for (int i = 0; i < dynamicList2.get(0).size(); i++) {
HtmlColumn column = new HtmlColumn();
dynamicDataTable.getChildren().add(column);
HtmlOutputText header = new HtmlOutputText();
header.setValue(createValueExpression("#{dynamicItemColumn[" + dynamicHeaders[i] + "]}", String.class));
column.setHeader(header);
HtmlOutputText output = new HtmlOutputText();
output.setValueExpression("value",
createValueExpression("#{dynamicItem[" + i + "]}", String.class));
column.getChildren().add(output);
}
dynamicDataTableGroup = new HtmlPanelGroup();
dynamicDataTableGroup.getChildren().add(dynamicDataTable);
setDynamicList(dynamicList2);
every thing works fine as data being added, now i wasnt sure and my apologies, how to iterate in jsf page(xhtml), to show relvant columna nd rowdata..

Related

Recover dynamic form data in Java PrimeFaces Extension

my job consists in recovering from a web service a form already filled; modify it with the transmit, the problem that the loop that I made gets the model before the modification I want to know how to recover the form after the modification
List<ModeleForm> modeles = new ArrayList<ModeleForm>();
for (DynaFormControl dynaFormControl : model.getControls()) {
System.out.println("recup");
modeles.add((ModeleForm) dynaFormControl.getData());
}
I tried this loop but it retrieves only the initial values.
model = new DynaFormModel();
try {
String url = "http://localhost:8080/activiti-rest/service/form/form-data?taskId=" + idTask + "";
Representation respons = getClientResource(url).get(MediaType.APPLICATION_JSON);
JSONObject object = new JSONObject(respons.getText());
if (object != null) {
JSONArray formProperties = object.getJSONArray("formProperties");
DynaFormLabel labels[] = new DynaFormLabel[0];
DynaFormControl labels2[] = new DynaFormControl[0];
labels = new DynaFormLabel[formProperties.length()];
labels2 = new DynaFormControl[formProperties.length()];
for (int i = 0; i < (formProperties.length()); i++) {
DynaFormRow row = model.createRegularRow();
boolean required = Boolean.valueOf(formProperties.getJSONObject(i).getString("required"));
labels[i] = row.addLabel(formProperties.getJSONObject(i).getString("name"));
labels2[i] = row.addControl(new ModeleForm(formProperties.getJSONObject(i).getString("name"), formProperties.getJSONObject(i).getString("id"), formProperties.getJSONObject(i).getString("value"), required), getType(formProperties.getJSONObject(i).getString("type")));
labels[i].setForControl(labels2[i]);
}
labels = null;
labels2 = null;
}
object = null;
} catch (MalformedURLException ex) {
Logger.getLogger(DemandeGeneraleController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DemandeGeneraleController.class.getName()).log(Level.SEVERE, null, ex);
} catch (JSONException ex) {
Logger.getLogger(DemandeGeneraleController.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("apres la fct create");
return model;
}
this code create the modele
<h:panelGroup id="dynaFormGroup">
<pe:dynaForm id="dynaForm" value="#{tachesController.createForm()}" var="data"
autoSubmit="true" widgetVar="dynaForm" >
<ui:include src="colsAddM2.xhtml"/>
</pe:dynaForm>
</h:panelGroup>
my page .xhtml which displays the dynamic form

LineChart Primefaces fetch data from DB

I want to make an income report line chart in last 30 days, i only need the date on series1 (horizontal chart) and the total income on series2 (vertical chart).
the object is DayBill that contain String date, and BigDecimal totalAmount. i want to make like date = 2017-09-19 got totalamount = 112527.5 , and so on.
public class ChartViewBean implements Serializable {
private LineChartModel lineModel1;
private List<DayBill> bills;
private TotalSalesDAO dao;
#PostConstruct
public void init() {
createLineModels();
}
public void itemSelect(ItemSelectEvent event) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Item selected",
"Item Index: " + event.getItemIndex() + ", Series Index:" + event.getSeriesIndex());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public LineChartModel getLineModel1() {
return lineModel1;
}
private void createLineModels() {
lineModel1 = initLinearModel();
lineModel1.setTitle("Linear Chart");
lineModel1.setLegendPosition("e");
Axis yAxis = lineModel1.getAxis(AxisType.Y);
yAxis.setMin(0);
yAxis.setMax(10);
lineModel1.setExtender("skinChart");
}
private LineChartModel initLinearModel() {
LineChartModel model = new LineChartModel();
LineChartSeries series1 = new LineChartSeries();
series1.setLabel("Series 1");
series1.set(1, 2);
series1.set(2, 1);
series1.set(3, 3);
series1.set(4, 6);
series1.set(5, 8);
LineChartSeries series2 = new LineChartSeries();
series2.setLabel("Series 2");
series2.set(1, 6);
series2.set(2, 3);
series2.set(3, 2);
series2.set(4, 7);
series2.set(5, 9);
model.addSeries(series1);
model.addSeries(series2);
return model;
}
this is my DAO, i already get the data that i want. The problem is i dont know how to put the data to the chart.
public List<DayBill> getDayBills() throws Exception
{
Connection conn = ds.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
StringBuffer query = new StringBuffer();
List<DayBill> list = new ArrayList<DayBill>();
query
.append(" select SUM(GRAND_TOTAL) , substr(BILL_DATE,0,11) ")
.append(" from R_BILL where substr(BILL_DATE,0,11) >= date('now','localtime','-30 day') ");
query.append(" group by strftime('%d',BILL_DATE) ");
query.append(" order by BILL_DATE ASC ");
try
{
DayBill daybill;
ps = conn.prepareStatement(query.toString());
rs = ps.executeQuery();
while(rs.next())
{
daybill = new DayBill();
daybill.setTotalAmount(rs.getBigDecimal(1));
daybill.setDate(rs.getString(2));
list.add(daybill);
}
}
finally
{
if(rs != null)
rs.close();
if(ps != null)
ps.close();
if(conn != null)
conn.close();
}
return list;
}
this is what i want, like income perday

How to execute query on csv file

i have uploaded a csv file and also make a data-table from csv file.now i want to find distinct values from each columns of data-table.what will be the code for this.
i have tried by this code but there is error show that object is not ADODB.what is ADODB and how can i remove this error
public static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
//read column names
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
foreach (DataColumn col in csvdata.Columns)
{
foreach (DataRow ro in csvdata.Rows)
{
textBox1.Text = "" + ro[col];
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Weka - Naive Bayes always gives borderline results

I am trying to write a text classifier in Weka with Naive Bayes. I have a collection of Foursquare tips as training data with close to 500 of them marked as positive and approximately same marked as negative in an excel file. The input file has two columns with first one being the tip text and second one the marked polarity. I am using AFINN-111.txt to add an attribute to enhance the output. It calculates all the polar words in that tip and gives a final score of all the words. Here is my entire code:
public class DataReader {
static Map<String, Integer> affinMap = new HashMap<String, Integer>();
public List<List<Object>> createAttributeList() {
ClassLoader classLoader = getClass().getClassLoader();
initializeAFFINMap(classLoader);
File inputWorkbook = new File(classLoader
.getResource("Tip_dataset2.xls").getFile());
Workbook w;
Sheet sheet = null;
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
sheet = w.getSheet(0);
} catch (Exception e) {
e.printStackTrace();
}
List<List<Object>> attributeList = new ArrayList<List<Object>>();
for (int i = 1; i < sheet.getRows(); i++) {
String tip = sheet.getCell(0, i).getContents();
tip = tip.replaceAll("'", "");
tip = tip.replaceAll("\"", "");
tip = tip.replaceAll("%", " percent");
tip = tip.replaceAll("#", " ATAUTHOR");
String polarity = getPolarity(sheet.getCell(1, i).getContents());
int affinScore = 0;
String[] arr = tip.split(" ");
for (int j = 0; j < arr.length; j++) {
if (affinMap.containsKey(arr[j].toLowerCase())) {
affinScore = affinScore
+ affinMap.get(arr[j].toLowerCase());
}
}
List<Object> attrs = new ArrayList<Object>();
attrs.add(tip);
attrs.add(affinScore);
attrs.add(polarity);
attributeList.add(attrs);
}
return attributeList;
}
private String getPolarity(String cell) {
if (cell.equalsIgnoreCase("positive")) {
return "positive";
} else {
return "negative";
}
}
private void initializeAFFINMap(ClassLoader classLoader) {
try {
InputStream stream = classLoader
.getResourceAsStream("AFINN-111.txt");
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
while ((str = br.readLine()) != null) {
String[] array = str.split("\t");
affinMap.put(array[0], Integer.parseInt(array[1]));
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
List<List<Object>> attrList=new DataReader().createAttributeList();
new CreateTrainedModel().createTrainingData(attrList);
}
}
Here is the actual classifier class:
public class CreateTrainedModel {
public void createTrainingData(List<List<Object>> attrList)
throws Exception {
Attribute tip = new Attribute("tip", (FastVector) null);
Attribute affin = new Attribute("affinScore");
FastVector pol = new FastVector(2);
pol.addElement("positive");
pol.addElement("negative");
Attribute polaritycl = new Attribute("polarity", pol);
FastVector inputDataDesc = new FastVector(3);
inputDataDesc.addElement(tip);
inputDataDesc.addElement(affin);
inputDataDesc.addElement(polaritycl);
Instances dataSet = new Instances("dataset", inputDataDesc,
attrList.size());
// Set class index
dataSet.setClassIndex(2);
for (List<Object> onList : attrList) {
Instance in = new Instance(3);
in.setValue((Attribute) inputDataDesc.elementAt(0), onList.get(0)
.toString());
in.setValue((Attribute) inputDataDesc.elementAt(1),
Integer.parseInt(onList.get(1).toString()));
in.setValue((Attribute) inputDataDesc.elementAt(2), onList.get(2)
.toString());
dataSet.add(in);
}
Filter f = new StringToWordVector();
f.setInputFormat(dataSet);
dataSet = Filter.useFilter(dataSet, f);
Classifier model = (Classifier) new NaiveBayes();
try {
model.buildClassifier(dataSet);
} catch (Exception e1) { // TODO Auto-generated catch block
e1.printStackTrace();
}
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
"FS-TipsNaiveBayes.model"));
oos.writeObject(model);
oos.flush();
oos.close();
FastVector fvWekaAttributes1 = new FastVector(3);
fvWekaAttributes1.addElement(tip);
fvWekaAttributes1.addElement(affin);
Instance in = new Instance(3);
in.setValue((Attribute) fvWekaAttributes1.elementAt(0),
"burger here is good");
in.setValue((Attribute) fvWekaAttributes1.elementAt(1), 0);
Instances testSet = new Instances("dataset", fvWekaAttributes1, 1);
in.setDataset(testSet);
double[] fDistribution = model.distributionForInstance(in);
System.out.println(fDistribution);
}
}
The problem I am facing is with any input the output distribution is always in the range of [0.52314376998377, 0.47685623001622995]. And it is always more towards the positive than the negative. These figures do not change drastically. Any idea what wrong am I doing?
I didn't read your code, but one thing I can say is that the AFFIN score is normalized between a certain range. If your output is more towards a positive range then you need to change your classification cost function, because it is overfitting your data.

How to edit data with dynamic TableView with dynamic column in JAVAFX

Today This is the demo to show data from CSV for DAT file without make custom class on tableView in JavaFX 2.0. I call this TableView as Dynamic TableView because the tableview automatically manages the columns and rows.
On my research about the editable on tableView we must have a custom class and implement it to tableView to show as this demo ==> http://docs.oracle.com/javafx/2/ui_controls/table-view.htm
But in this case I can not do it because we don't know how many column example with csv file or .dat file.... I want to do editable on this tableView in this case by add TextField into TableCell. How does it do without make custom class (because you do not how many column ...), and if it must make custom class then how about the design of custom class for this case?
Could you please help me?
private void getDataDetailWithDynamic() {
tblView.getItems().clear();
tblView.getColumns().clear();
tblView.setPlaceholder(new Label("Loading..."));
// #Override
try {
File aFile = new File(txtFilePath.getText());
InputStream is = new BufferedInputStream(new FileInputStream(aFile));
Reader reader = new InputStreamReader(is, "UTF-8");
BufferedReader in = new BufferedReader(reader);
final String headerLine = in.readLine();
final String[] headerValues = headerLine.split("\t");
for (int column = 0; column < headerValues.length; column++) {
tblView.getColumns().add(
createColumn(column, headerValues[column]));
}
// Data:
String dataLine;
while ((dataLine = in.readLine()) != null) {
final String[] dataValues = dataLine.split("\t");
// Add additional columns if necessary:
for (int columnIndex = tblView.getColumns().size(); columnIndex < dataValues.length; columnIndex++) {
tblView.getColumns().add(createColumn(columnIndex, ""));
}
// Add data to table:
ObservableList<StringProperty> data = FXCollections
.observableArrayList();
for (String value : dataValues) {
data.add(new SimpleStringProperty(value));
}
tblView.getItems().add(data);
}
} catch (Exception ex) {
System.out.println("ex: " + ex.toString());
}
for(int i=0; i<tblView.getColumns().size(); i++) {
TableColumn col = (TableColumn)tblView.getColumns().get(i);
col.setPrefWidth(70);
}
}
private TableColumn createColumn(
final int columnIndex, String columnTitle) {
TableColumn column = new TableColumn(DefaultVars.BLANK_CHARACTER);
String title;
if (columnTitle == null || columnTitle.trim().length() == 0) {
title = "Column " + (columnIndex + 1);
} else {
title = columnTitle;
}
Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>() {
#Override
public TableCell call(TableColumn p) {
System.out.println("event cell");
EditingCellData cellExtend = new EditingCellData();
return cellExtend;
}
};
column.setText(title);
column.setCellValueFactory(cellFactory);
return column;
}
Thanks for your reading.
This is the best way to resolve it ==> https://forums.oracle.com/message/11216643#11216643
I'm really thank for your reading about that.
Thanks

Resources