Vaadin: Bind Enum values to String in Vaadin 8 - vaadin

I’m working on upgrading our application vaadin version from 7.7.24 to 8.13.3. We’ve completed all the dependency issues and i’m able to start the application in locally.
We have a textbox that is showing up the Event data.
Here is the class file that i'm using:
#Entity
#Table(name = "changelog")
public class ChangelogEvent extends BaseEntity
{
#Column(name = "remote_ip")
private String remoteIp;
#Column(name = "remote_host")
private String remoteHost;
#Column(name = "event")
#Enumerated(EnumType.ORDINAL)
private ChangelogEventType eventType;
#Column(name = "entity_type")
private String entityType;
public ChangelogEvent()
{
}
public ChangelogEvent(String remoteIp, String remoteHost, ChangelogEventType eventType)
{
this.remoteIp = remoteIp;
this.remoteHost = remoteHost;
this.eventType = eventType;
}
public String getRemoteIp()
{
return remoteIp;
}
public void setRemoteIp(String remoteIp)
{
this.remoteIp = remoteIp;
}
public ChangelogEventType getEventType()
{
return eventType;
}
public void setEventType(ChangelogEventType eventType)
{
this.eventType = eventType;
}
public String getRemoteHost()
{
return remoteHost;
}
public void setRemoteHost(String remoteHost)
{
this.remoteHost = remoteHost;
}
public String getEntityType()
{
return entityType;
}
public void setEntityType(String entityType)
{
this.entityType = entityType;
}
}
And here is my ChangelogEventType.java file that defined ChangelogEventType enum:
public enum ChangelogEventType
{
CREATED("Created"),
UPDATED("Updated"),
DELETED("Deleted"),
LOGIN("Login"),
LOGOUT("Logout"),
LOGIN_RETRY("Login Retry"),
ACCOUNT_LOCKED("Account Locked"),
PASSWORD_EXPIRED("Password Expired"),
PASSWORD_CHANGED("Password Changed");
private String text;
ChangelogEventType(String text)
{
this.text = text;
}
public String getText()
{
return text;
}
public static ChangelogEventType fromString(String text)
{
if (text != null)
{
for (ChangelogEventType event : ChangelogEventType.values())
{
if (text.equalsIgnoreCase(event.text))
{
return event;
}
}
}
return null;
}
}
Here is the code that i'm using for binding the values into textfield.
eventType = createTextField("Event", COLUMN_WIDTH);
binder.forField(eventType)
.withNullRepresentation("None")
.bind(ChangelogEvent::getEventType, ChangelogEvent::setEventType);
Is there any way to bind the Enum to textbox ?

You need to write custom converter and use it in Binder using withConverter method, in your case something like:
class StringToChangelogEventTypeConverter implements Converter<String, ChangelogEventType> {
#Override
public Result<ChangelogEventType> convertToModel(String fieldValue, ValueContext context) {
// Produces a converted value or an error
ChangelogEventType event = ChangelogEventType.fromString(fieldValue);
if (event != null) {
// ok is a static helper method that creates a Result
return Result.ok(ChangelogEventType.fromString(fieldValue));
} else {
// error is a static helper method that creates a Result
return Result.error("Please enter a number");
}
}
#Override
public String convertToPresentation(ChangelogEventType event, ValueContext context) {
// Converting to the field type should always succeed,
// so there is no support for returning an error Result.
return event.getText();
}
}

Related

button inside column for each row in tableview

