I am new to stackoverflow and to Java. I am trying to fetch the data from the database then display it in a JSF page.
For the table I have a model : BusesInfo.java that contains getters and setters for the attributes of the table.
then I also have BusesDao that fetches the data from DB and stores it in an array list. BusesInfoBean that links these data to the JSF page. The connection to the database is success. the JSF page contains a table that calls BusesInfobean.busesInfo in the columns i call BusesInfo.attribute
Please I need your help! Below you can find sample codes:
package beans;
import daos.BusesDao;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import models.BusesInfo;
#ViewScoped
public class BusesInfoBean implements Serializable {
private final BusesDao busesDao = new BusesDao();
private ArrayList<BusesInfo> busesInfo;
public BusesInfoBean(){}
#PostConstruct
public void init(){
try {
busesInfo = busesDao.buildBusesInfo();
} catch (Exception ex) {
Logger.getLogger(ManageEventsBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ArrayList<BusesInfo> getBusesInfo() {
return busesInfo;
}
public void setBusesInfo(ArrayList<BusesInfo> busesInfo) {
this.busesInfo = busesInfo;
}
}
BusesDao.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import models.BusesInfo;
import java.util.logging.Logger;
import java.util.logging.Level;
public class BusesDao extends ConnectionDao {
public ArrayList<BusesInfo> buildBusesInfo() throws Exception {
ArrayList<BusesInfo> list = new ArrayList<>();
Connection conn = getConnection();
try {
String sql = "SELECT * FROM BUSES_INFO";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(populateBusesInfo(rs));
}
rs.close();
ps.close();
return list;
} catch (SQLException e) {
throw new SQLException(e.getMessage());
}
}
private BusesInfo populateBusesInfo(ResultSet rs) throws SQLException {
BusesInfo busesInfo = new BusesInfo();
busesInfo.setBusID(rs.getInt("BUS_ID"));
busesInfo.setDriverID(rs.getInt("DRIVER_ID"));
busesInfo.setDepartureTime(rs.getString("DEPARTURE_TIME"));
busesInfo.setArrivalTime(rs.getString("ARRIVAL_TIME"));
busesInfo.setRouteEn(rs.getString("ROUTE_EN"));
busesInfo.setRouteAr(rs.getString("ROUTE_AR"));
busesInfo.setLicensePlate(rs.getString("LICENSE_PLATE"));
busesInfo.setCapacity(rs.getInt("CAPACITY"));
return busesInfo;
}
public static void main(String [] args){
try {
BusesDao busesDao = new BusesDao();
ArrayList<BusesInfo> busesInfo = busesDao.buildBusesInfo();
} catch (Exception ex) {
Logger.getLogger(EventsDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
the model class BusesInfo only contains getters and setters:
public class BusesInfo implements Serializable {
private int busID;
private int driverID;
private String departureTime;
private String arrivalTime;
private String routeEn;
private String routeAr;
private String licensePlate;
private int capacity;
public BusesInfo(){}
/**
*
* #param busID
* #param driverID
* #param departureTime
* #param arrivalTime
* #param routeEn
* #param routeAr
* #param licensePlate
* #param capacity
*/
public BusesInfo(int busID, int driverID, String departureTime, String arrivalTime, String routeEn, String routeAr, String licensePlate, int capacity) {
this.busID = busID;
this.driverID = driverID;
this.departureTime = departureTime;
this.arrivalTime = arrivalTime;
this.routeEn = routeEn;
this.routeAr = routeAr;
this.licensePlate = licensePlate;
this.capacity = capacity;
}
public int getBusID() {
return busID;
}
public void setBusID(int busID) {
this.busID = busID;
}
public int getDriverID() {
return driverID;
}
public void setDriverID(int driverID) {
this.driverID = driverID;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getRouteEn() {
return routeEn;
}
public void setRouteEn(String routeEn) {
this.routeEn = routeEn;
}
public String getRouteAr() {
return routeAr;
}
public void setRouteAr(String routeAr) {
this.routeAr = routeAr;
}
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
}
JSF page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>#{msgs.buses}</title>
</h:head>
<h:body>
<div>
<ui:decorate template="/app_templates/app_template.xhtml">
<h:form id="bus_info_form">
<p:dataTable
id="bus_info_tbl"
value = "#{busesInfoBean.busesInfo}"
class = "dataTable"
var="event"
rows="2"
dir="#{langBean.dir}"
emptyMessage="#{msgs.no_buses}"
paginator="true"
paginatorPosition="top"
paginatorTemplate="#{langBean.isEnglish? '{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}' : '{RowsPerPageDropdown} {LastPageLink} {NextPageLink} {PageLinks} {PreviousPageLink} {FirstPageLink}'}"
>
<p:ajax event="rowSelectRadio"
update=":bus_info_form:bus_info_tbl"/>
<f:facet name="header" id="header">
#{msgs.buses}
</f:facet>
<p:column selectionMode="single" style="width:5%"/>
<p:column headerText="#{msgs.bus_id}"
style="width:15%"
sortBy="#{busesInfo.busID}">
<h:outputText value="#{busesInfo.busID}"/>
</p:column>
<p:column headerText="#{msgs.driver_id}"
style="width:15%"
sortBy="#{busesInfo.driverID}">
<h:outputText value="#{busesInfo.driverID}"/>
</p:column>
<p:column headerText="#{msgs.departure_time}"
style="width:15%"
sortBy="#{busesInfo.departureTime}">
<h:outputText value="#{busesInfo.departureTime}"/>
</p:column>
<p:column headerText="#{msgs.arrival_time}"
style="width:15%"
sortBy="#{busesInfo.arrivalTime}">
<h:outputText value="#{busesInfo.arrivalTime}"/>
</p:column>
<p:column headerText="#{msgs.route}"
style="width:20%"
filterBy="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}"
filterMatchMode="contains"
sortBy="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}">
<h:outputText value="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}"/>
</p:column>
<p:column headerText="#{msgs.license_plate}"
style="width:15%"
sortBy="#{busesInfo.licensePlate}">
<h:outputText value="#{busesInfo.licensePlate}"/>
</p:column>
<p:column headerText="#{msgs.capacity}"
style="width:15%"
sortBy="#{busesInfo.capacity}">
<h:outputText value="#{busesInfo.capacity}"/>
</p:column>
</p:dataTable>
</h:form>
</ui:decorate>
</div>
</h:body>
</html>
Related
my code is working to 90% I think.
The Output is right, but not all columns are shown in the tableview.
I don't know where the problem is.
The fx:id is right, the code too, I believe.
Here's a picture of the openend program. I will give you also my output an my controller an table-code. The launching code isn't important.
Picture:
http://www.directupload.net/file/d/3791/aitj4rff_png.htm
Output:
*** Loaded Oracle-Driver ***
*** Connected with Database ***
Film: Hugo Gesehen: JA
Film: FAST and FURIOS 6 Gesehen: JA
Film: Emil Gesehen: NEIN
Film: DAS_BOOT Gesehen: JA
*** Database data saved to Observable List named 'data'
*** Table Items setted ***
table_controller:
package controller;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import oracle.jdbc.*;
import model.filmtable_data;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
#SuppressWarnings("unused")
public class table_controller implements Initializable {
private ObservableList<filmtable_data> filmData = FXCollections.observableArrayList();
#FXML
private TableView<filmtable_data> FilmTable;
#FXML
private TableColumn<filmtable_data, String> Filmtitel_Col;
#FXML
private TableColumn<filmtable_data, Integer> ID_Col;
#FXML
private TableColumn<filmtable_data, String> Gesehen_Col;
#Override
public void initialize(URL location, ResourceBundle resources) {
// Observable List
ID_Col.setCellValueFactory(new PropertyValueFactory<filmtable_data, Integer>("rID"));
Filmtitel_Col.setCellValueFactory(new PropertyValueFactory<filmtable_data, String>("rFilmtitel"));
Gesehen_Col.setCellValueFactory(new PropertyValueFactory<filmtable_data, String>("rGesehen"));
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("*** Loaded Oracle-Driver ***");
} catch (ClassNotFoundException e1) {
System.out.println("Driver-Loading failed.");
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:lukas/1234#10.140.79.39:1521:OTTO");
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("SELECT FILMTITEL, GESEHEN FROM LUKA1");
String filmtitel = "empty";
String gesehen = "empty";
int zaehler = 1;
System.out.println("*** Connected with Database ***");
while (resultset.next()) {
filmtitel = resultset.getString("FILMTITEL");
gesehen = resultset.getString("GESEHEN");
System.out.println("Film: " + filmtitel + "\t\t\tGesehen: " + gesehen);
filmtable_data entry = new filmtable_data(zaehler, filmtitel, gesehen);
filmData.add(entry);
zaehler++;
}
System.out.println("*** Database data saved to Observable List named 'data'");
FilmTable.setItems(filmData);
System.out.println("*** Table Items setted ***");
statement.close();
} catch (SQLException e) {
System.out.println("Login fehlgeschlagen.");
e.printStackTrace();
}
}
}
filmtable_data:
package model;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class filmtable_data {
private final SimpleIntegerProperty rID;
private final SimpleStringProperty rFilmtitel;
private final SimpleStringProperty rGesehen;
public filmtable_data (Integer sID, String sFilmtitel, String sGesehen) {
this.rID = new SimpleIntegerProperty(sID);
this.rFilmtitel = new SimpleStringProperty(sFilmtitel);
this.rGesehen = new SimpleStringProperty(sGesehen);
}
public Integer getRID() {
return rID.get();
}
public void setRID(int set) {
rID.set(set);
}
public String getRFilmtitel() {
return rFilmtitel.get();
}
public void setRFilmtitel(String set) {
rFilmtitel.set(set);
}
public String setRGesehen() {
return rGesehen.get();
}
public void setRGesehen(String set) {
rGesehen.set(set);
}
}
the fx-file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="366.0" prefWidth="268.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.table_controller">
<children>
<TableView fx:id="FilmTable" prefHeight="366.0" prefWidth="425.0">
<columns>
<TableColumn fx:id="ID_Col" minWidth="-Infinity" prefWidth="43.0" text="ID" />
<TableColumn fx:id="Filmtitel_Col" prefWidth="137.0" text="Filmtitel" />
<TableColumn fx:id="Gesehen_Col" prefWidth="137.0" text="Gesehen" />
</columns>
</TableView>
</children>
</AnchorPane>
You have a typo in your POJO class, and there is not getter:
This is wrong:
public String setRGesehen() {
return rGesehen.get();
}
It should be:
public String getRGesehen() {
return rGesehen.get();
}
Notice you should add also the property methods, like:
public StringProperty rGesehenProperty() {
return rGesehen;
}
Even with the wrong getter, as the PropertyValueFactory looks first for the property, it would have worked.
I took the sample code from How to create custom components in JavaFX 2.0 using FXML?. the code working fine in jdk7 but the checkbox and combo box values are not working in jdk8. I am not able to click the check box even and select the dropdown.
Please guide me for the same.
Please find the sample code below
Package structure
com.example.javafx.choice
ChoiceCell.java
ChoiceController.java
ChoiceModel.java
ChoiceView.fxml
com.example.javafx.mvc
FxmlMvcPatternDemo.java
MainController.java
MainView.fxml
MainView.properties
ChoiceCell.java
package com.example.javafx.choice;
import java.io.IOException;
import java.net.URL;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
public class ChoiceCell extends ListCell<ChoiceModel>
{
#Override
protected void updateItem(ChoiceModel model, boolean bln)
{
super.updateItem(model, bln);
if(model != null)
{
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try
{
Node root = (Node)fxmlLoader.load(location.openStream());
ChoiceController controller = (ChoiceController)fxmlLoader.getController();
controller.setModel(model);
setGraphic(root);
}
catch(IOException ioe)
{
throw new IllegalStateException(ioe);
}
}
}
}
ChoiceController.java
package com.example.javafx.choice;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
public class ChoiceController
{
private final ChangeListener<String> LABEL_CHANGE_LISTENER = new ChangeListener<String>()
{
public void changed(ObservableValue<? extends String> property, String oldValue, String newValue)
{
updateLabelView(newValue);
}
};
private final ChangeListener<Boolean> IS_SELECTED_CHANGE_LISTENER = new ChangeListener<Boolean>()
{
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue)
{
updateIsSelectedView(newValue);
}
};
private final ChangeListener<Boolean> IS_VISIBILITY1_CHANGE_LISTENER = new ChangeListener<Boolean>() {
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue) {
updateIsVisibleView1(newValue);
}};
#FXML
private Label labelView;
#FXML
private CheckBox isSelectedView;
#FXML
ComboBox isVisible1;
private ChoiceModel model;
public ChoiceModel getModel()
{
return model;
}
public void setModel(ChoiceModel model)
{
if(this.model != null)
removeModelListeners();
this.model = model;
setupModelListeners();
updateView();
}
private void removeModelListeners()
{
model.labelProperty().removeListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().removeListener(IS_SELECTED_CHANGE_LISTENER);
model.isVisibleProperty1().removeListener(IS_VISIBILITY1_CHANGE_LISTENER);
isSelectedView.selectedProperty().unbindBidirectional(model.isSelectedProperty());
}
private void setupModelListeners()
{
model.labelProperty().addListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().addListener(IS_SELECTED_CHANGE_LISTENER);
model.isVisibleProperty1().addListener(IS_VISIBILITY1_CHANGE_LISTENER);
isSelectedView.selectedProperty().bindBidirectional(model.isSelectedProperty());
}
private void updateView()
{
updateLabelView();
updateIsSelectedView();
updateIsVisibleView1();
}
private void updateLabelView(){ updateLabelView(model.getLabel()); }
private void updateLabelView(String newValue)
{
labelView.setText(newValue);
}
private void updateIsSelectedView(){ updateIsSelectedView(model.isSelected()); }
private void updateIsSelectedView(boolean newValue)
{
isSelectedView.setSelected(newValue);
}
private void updateIsVisibleView1() {
updateIsVisibleView1(model.isVisible1());
}
private void updateIsVisibleView1(boolean newValue) {
isVisible1.setVisible(newValue);
}
}
ChoiceModel.java
package com.example.javafx.choice;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class ChoiceModel
{
private final StringProperty label;
private final BooleanProperty isSelected;
private final BooleanProperty isVisible1;
public ChoiceModel(String label, boolean isSelected, boolean isVisible1)
{
this.label = new SimpleStringProperty(label);
this.isSelected = new SimpleBooleanProperty(isSelected);
this.isVisible1 = new SimpleBooleanProperty(isVisible1);
}
public String getLabel(){ return label.get(); }
public void setLabel(String label){ this.label.set(label); }
public StringProperty labelProperty(){ return label; }
public boolean isSelected(){ return isSelected.get(); }
public void setSelected(boolean isSelected){ this.isSelected.set(isSelected); }
public BooleanProperty isSelectedProperty(){ return isSelected; }
public boolean isVisible1()
{
return isVisible1.get();
}
public void setVisible1(boolean isVisible1)
{
this.isVisible1.set(isVisible1);
}
public BooleanProperty isVisibleProperty1()
{
return isVisible1;
}
}
ChoiceView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.collections.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<HBox xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="com.example.javafx.choice.ChoiceController">
<children>
<CheckBox fx:id="isSelectedView" />
<Label fx:id="labelView" />
<ComboBox id="isVisible1" fx:id="isVisible1" value="last 7 digits" visible="false">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="last 10 digits" />
<String fx:value="last 9 digits" />
<String fx:value="last 8 digits" />
<String fx:value="last 7 digits" />
<String fx:value="last 6 digits" />
<String fx:value="last 5 digits" />
<String fx:value="last 4 digits" />
<String fx:value="last 3 digits" />
</FXCollections>
</items>
</ComboBox>
</children>
</HBox>
FxmlMvcPatternDemo.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceController;
import java.util.ResourceBundle;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FxmlMvcPatternDemo extends Application
{
public static void main(String[] args) throws ClassNotFoundException
{
Application.launch(FxmlMvcPatternDemo.class, args);
}
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load
(
FxmlMvcPatternDemo.class.getResource("MainView.fxml"),
ResourceBundle.getBundle(FxmlMvcPatternDemo.class.getPackage().getName()+".MainView")/*properties file*/
);
ChoiceController controller = new ChoiceController();
stage.setScene(new Scene(root));
stage.show();
}
}
MainController.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceCell;
import com.example.javafx.choice.ChoiceModel;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
public class MainController implements Initializable
{
#FXML
private ListView<ChoiceModel> choicesView;
#Override
public void initialize(URL url, ResourceBundle rb)
{
choicesView.setCellFactory(new Callback<ListView<ChoiceModel>, ListCell<ChoiceModel>>()
{
public ListCell<ChoiceModel> call(ListView<ChoiceModel> p)
{
return new ChoiceCell();
}
});
choicesView.setItems(FXCollections.observableArrayList
(
new ChoiceModel("Tiger", true, false),
new ChoiceModel("Shark", false, true),
new ChoiceModel("Bear", false, true),
new ChoiceModel("Wolf", true, true)
));
}
#FXML
private void handleForceChange(ActionEvent event)
{
if(choicesView != null && choicesView.getItems().size() > 0)
{
boolean isSelected = choicesView.getItems().get(0).isSelected();
choicesView.getItems().get(0).setSelected(!isSelected);
}
}
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox
xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.javafx.mvc.MainController"
prefWidth="300"
prefHeight="400"
fillWidth="false"
>
<children>
<Label text="%title" />
<ListView fx:id="choicesView" />
<Button text="Force Change" onAction="#handleForceChange" />
</children>
</VBox>
MainView.proprties
title=JavaFX 2.0 FXML MVC demo
I didn't dig deeper but refactoring like as following should suffice. Double check for correct executions of attached and removed listeners.
public class ChoiceCell extends ListCell<ChoiceModel> {
private Node root;
private ChoiceController controller;
public ChoiceCell() {
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try {
root = (Node) fxmlLoader.load(location.openStream());
controller = (ChoiceController) fxmlLoader.getController();
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
#Override
protected void updateItem(ChoiceModel model, boolean bln) {
super.updateItem(model, bln);
if (model != null) {
controller.setModel(model);
setGraphic(root);
} else {
setGraphic(null);
}
}
}
I want to convert csv file to xml and i want to send the converted xml file to a queue in activemq..Is there any sample code or any reference websites or blogs please help to find sample code for this program..
Use the Bindy and Xstream components. From http://workingwithqueues.blogspot.ch/2012/07/converting-csv-to-xml-with-camel-bindy.html (with a JMS endpoint instead of a file endpoint):
DataFormat bindy = new BindyCsvDataFormat("com.package.dto");
from("file://TEST?fileName=Employee.csv")
.unmarshal(bindy)
.marshal()
.xstream()
.to("jms:queue:FOO.BAR");
For connecting to JMS have a look at the JMS and ActiveMQ components.
package org.mycompany.conversion;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Greeting {
#XmlElementWrapper(name = "Person")
#XmlElement(name = "persons")
private List<Person> persons;
public List<Person> getPerson() {
return persons;
}
public void setPerson(List<Person> persons) {
this.persons = persons;
}
}
========================================================================================
package org.mycompany.conversion;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#CsvRecord(separator = ",")
public class Person {
#DataField(pos = 1)
#XmlElement
private int id;
#DataField(pos = 2)
#XmlElement
private String name;
#DataField(pos = 3)
#XmlElement
private int age;
#Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
======================================================================================
package org.mycompany.conversion;
import javax.xml.bind.JAXBContext;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.DataFormat;
public class CsvConversion {
public static void main(String[] args) throws Exception {
JaxbDataFormat xmlDataFormat = new JaxbDataFormat();
JAXBContext con = JAXBContext.newInstance(Greeting.class);
xmlDataFormat.setContext(con);
DataFormat bindy = new BindyCsvDataFormat(Person.class);
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:src/main/data/in/csv?noop=true").split().tokenize("\n").unmarshal(bindy)
// constanr(true):-aggregate all using same expression
.aggregate(constant(true), new AttachAggregation())
//mandatory after aggregate
.completionTimeout(100)//end after this gives problem
.marshal(xmlDataFormat).log("xml body is ${body}")
.to("file:src/main/data/in/xml?fileName=convertedXml.xml");// .aggregate(new
// AttachAggreagation());
}
});
context.start();
Thread.sleep(5000);
}
}
=========================================================================================
package org.mycompany.conversion;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.Exchange;
import org.apache.camel.processor.aggregate.AggregationStrategy;
public class AttachAggregation implements AggregationStrategy {
List<Person> list = new ArrayList();
Greeting gre = new Greeting();
#Override
//person-address
// greeting-user
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
Person newBody1 = newExchange.getIn().getBody(Person.class);
list.add(newBody1);
return newExchange;
} else {
Person newBody2 = newExchange.getIn().getBody(Person.class);
list.add(newBody2);
gre.setPerson(list);
oldExchange.getIn().setBody(gre);
return oldExchange;
}
}
}
I have this problem and I'm really going crazy without having a result.
I have a form and all fields are required through validator.xml
My form contains a field for the upload image (required)
When I click the submit button present a paggina waiting through (execAndWait configured in struts.xml).
my big problem is this:
the waiting page always redirect to my form page with text (the file field and mandatory).
Here is the code:
/register.jsp
<!-- al submit chiama l'action register -->
<action name="register" class="action.Register" method="execute" >
<interceptor-ref name="defaultStack" />
<interceptor-ref name="fileUpload">
<param name="maximumSize">10000000</param>
<param name="allowedTypes">image/jpeg,image/gif,image/jpg</param>
</interceptor-ref>
<interceptor-ref name="params"></interceptor-ref>
<interceptor-ref name="execAndWait">
</interceptor-ref>
<result name="success">index.jsp</result>
<result name="input">/register.jsp</result>
<result name="wait">/test.jsp</result>
</action>
waiting page:
<meta http-equiv="refresh" content="5;url=<s:url includeParams="all" />"/>
</head>
<body>
<p>your request is processing...</p>
<img src="images/indicator.gif"/>
my form:
<s:form method="post" action="register" validate="false" enctype="multipart/form-data">
<s:textfield key="utenteBean.nome" name="utenteBean.nome" value="a" />
<s:textfield key="utenteBean.nickname" name="utenteBean.nickname" value="a" />
<sj:datepicker key="utenteBean.nato" name="utenteBean.nato"
showButtonPanel="true" displayFormat="dd/mm/yy" value="25/09/1983"/>
<s:textfield key="utenteBean.professione" name="utenteBean.professione" value="a"/>
<s:textfield key="utenteBean.eta" name="utenteBean.eta" value="3"/>
<s:textfield key="utenteBean.dj_preferito" name="utenteBean.dj_preferito" value="a" />
<s:textfield key="utenteBean.rave_fatti" name="utenteBean.rave_fatti" value="3" />
<s:textfield key="utenteBean.sito_preferito" name="utenteBean.sito_preferito" value="a" />
<s:textfield key="utenteBean.come_siveste" name="utenteBean.come_siveste" value="a" />
<s:textarea key="utenteBean.messaggio" name="utenteBean.messaggio" value="a"/>
<s:file label="file" name="file" requiredLabel="true"" ></s:file>
really thanks for your help
I suppose that you have put wrong field name for the file tag. Can you show us your action class? Regarding to that instead of:
<s:file label="file" name="file" requiredLabel="true"" ></s:file>
try to use:
<s:file label="file" name="utenteBean.file" requiredLabel="true"" ></s:file>
or just check in your action class the name of the file property.
yes sure ... below my Action class:
public class Register extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private UtenteBeanAction utenteBean;
private File file;
private String fileContentType;
private String fileFileName;
private String filesPath;
private ServletContext context;
Map<String, Object> session;
public String execute(){
if (file != null) {
File file = this.file;
// /System.out.println(file.getName());
try {
Util.saveFile(file, fileFileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
} else {
return ERROR;
}
return SUCCESS;
}
public void validate(){
if(this.fileFileName==null){
this.addFieldError("file", "errore");
}
}
public UtenteBeanAction getUtenteBean() {
return utenteBean;
}
public void setUtenteBean(UtenteBeanAction utenteBean) {
this.utenteBean = utenteBean;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFilesPath() {
return filesPath;
}
public void setFilesPath(String filesPath) {
this.filesPath = filesPath;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
#Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
}
Thank you so much for your help ...
I solved it by putting my bean in session. I could not find a better solution after many hours of work.
If other people have the same problem I can see the changes I made in my. Action
package action;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import Bean.UtenteBeanAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import Utility.Util;
public class Register extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private UtenteBeanAction utenteBean;
private ServletContext context;
Map<String, Object> session;
public String execute(){
session.put("utente", utenteBean);
if (utenteBean.getFile() != null) {
File file = utenteBean.getFile();
// /System.out.println(file.getName());
try {
Util.saveFile(file, utenteBean.getFileFileName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
} else {
return ERROR;
}
return SUCCESS;
}
public void validate() {
if (session.get("utente") != null) {
this.utenteBean = (UtenteBeanAction) session.get("utente");
}
if (this.utenteBean.getFileFileName() == null) {
this.addFieldError("utenteBean.file", "errore");
}
}
public UtenteBeanAction getUtenteBean() {
return utenteBean;
}
public void setUtenteBean(UtenteBeanAction utenteBean) {
this.utenteBean = utenteBean;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
#Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
}
I hope I can be of help.
Thanks for the support.
Base on the sample from:
http://showcase.richfaces.org/richfaces/component-sample.jsf?demo=dataTable&sample=dataTableEdit&skin=blueSky
I did a bit modify on the xhtml page and CarBean to include a button to display the result. Result display as expected but the popup panel not working (ie. no popup).
Software version I use:
richface 4.3.0 Final
GAE 1.7.2
Note: It work fine on my local notebook and problem mention above apply when deploy online.
Here the online url
http://cloudenterpriseapps.appspot.com/public/test/testPopup5.jsf
Any help?
[CarsBean.java]
package test.faces.bean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import org.richfaces.demo.common.data.RandomHelper;
import org.richfaces.demo.tables.model.cars.InventoryItem;
import org.richfaces.demo.tables.model.cars.InventoryVendorItem;
import org.richfaces.demo.tables.model.cars.InventoryVendorList;
#ManagedBean(name = "carsBean2")
#SessionScoped
public class CarsBean2 implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3832235132261771583L;
private static final int DECIMALS = 1;
private static final int CLIENT_ROWS_IN_AJAX_MODE = 15;
private static final int ROUNDING_MODE = BigDecimal.ROUND_HALF_UP;
private List<InventoryItem> allInventoryItems = null;
private List<InventoryVendorList> inventoryVendorLists = null;
private int currentCarIndex;
private InventoryItem editedCar;
private int page = 1;
private int clientRows;
public void switchAjaxLoading(ValueChangeEvent event) {
this.clientRows = (Boolean) event.getNewValue() ? CLIENT_ROWS_IN_AJAX_MODE : 0;
}
public void remove() {
allInventoryItems.remove(allInventoryItems.get(currentCarIndex));
}
public void store() {
allInventoryItems.set(currentCarIndex, editedCar);
}
public List<SelectItem> getVendorOptions() {
List<SelectItem> result = new ArrayList<SelectItem>();
result.add(new SelectItem("", ""));
for (InventoryVendorList vendorList : getInventoryVendorLists()) {
result.add(new SelectItem(vendorList.getVendor()));
}
return result;
}
public List<String> getAllVendors() {
List<String> result = new ArrayList<String>();
for (InventoryVendorList vendorList : getInventoryVendorLists()) {
result.add(vendorList.getVendor());
}
return result;
}
public List<InventoryVendorList> getInventoryVendorLists() {
synchronized (this) {
if (inventoryVendorLists == null) {
inventoryVendorLists = new ArrayList<InventoryVendorList>();
List<InventoryItem> inventoryItems = getAllInventoryItems();
Collections.sort(inventoryItems, new Comparator<InventoryItem>() {
public int compare(InventoryItem o1, InventoryItem o2) {
return o1.getVendor().compareTo(o2.getVendor());
}
});
Iterator<InventoryItem> iterator = inventoryItems.iterator();
InventoryVendorList vendorList = new InventoryVendorList();
vendorList.setVendor(inventoryItems.get(0).getVendor());
while (iterator.hasNext()) {
InventoryItem item = iterator.next();
InventoryVendorItem newItem = new InventoryVendorItem();
itemToVendorItem(item, newItem);
if (!item.getVendor().equals(vendorList.getVendor())) {
inventoryVendorLists.add(vendorList);
vendorList = new InventoryVendorList();
vendorList.setVendor(item.getVendor());
}
vendorList.getVendorItems().add(newItem);
}
inventoryVendorLists.add(vendorList);
}
}
return inventoryVendorLists;
}
private void itemToVendorItem(InventoryItem item, InventoryVendorItem newItem) {
newItem.setActivity(item.getActivity());
newItem.setChangePrice(item.getChangePrice());
newItem.setChangeSearches(item.getChangeSearches());
newItem.setDaysLive(item.getDaysLive());
newItem.setExposure(item.getExposure());
newItem.setInquiries(item.getInquiries());
newItem.setMileage(item.getMileage());
newItem.setMileageMarket(item.getMileageMarket());
newItem.setModel(item.getModel());
newItem.setPrice(item.getPrice());
newItem.setPriceMarket(item.getPriceMarket());
newItem.setPrinted(item.getPrinted());
newItem.setStock(item.getStock());
newItem.setVin(item.getVin());
}
public String queryRec(){
String result = "";
synchronized (this) {
getAllInventoryItems();
}
return result;
}
public String initQuery(){
String result = "";
synchronized (this) {
allInventoryItems = null;
}
return result;
}
public List<InventoryItem> getInventoryItems() {
return allInventoryItems;
}
public List<InventoryItem> getAllInventoryItems() {
synchronized (this) {
if (allInventoryItems == null) {
allInventoryItems = new ArrayList<InventoryItem>();
for (int k = 0; k <= 5; k++) {
try {
switch (k) {
case 0:
allInventoryItems.addAll(createCar("Chevrolet", "Corvette", 5));
allInventoryItems.addAll(createCar("Chevrolet", "Malibu", 8));
allInventoryItems.addAll(createCar("Chevrolet", "Tahoe", 6));
break;
case 1:
allInventoryItems.addAll(createCar("Ford", "Taurus", 12));
allInventoryItems.addAll(createCar("Ford", "Explorer", 11));
break;
case 2:
allInventoryItems.addAll(createCar("Nissan", "Maxima", 9));
allInventoryItems.addAll(createCar("Nissan", "Frontier", 6));
break;
case 3:
allInventoryItems.addAll(createCar("Toyota", "4-Runner", 7));
allInventoryItems.addAll(createCar("Toyota", "Camry", 15));
allInventoryItems.addAll(createCar("Toyota", "Avalon", 13));
break;
case 4:
allInventoryItems.addAll(createCar("GMC", "Sierra", 8));
allInventoryItems.addAll(createCar("GMC", "Yukon", 10));
break;
case 5:
allInventoryItems.addAll(createCar("Infiniti", "G35", 6));
allInventoryItems.addAll(createCar("Infiniti", "EX35", 5));
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return allInventoryItems;
}
public List<InventoryItem> createCar(String vendor, String model, int count) {
ArrayList<InventoryItem> iiList = null;
try {
int arrayCount = count;
InventoryItem[] demoInventoryItemArrays = new InventoryItem[arrayCount];
for (int j = 0; j < demoInventoryItemArrays.length; j++) {
InventoryItem ii = new InventoryItem();
ii.setVendor(vendor);
ii.setModel(model);
ii.setStock(RandomHelper.randomstring(6, 7));
ii.setVin(RandomHelper.randomstring(17, 17));
ii.setMileage(new BigDecimal(RandomHelper.rand(5000, 80000)).setScale(DECIMALS, ROUNDING_MODE));
ii.setMileageMarket(new BigDecimal(RandomHelper.rand(25000, 45000)).setScale(DECIMALS, ROUNDING_MODE));
ii.setPrice(new Integer(RandomHelper.rand(15000, 55000)));
ii.setPriceMarket(new BigDecimal(RandomHelper.rand(15000, 55000)).setScale(DECIMALS, ROUNDING_MODE));
ii.setDaysLive(RandomHelper.rand(1, 90));
ii.setChangeSearches(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setChangePrice(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setExposure(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setActivity(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setPrinted(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setInquiries(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
demoInventoryItemArrays[j] = ii;
}
iiList = new ArrayList<InventoryItem>(Arrays.asList(demoInventoryItemArrays));
} catch (Exception e) {
e.printStackTrace();
}
return iiList;
}
public int getCurrentCarIndex() {
return currentCarIndex;
}
public void setCurrentCarIndex(int currentCarIndex) {
this.currentCarIndex = currentCarIndex;
}
public InventoryItem getEditedCar() {
return editedCar;
}
public void setEditedCar(InventoryItem editedCar) {
this.editedCar = editedCar;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getClientRows() {
return clientRows;
}
public void setClientRows(int clientRows) {
this.clientRows = clientRows;
}
}
[testPopup5.xhtml]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<ui:composition>
<h:head>
<title>RichFaces Showcase</title>
</h:head>
<h:body>
<h:outputStylesheet>
a.no-decor>img {
border: none;
}
</h:outputStylesheet>
<a4j:status onstart="#{rich:component('statPane')}.show()"
onstop="#{rich:component('statPane')}.hide()" />
<h:form>
<h:panelGrid columns="2">
<a4j:commandButton id="search" action="#{carsBean2.queryRec}"
value="Search" render="table" />
<a4j:commandButton id="reset" action="#{carsBean2.initQuery}"
value="Reset" type="reset" render="table" />
</h:panelGrid>
</h:form>
<h:form>
<rich:dataTable value="#{carsBean2.inventoryItems}" var="car"
id="table" rows="5">
<rich:column>
<f:facet name="header">Model</f:facet>
<h:outputText value="#{car.model}" />
</rich:column>
<rich:column>
<f:facet name="header">Price</f:facet>
<h:outputText value="#{car.price}" />
</rich:column>
<rich:column>
<a4j:commandLink styleClass="no-decor" render="editGrid"
execute="#this" oncomplete="#{rich:component('editPanel')}.show()">
<h:graphicImage value="/images/icons/common/edit.gif" alt="edit" />
<f:setPropertyActionListener target="#{carsBean2.editedCar}"
value="#{car}" />
</a4j:commandLink>
</rich:column>
</rich:dataTable>
<rich:popupPanel id="statPane" autosized="true" rendered="true">
<h:graphicImage value="/images/common/ai.gif" alt="ai" />
Please wait...
</rich:popupPanel>
<rich:popupPanel header="Edit Car Details" id="editPanel">
<h:panelGrid columns="3" id="editGrid">
<h:outputText value="Model" />
<h:outputText value="#{carsBean2.editedCar.model}" />
<h:panelGroup />
<h:outputText value="Price" />
<h:outputText value="#{carsBean2.editedCar.price}" />
<h:panelGroup />
</h:panelGrid>
<a4j:commandButton value="Cancel"
onclick="#{rich:component('editPanel')}.hide(); return false;" />
</rich:popupPanel>
</h:form>
</h:body>
</ui:composition>
</html>
Using firebug, I manage discover few diff between local and online GAE version.
1) editPanel # local change it style stage from 'visibility hidden' to 'display none' and then 'display block' when click on edit icon.
However editPanel # GAE still remain unchange with 'visibility hidden'
[Local]
<div id="j_idt9:editPanel" style="visibility: hidden;">
<div id="j_idt9:editPanel" style="display: none;">
<div id="j_idt9:editPanel" style="display: block;">
[GAE]
<div id="j_idt9:editPanel" style="visibility: hidden;">
2) under , local version contain value in table tag
3) Shown in firebug's script tab, when click on edit link, local version display as: and follow by table values.
However online version display it as and without any table values
p/s: Online: http://cloudenterpriseapps.appspot.com/public/test/testPopup5.jsf
By the way the GAE display below warning when page first load. Don't know is related to the problem or not.
[s~cloudenterpriseapps/0.365021621033424561].: SystemId Unknown; Line #57; Column #31; Failed calling setMethod method
[FireBug Script tab, Local. Click on edit link]
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="j_idt9:editGrid"><![CDATA[<table id="j_idt9:editGrid">
<tbody>
<tr>
<td>Model</td>
<td>Corvette</td>
<td></td>
</tr>
<tr>
<td>Price</td>
<td>47405</td>
<td></td>
</tr>
</tbody>
</table>
]]></update><update id="javax.faces.ViewState"><![CDATA[H4sIAAAAAAEUTEh...EUXAkFAAA]]></update></changes><extension id="org.richfaces.extension"><complete>RichFaces.$('j_idt9:editPanel').show();</complete><render>j_idt9:editGrid</render></extension></partial-response>
[FireBug Script tab, GAE. Click on edit link]
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="javax.faces.ViewState"><![CDATA[H4sIAAAAAAAAANVYbW....KBTUkFAAA]]></update></changes></partial-response>
Solved after upgrade JSF api and implementation jar from 2.0 to 2.1