In my TableView I have column with button for each row for update so I need when click the button to take all the values from the row to a new fxml window
This is my contractor class:
public class constractor {
private String co_id;
private String co_name;
private String co_address;
private String co_create_date;
private String co_description;
private String co_mobile;
private String co_type_compile;
private String co_status;
private String co_type_model;
private Button button;
public constractor(String co_id, String co_name, String co_type_compile, String co_description, String co_create_date, String co_status, String co_address, String co_mobile, String co_type_model, String button) {
this.co_id = co_id;
this.co_name = co_name;
this.co_type_compile = co_type_compile;
this.co_description = co_description;
this.co_create_date = co_create_date;
this.co_status = co_status;
this.co_address = co_address;
this.co_mobile = co_mobile;
this.co_type_model = co_type_model;
this.button = new Button("edit");
}
public String getCo_id() {
return co_id;
}
public void setCo_id(String co_id) {
this.co_id = co_id;
}
public String getCo_name() {
return co_name;
}
public void setCo_name(String co_name) {
this.co_name = co_name;
}
public String getCo_address() {
return co_address;
}
public void setCo_address(String co_address) {
this.co_address = co_address;
}
public String getCo_create_date() {
return co_create_date;
}
public void setCo_create_date(String co_create_date) {
this.co_create_date = co_create_date;
}
public String getCo_description() {
return co_description;
}
public void setCo_description(String co_description) {
this.co_description = co_description;
}
public String getCo_mobile() {
return co_mobile;
}
public void setCo_mobile(String co_mobile) {
this.co_mobile = co_mobile;
}
public String getCo_type_compile() {
return co_type_compile;
}
public void setCo_type_compile(String co_type_compile) {
this.co_type_compile = co_type_compile;
}
public String getCo_status() {
return co_status;
}
public void setCo_status(String co_status) {
this.co_status = co_status;
}
public String getCo_type_model() {
return co_type_model;
}
public void setCo_type_model(String co_type_model) {
this.co_type_model = co_type_model;
}
public Button getButton() {
return button;
}
public void setButton(Button button) {
this.button = button;
}
}
This is my class for table:
public class MainscreenController implements Initializable {
#FXML
private TableView<constractor> co_tableview;
#FXML
private TableColumn<constractor, String> col_id;
#FXML
private TableColumn<constractor, String> col_name;
#FXML
private TableColumn<constractor, String> col_compaile_type;
#FXML
private TableColumn<constractor, String> col_description;
#FXML
private TableColumn<constractor, String> col_ceartedat;
#FXML
public TableColumn<constractor, String> col_status;
#FXML
private TableColumn<constractor, String> col_mobile;
#FXML
private TableColumn<constractor, String> col_type_model;
#FXML
private TextField search;
#FXML
private TableColumn<constractor, Button> col_button;
int indexorder = -1;
ObservableList<constractor> orderdata = FXCollections.observableArrayList();
#FXML
public void ordertables() {
Connection con = DB.getConnection();
orderdata.clear();
try {
try (ResultSet rs = con.createStatement().executeQuery("select * from mr_order")) {
while (rs.next()) {
orderdata.add(new constractor(
rs.getString("co_id"),
rs.getString("co_name"),
rs.getString("co_type_model"),
rs.getString("co_description"),
rs.getString("co_create_date"),
rs.getString("co_status"),
rs.getString("co_mobile"),
rs.getString("co_address"),
rs.getString("co_type_compile"),
rs.getString("co_user_id")
));
}
countneworder();
}
} catch (SQLException ex) {
Logger.getLogger(MainscreenController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int tablesandsearchorder() {
////tableview Itemsinserting
col_id.setCellValueFactory(new PropertyValueFactory<>("co_id"));
col_name.setCellValueFactory(new PropertyValueFactory<>("co_name"));
col_compaile_type.setCellValueFactory(new PropertyValueFactory<>
("co_type_compile"));
col_description.setCellValueFactory(new PropertyValueFactory<>
("co_description"));
col_ceartedat.setCellValueFactory(new PropertyValueFactory<>
("co_create_date"));
col_status.setCellValueFactory(new PropertyValueFactory<>("co_status"));
col_mobile.setCellValueFactory(new PropertyValueFactory<>("co_mobile"));
col_type_model.setCellValueFactory(new PropertyValueFactory<>
("co_type_model"));
col_button.setCellValueFactory(new PropertyValueFactory<>("button"));
co_tableview.setItems(orderdata);
co_tableview.getItems().setAll(orderdata);
co_tableview.itemsProperty().addListener((observable, oldItems, newItems)
-> {
countorder.textProperty().bind(
Bindings.size(newItems).asString());
});
// 2. Set the filter Predicate whenever the filter changes.
search.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
filteredData.setPredicate(constractor -> {
// If filter text is empty, display all persons.
if (newValue == null || newValue.isEmpty()) {
return true;
}
// Compare first name and last name of every person with filter text.
String lowerCaseFilter = newValue.toLowerCase();
if
(constractor.getCo_name().toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches first name.
} else if (constractor.getCo_id().toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches last name.
} else if
(constractor.getCo_description().toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches last name.
}
return false; // Does not match.
});
});
// 3. Wrap the FilteredList in a SortedList.
SortedList<constractor> sortedData = new SortedList<>(filteredData);
// 4. Bind the SortedList comparator to the TableView comparator.
sortedData.comparatorProperty().bind(co_tableview.comparatorProperty());
// 5. Add sorted (and filtered) data to the table.
co_tableview.setItems(sortedData);
return 0;
}
#FXML
public void openinsert() {
try {
//in this fxml i create the new order and also i need for update the status the order from this fxml when i click the button inside the tableview
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("createorder.fxml"));
Scene scene = new Scene(fxmlLoader.load());
Stage stage = new Stage();
stage.setTitle("neworder");
stage.setScene(scene);
stage.setFullScreen(false);
stage.setResizable(false);
stage.setMinHeight(400);
stage.setMinWidth(600);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
}
It's usually recommended not mixing the view code (Button) with the model code (constractor). Instead you should use a custom TableCell class for the column.
Assuming you know how to pass the data (otherwise take a look here: Passing Parameters JavaFX FXML), all required info should be available via the constractor instance which you should pass to the new scene.
MainscreenController
#FXML
private TableColumn<constractor, Void> col_button;
...
private void editConstractor(constractor constractor) {
// TODO: implement
}
#FXML
private void initialize() {
col_button.setCellFactory(col -> new TableCell<constractor, Void>() {
private final Button button;
{
button = new Button("edit");
button.setOnAction(evt -> {
constractor item = getTableRow().getItem();
editConstractor(item);
});
}
#Override
protected void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
setGraphic(empty ? null : button);
}
});
}
You also need to remove the cellValueFactory for the button column.
Note:
Sticking to the java naming conventions would make the code easier to read. (Type names should start with an uppercase letter and identifiers should use camelCase instead of underscores assuming they're not for a static final field.)
constractor is most likely misspelled. Did you mean contractor? I recommend using the renaming functionality of your IDE to fix this typo...
(In my code I used the same spelling for the editConstractor method.)

Using the "version" annotation in a document with spring boot elasticearch

i'm using spring-boot-starter-data-elasticsearch (1.4.0.M3).
I'm unable to get the version (_version in elasticsearch query result) of a document using the annoation "version".
Any idea why the annotation isn't working ?
f.e.:
#GwtCompatible
#Document(indexName = "myIndexName")
public class Catalog implements Serializable {
private List<GroupProduct> groups;
#Id
private String uuid;
#Version
private Long version;
#Field(type = FieldType.Nested)
private List<Product> products;
private String label;
#NotEmpty
private String organizationUuid;
private List<String> organizationUnitUuids;
private Date updateDate;
private List<VAT> vats;
public Catalog() {
}
public List<GroupProduct> getGroups() {
return groups;
}
public List<Product> getProducts() {
return products;
}
public Date getUpdateDate() {
return updateDate;
}
public void setGroups(List<GroupProduct> groups) {
this.groups = groups;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public List<VAT> getVats() {
return vats;
}
public void setVats(List<VAT> vats) {
this.vats = vats;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getOrganizationUuid() {
return organizationUuid;
}
public void setOrganizationUuid(String organizationUuid) {
this.organizationUuid = organizationUuid;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public List<String> getOrganizationUnitUuids() {
return organizationUnitUuids;
}
public void setOrganizationUnitUuids(List<String> organizationUnitUuids) {
this.organizationUnitUuids = organizationUnitUuids;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}
Spring Data Elasticsearch (as of version 2.0.2) seems to have only partial support for the #Version annotation. If you annotate a document with a version field, it will be used when indexing a document. It will tell Elasticsearch that the document being saved is that specified version. If the new version is less than or equal to the version of the current document, Elasticsearch will throw a VersionConflictEngineException.
Unfortunately, Spring does not appear to populate this version field when a document is retrieved. As far as I can tell, this makes the version annotation useless. Perhaps the project will add this support in the near future. In the meantime, I have found a workaround by extending the default ResultMapper that Spring uses:
public class ExtendedResultMapper extends DefaultResultMapper {
protected MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext;
public ExtendedResultMapper(MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
super(mappingContext);
this.mappingContext = mappingContext;
}
#Override
public <T> T mapResult(GetResponse response, Class<T> clazz) {
T result = super.mapResult(response, clazz);
if (result != null) {
setPersistentEntityVersion(result, response.getVersion(), clazz);
}
return result;
}
#Override
public <T> LinkedList<T> mapResults(MultiGetResponse responses, Class<T> clazz) {
LinkedList<T> results = super.mapResults(responses, clazz);
if (results != null) {
for (int i = 0; i < results.size(); i++) {
setPersistentEntityVersion(results.get(i), responses.getResponses()[i].getResponse().getVersion(), clazz);
}
}
return results;
}
private <T> void setPersistentEntityVersion(T result, Long version, Class<T> clazz) {
if (mappingContext != null && clazz.isAnnotationPresent(Document.class)) {
PersistentProperty<ElasticsearchPersistentProperty> versionProperty = mappingContext.getPersistentEntity(clazz).getVersionProperty();
if (versionProperty != null && versionProperty.getType().isAssignableFrom(Long.class)) {
Method setter = versionProperty.getSetter();
if (setter != null) {
try {
setter.invoke(result, version);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
}
}
You can tell Spring to use this version instead of the default mapper as follows:
#Autowired
private Client client;
#Bean
public ElasticsearchTemplate elasticsearchTemplate() {
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext());
ExtendedResultMapper mapper = new ExtendedResultMapper(converter.getMappingContext());
return new ElasticsearchTemplate(client, converter, mapper);
}
Note that the version is only populated for Get or Multi-Get requests. Search results do not include version information.
You could also use this same approach to extract other information from the GetResponse objects.
Using this code, if you get a document and then try to save it back, it will fail unless you increment the version.

ResultSet mapping to object dynamically in dropwizard

I was trying to map ResultSet data to an object and returning it. Here is how i'm mapping data to an object. Now i'm having only 7 columns in resultset so this is working fine but what if i'm having 20 or 30 columns. How can i map dynamically those columns.
public class ProductsWrapperMapper implements ResultSetMapper<ProductsWrapper> {
public ProductsWrapper map(int i, ResultSet resultSet,
StatementContext statementContext) throws SQLException {
ProductsWrapper product = new ProductsWrapper();
if ((isColumnPresent(resultSet,"a_productid"))) {
product.setId(resultSet.getInt("a_productid"));
}
if ((isColumnPresent(resultSet,"a_productname"))) {
product.setProductName(resultSet.getString("a_productname"));
}
if ((isColumnPresent(resultSet,"a_productlink"))) {
product.setLink(resultSet.getString("a_productlink"));
}
if ((isColumnPresent(resultSet,"a_productimagelink"))) {
product.setImageLink(resultSet.getString("a_productimagelink"));
}
if ((isColumnPresent(resultSet,"a_websiteid"))) {
product.setWebsiteId(resultSet.getInt("a_websiteid"));
}
if ((isColumnPresent(resultSet,"a_productidentification"))) {
product.setProductIdentification(resultSet
.getString("a_productidentification"));
}
if ((isColumnPresent(resultSet,"a_adddate"))) {
product.setAddDate(resultSet.getString("a_adddate"));
}
return product;
}
public boolean isColumnPresent(ResultSet resultSet,String column) {
try {
#SuppressWarnings("unused")
int index = resultSet.findColumn(column);
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
return false;
}
}
}
Below one is my class which i was returning the object from mapper class above.
#JsonInclude(Include.NON_NULL)
public class ProductsWrapper {
private int id;
private String productName;
private String link;
private String imageLink;
private int websiteId;
private String productIdentification;
private String addDate;
int getWebsiteId() {
return websiteId;
}
public void setWebsiteId(int websiteId) {
this.websiteId = websiteId;
}
public String getProductIdentification() {
return productIdentification;
}
public void setProductIdentification(String productIdentification) {
this.productIdentification = productIdentification;
}
public String getAddDate() {
return addDate;
}
public void setAddDate(String addDate) {
this.addDate = addDate;
}`enter code here`
public ProductsWrapper(int id) {
this.setId(id);
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImageLink() {
return imageLink;
}
public void setImageLink(String imageLink) {
this.imageLink = imageLink;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
You can also try Jdbi-folder. It automatically takes care of dynamic bynding and also it provides one to many mapping relationship.
You can add Rosetta as a mapper for your JDBI result sets (it also works for bindings). Have a look at the advanced features to map column names with underscores to snake snake case java names.
Beware that there is no warning message if Rosetta is unable to map a value: any missed property in the target bean will just be empty. I found that my database returned column names in capital letters, therefore the LowerCaseWithUnderscoresStrategy in the example didn't work for me. I created a UpperCaseWithUnderscoresStrategy.
To skip writing getters and setters in ProductsWrapper have a look at Lombok's #Data annotation.

Unable to get Key and Value in picklist in richfaces

Hi I am new to richfaces picklist , My scenario is to load hashmap and by selecting the key value i need to load it in picklist. After getting the key i need to generate dynamic jasper report. My problem is while try to load the map value i end up with Typecast exception with the examples i came accross.
<rich:pickList id="pickList1" value="#{xxx.selectionBean.fieldNameList}" sourceCaption="Fields to be Selected for Report"
targetCaption="Selected Fields for Report" listWidth="165px" listHeight="100px" orderable="true" converter="pickListConvertor">
<f:selectItems value="#{xxx.commencementworkBean.commencementList}" var="s"
itemLabel="#{s.key}" itemValue="#{s.value}" />
<f:converter converterId="pickListConvertor" />
</rich:pickList>
SelectionBean
package xxx.xxx.xxx.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class SelectionBean implements Serializable{
/**
vs00324258
*/
private static final long serialVersionUID = -1597587007448113972L;
private String key;
private String value;
List<SelectionBean> fieldNameList = new ArrayList<SelectionBean>();
List<SelectionBean> dynamicList = new ArrayList<SelectionBean>();
List<Object> fieldList = new ArrayList<Object>();
public List<SelectionBean> getFieldNameList() {
return fieldNameList;
}
public void setFieldNameList(List<SelectionBean> fieldNameList) {
this.fieldNameList = fieldNameList;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<SelectionBean> getDynamicList() {
return dynamicList;
}
public void setDynamicList(List<SelectionBean> dynamicList) {
this.dynamicList = dynamicList;
}
public List<Object> getFieldList() {
return fieldList;
}
public void setFieldList(List<Object> fieldList) {
this.fieldList = fieldList;
}
}
PicklistConvertor
#FacesConverter(value = "pickListConvertor")
public class PickListConvertor implements Converter{
#Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if(submittedValue.trim().equals("")){
return null;
}else{
return submittedValue.toString();
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null || value.equals("")) {
return "";
} else {
return String.valueOf(((SelectionBean) value));
}
}
}
CommencementWorkBean
public class CommencementworkBean implements Serializable{
/**
vs00324258
*/
private static final long serialVersionUID = -5020735931910106047L;
private String agreementnum;
private String agreementtype;
private String authorityentering;
private String contractorname;
private String tendercalledbyoffice;
private Date dateofagreemtn;
private Date dateofcommofwork;
private Date dateofintendedcompl;
private Date tenderdate;
private Date duedateofmeterialworks;
private Date regdateofcontract;
private String detailsofsecurdeposit;
private String estamtsanctionno;
private String estimateamt;
private String isitlowest;
private String nameofwork;
private String orignalorsupplemental;
private String pricevariationapplicable;
private String reasonforlowest;
private String regnumberofvendor;
private String remarks;
private String taxes;
private String statusCode;
private String tenderauthority;
private String tenderpremium;
private String validityofsecurdeposit;
private String valueofcontract;
private String worldbankapproval;
private boolean searchCommTableEnabled = false;
private String fieldName;
private Map<String,Object> commencementList = new TreeMap<String, Object>();
private String headerName;
private String valueName;
private List<CommencementworkBean>searchCommencementBeanList = new ArrayList<CommencementworkBean>();
public String getAgreementnum() {
return agreementnum;
}
public void setAgreementnum(String agreementnum) {
this.agreementnum = agreementnum;
}
public String getAgreementtype() {
return agreementtype;
}
public void setAgreementtype(String agreementtype) {
this.agreementtype = agreementtype;
}
public String getAuthorityentering() {
return authorityentering;
}
public void setAuthorityentering(String authorityentering) {
this.authorityentering = authorityentering;
}
public String getContractorname() {
return contractorname;
}
public void setContractorname(String contractorname) {
this.contractorname = contractorname;
}
public String getTendercalledbyoffice() {
return tendercalledbyoffice;
}
public void setTendercalledbyoffice(String tendercalledbyoffice) {
this.tendercalledbyoffice = tendercalledbyoffice;
}
public Date getDateofagreemtn() {
return dateofagreemtn;
}
public void setDateofagreemtn(Date dateofagreemtn) {
this.dateofagreemtn = dateofagreemtn;
}
public Date getDateofcommofwork() {
return dateofcommofwork;
}
public void setDateofcommofwork(Date dateofcommofwork) {
this.dateofcommofwork = dateofcommofwork;
}
public Date getDateofintendedcompl() {
return dateofintendedcompl;
}
public void setDateofintendedcompl(Date dateofintendedcompl) {
this.dateofintendedcompl = dateofintendedcompl;
}
public Date getTenderdate() {
return tenderdate;
}
public void setTenderdate(Date tenderdate) {
this.tenderdate = tenderdate;
}
public Date getRegdateofcontract() {
return regdateofcontract;
}
public void setRegdateofcontract(Date regdateofcontract) {
this.regdateofcontract = regdateofcontract;
}
public String getDetailsofsecurdeposit() {
return detailsofsecurdeposit;
}
public void setDetailsofsecurdeposit(String detailsofsecurdeposit) {
this.detailsofsecurdeposit = detailsofsecurdeposit;
}
public String getEstamtsanctionno() {
return estamtsanctionno;
}
public void setEstamtsanctionno(String estamtsanctionno) {
this.estamtsanctionno = estamtsanctionno;
}
public String getEstimateamt() {
return estimateamt;
}
public void setEstimateamt(String estimateamt) {
this.estimateamt = estimateamt;
}
public String getIsitlowest() {
return isitlowest;
}
public void setIsitlowest(String isitlowest) {
this.isitlowest = isitlowest;
}
public String getNameofwork() {
return nameofwork;
}
public void setNameofwork(String nameofwork) {
this.nameofwork = nameofwork;
}
public String getOrignalorsupplemental() {
return orignalorsupplemental;
}
public void setOrignalorsupplemental(String orignalorsupplemental) {
this.orignalorsupplemental = orignalorsupplemental;
}
public String getPricevariationapplicable() {
return pricevariationapplicable;
}
public void setPricevariationapplicable(String pricevariationapplicable) {
this.pricevariationapplicable = pricevariationapplicable;
}
public String getReasonforlowest() {
return reasonforlowest;
}
public void setReasonforlowest(String reasonforlowest) {
this.reasonforlowest = reasonforlowest;
}
public String getRegnumberofvendor() {
return regnumberofvendor;
}
public void setRegnumberofvendor(String regnumberofvendor) {
this.regnumberofvendor = regnumberofvendor;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getTaxes() {
return taxes;
}
public void setTaxes(String taxes) {
this.taxes = taxes;
}
public String getTenderauthority() {
return tenderauthority;
}
public void setTenderauthority(String tenderauthority) {
this.tenderauthority = tenderauthority;
}
public String getTenderpremium() {
return tenderpremium;
}
public void setTenderpremium(String tenderpremium) {
this.tenderpremium = tenderpremium;
}
public String getValidityofsecurdeposit() {
return validityofsecurdeposit;
}
public void setValidityofsecurdeposit(String validityofsecurdeposit) {
this.validityofsecurdeposit = validityofsecurdeposit;
}
public String getValueofcontract() {
return valueofcontract;
}
public void setValueofcontract(String valueofcontract) {
this.valueofcontract = valueofcontract;
}
public String getWorldbankapproval() {
return worldbankapproval;
}
public void setWorldbankapproval(String worldbankapproval) {
this.worldbankapproval = worldbankapproval;
}
public Date getDuedateofmeterialworks() {
return duedateofmeterialworks;
}
public void setDuedateofmeterialworks(Date duedateofmeterialworks) {
this.duedateofmeterialworks = duedateofmeterialworks;
}
public boolean isSearchCommTableEnabled() {
return searchCommTableEnabled;
}
public void setSearchCommTableEnabled(boolean searchCommTableEnabled) {
this.searchCommTableEnabled = searchCommTableEnabled;
}
public List<CommencementworkBean> getSearchCommencementBeanList() {
return searchCommencementBeanList;
}
public void setSearchCommencementBeanList(
List<CommencementworkBean> searchCommencementBeanList) {
this.searchCommencementBeanList = searchCommencementBeanList;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getHeaderName() {
return headerName;
}
public void setHeaderName(String headerName) {
this.headerName = headerName;
}
public String getValueName() {
return valueName;
}
public void setValueName(String valueName) {
this.valueName = valueName;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public Map<String, Object> getCommencementList() {
return commencementList;
}
public void setCommencementList(Map<String, Object> commencementList) {
this.commencementList = commencementList;
}
}
What should i do to get key and value from the selection list.
Exception
java.lang.String cannot be cast to xxx.xxx.xxx.bean.SelectionBean
java.lang.ClassCastException: java.lang.String cannot be cast to xxx.xxx.xxx.bean.SelectionBean
at org.gov.tnwrd.utils.PickListConvertor.getAsString(PickListConvertor.java:26)
at org.richfaces.component.util.InputUtils.getConvertedStringValue(InputUtils.java:96)
at org.richfaces.component.util.InputUtils.getConvertedStringValue(InputUtils.java:88)
at org.richfaces.renderkit.SelectHelper.generateClientSelectItem(SelectHelper.java:80)
at org.richfaces.renderkit.SelectManyHelper.getClientSelectItems(SelectManyHelper.java:254)
at org.richfaces.renderkit.SelectManyRendererBase.getClientSelectItems(SelectManyRendererBase.java:60)
at org.richfaces.renderkit.html.PickListRenderer.encodeEnd(PickListRenderer.java:202)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at org.richfaces.renderkit.RendererBase.renderChildren(RendererBase.java:276)
at org.richfaces.renderkit.html.PanelRenderer.encodeEnd(PanelRenderer.java:181)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at org.richfaces.renderkit.RendererBase.renderChildren(RendererBase.java:276)
at org.richfaces.renderkit.html.AjaxOutputPanelRenderer.encodeChildren(AjaxOutputPanelRenderer.java:57)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1779)
at org.richfaces.context.ExtendedPartialViewContextImpl$RenderVisitCallback.visit(ExtendedPartialViewContextImpl.java:504)
at org.richfaces.context.BaseExtendedVisitContext.invokeVisitCallback(BaseExtendedVisitContext.java:321)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1612)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at org.richfaces.component.AbstractTogglePanel.visitTree(AbstractTogglePanel.java:743)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIForm.visitTree(UIForm.java:371)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at org.richfaces.context.ExtendedPartialViewContextImpl.processPartialRenderPhase(ExtendedPartialViewContextImpl.java:272)
at org.richfaces.context.ExtendedPartialViewContextImpl.processPartial(ExtendedPartialViewContextImpl.java:194)
at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:981)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1779)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:409)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:124)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)

p:selectOneMenu not calling setter on form submit

I'm kinda new to JSF and primefaces and I'm running into a very annoying problem.
I'm making a very basic application to learn a bit more about primefaces. I have a simple form that has several textual input fields, two datepickers and one dropdown (selectOneMenu).
Everything works all values are put in the backing bean when I submit the form, except for the value from the dropdown menu. The setter for that item is never called. And the application does not call the public void saveNewActivity(ActionEvent evt) method on the controller as defined on the commandbutton. When I however remove or comment out the dropdown menu in html it does call that method (but the field for the dropdown menu is obviously null).
I've been trying things for nearly two days, and still can't get this to work properly.
I have the following code (snippets):
My html/jsf code
<div id="newActivitycontent">
<h:form id="newActivityForm">
<h:messages id="messages"/>
<table>
<tr>
<td>Gebruiker:</td>
<td><p:selectOneMenu value="#{plannedActivityController.newActivity.organiser}}"
converter="#{userConverter}">
<f:selectItem itemLabel="Kies een gebruiker" itemValue=""/>
<f:selectItems value="#{plannedActivityController.users}" var="user"
itemLabel="#{user.firstname} #{user.lastname}" itemValue="#{user}"/>
</p:selectOneMenu></td>
</tr>
<tr>
<td>Titel:</td>
<td><p:inputText value="#{plannedActivityController.newActivity.name}"/></td>
</tr>
<tr>
<td>Beschrijving:</td>
<td><p:inputText value="#{plannedActivityController.newActivity.desctription}"/></td>
</tr>
<tr>
<td>Startdatum:</td>
<td><p:calendar value="#{plannedActivityController.newActivity.startDateDate}"/></td>
</tr>
<tr>
<td>Einddatum:</td>
<td><p:calendar value="#{plannedActivityController.newActivity.endDateDate}"/></td>
</tr>
</table>
<p:commandButton id="btnSaveNewActivity" value="Opslaan"
actionListener="#{plannedActivityController.saveNewActivity}"
update=":overviewForm:activityTable messages"/>
<p:commandButton id="btnCancelNewActivity" value="Annuleren"
actionListener="#{plannedActivityController.cancelNewActivity}" onclick="hideAddNewUI()"
update=":overviewForm:activityTable" type="reset" immediate="true"/>
</h:form>
</div>
The controller that is used by that code:
#Named
#SessionScoped
public class PlannedActivityController implements Serializable {
#Inject
private ApplicationModel appModel;
#Inject
private SessionModel sessionModel;
#Inject
private ActivityMapper activityMapper;
#Inject
private UserMapper userMapper;
private ActivityBean newActivity;
private ActivityBean selectedActivity;
private List<ActivityBean> activities;
private List<UserBean> users;
public PlannedActivityController() {
}
#PostConstruct
public void onCreated() {
convertActivities();
onNewActivity();
users = userMapper.mapToValueObjects(appModel.getUsers());
}
public void convertActivities() {
List<PlannedActivity> originalActivities = appModel.getActivities();
this.activities = activityMapper.mapToValueObjects(originalActivities);
}
public void onRowEditComplete(RowEditEvent event) {
System.out.println("row edited : " + event.getObject());
//TODO: save changes back to db!
}
public void onRowSelectionMade(SelectEvent event) {
System.out.println("row selected : " + event.getObject());
selectedActivity = (ActivityBean)event.getObject();
}
//Activity crud methods
public void onNewActivity() {
newActivity = new ActivityBean();
newActivity.setId(new Date().getTime());
}
public void saveNewActivity(ActionEvent evt) {
PlannedActivity newAct = activityMapper.mapToEntity(newActivity);
if(newAct != null) {
appModel.getActivities().add(newAct);
}
convertActivities();
}
public void cancelNewActivity() {
//TODO: cleanup.
}
public void deleteSelectedActivity() {
if(selectedActivity != null) {
activities.remove(selectedActivity);
appModel.setActivities(activityMapper.mapToEntities(activities));
convertActivities();
} else {
//TODO: show error or information dialog, that delete cannot be done when nothing has been selected!
}
}
//Getters & Setters
public ApplicationModel getAppModel() {
return appModel;
}
public void setAppModel(ApplicationModel appModel) {
this.appModel = appModel;
}
public SessionModel getSessionModel() {
return sessionModel;
}
public void setSessionModel(SessionModel sessionModel) {
this.sessionModel = sessionModel;
}
public ActivityMapper getActivityMapper() {
return activityMapper;
}
public void setActivityMapper(ActivityMapper activityMapper) {
this.activityMapper = activityMapper;
}
public UserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public ActivityBean getNewActivity() {
return newActivity;
}
public void setNewActivity(ActivityBean newActivity) {
this.newActivity = newActivity;
}
public ActivityBean getSelectedActivity() {
return selectedActivity;
}
public void setSelectedActivity(ActivityBean selectedActivity) {
this.selectedActivity = selectedActivity;
}
public List<ActivityBean> getActivities() {
return activities;
}
public void setActivities(List<ActivityBean> activities) {
this.activities = activities;
}
public List<UserBean> getUsers() {
return users;
}
public void setUsers(List<UserBean> users) {
this.users = users;
}
}
My activitybean:
public class ActivityBean implements Serializable {
private Long id = 0L;
private String name;
private String desctription;
private UserBean organiser;
private Calendar startDate;
private Calendar endDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesctription() {
return desctription;
}
public void setDesctription(String desctription) {
this.desctription = desctription;
}
public UserBean getOrganiser() {
return organiser;
}
public void setOrganiser(UserBean organiser) {
this.organiser = organiser;
}
public Calendar getStartDate() {
return startDate;
}
public void setStartDate(Calendar startDate) {
this.startDate = startDate;
}
public Date getStartDateDate() {
if(this.startDate == null) {
return null;
}
return this.endDate.getTime();
}
public void setStartDateDate(Date startDate) {
if(this.startDate == null) {
this.startDate = new GregorianCalendar();
}
this.startDate.setTime(startDate);
}
public String getStartDateString() {
if(this.startDate == null) {
return null;
}
return startDate.get(Calendar.DAY_OF_MONTH) + "/" + startDate.get(Calendar.MONTH) + "/" + startDate.get(Calendar.YEAR) + "";
}
public Calendar getEndDate() {
return endDate;
}
public void setEndDate(Calendar endDate) {
this.endDate = endDate;
}
public Date getEndDateDate() {
if(this.endDate == null) {
return null;
}
return endDate.getTime();
}
public void setEndDateDate(Date endDate) {
if(this.endDate == null) {
this.endDate = new GregorianCalendar();
}
this.endDate.setTime(endDate);
}
public String getEndDateString() {
if(this.endDate == null) {
return null;
}
return endDate.get(Calendar.DAY_OF_MONTH) + "/" + endDate.get(Calendar.MONTH) + "/" + endDate.get(Calendar.YEAR) + "";
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActivityBean that = (ActivityBean) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
return true;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
My userbean:
public class UserBean {
private Long id;
private String username;
private String firstname;
private String lastname;
private String email;
private String phone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserBean userBean = (UserBean) o;
if (id != null ? !id.equals(userBean.id) : userBean.id != null) return false;
return true;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
And the converter used by the selectOneMenu:
#Named
public class userConverter implements Converter{
#Inject
private PlannedActivityController activityController;
#Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
for (UserBean user : activityController.getUsers()) {
if(user.getId().toString().equals(s)) {
return user;
}
}
return null;
}
#Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
if(o instanceof UserBean) {
UserBean user = (UserBean)o;
return user.getId().toString();
}
return "";
}
}
The problem is here. Look closer. This is invalid EL syntax.
value="#{plannedActivityController.newActivity.organiser}}"
This should however have thrown a PropertyNotWritableException on submit something like this:
javax.el.PropertyNotWritableException: /test.xhtml #25,39 value="#{plannedActivityController.newActivity.organiser}}": Illegal Syntax for Set Operation
at com.sun.faces.facelets.el.TagValueExpression.setValue(TagValueExpression.java:136)
at javax.faces.component.UIInput.updateModel(UIInput.java:822)
at javax.faces.component.UIInput.processUpdates(UIInput.java:739)
at javax.faces.component.UIForm.processUpdates(UIForm.java:281)
at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1244)
at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1244)
at javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:1223)
at com.sun.faces.lifecycle.UpdateModelValuesPhase.execute(UpdateModelValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
This exception should have been logged to the server log. By default this will however not end up in an error page for the enduser because JSF/PrimeFaces have by default no form of feedback to enduser in case of exceptions which are thrown during ajax requests. You should however be able to see it in actual ajax response body in webbrowser's builtin HTTP traffic monitor.
The JSF utility library OmniFaces offers a FullAjaxExceptionHandler for the very problem of total absence of feedback on exceptions during ajax requests. You may find it useful. When I tried to recreate your problem, I was been presented a clear error page so that I don't need to dig in server log or HTTP traffic monitor for clues.

Resources