display jsf 2D table - jsf

I want to display a 2D array in my view .xhtml, which contains the database column as rows, but I can not get a 2D array
my BD Table
training | experience | motivation
NA | B | AT
I want to display a data table as follows
| evaluation | comment
-------------------------------------------
training | A | ...
-------------------------------------------------- -----
experience | B | ....

You'll have to write some Java code in a managed bean like this:
public class SomethingSomethingDTO {
private final String subject;
private final String evaluation;
private final String comment;
public SomethingSomethingDTO(final String subject,
final String evaluation, final String comment) {
this.subject = subject;
this.evaluation = evaluation;
this.comment = comment;
}
public String getSubject() {
return subject;
}
public String getEvaluation() {
return evaluation;
}
public String getComment() {
return comment;
}
}
#PostConstruct // or some other event or command button action
public void initializeSomething() {
somethings = new ArrayList<>();
somethings.add(new SomethingSomethingDTO("training", "A", "..."));
somethings.add(new SomethingSomethingDTO("experiance", "B", "..."));
}
private List<SomethingSomethingDTO> somethings;
public List<SomethingSomethingDTO> getSomethings() {
return somethings;
}

Related

Spring data Cassandra, Allow filtering

I have the following table
CREATE TABLE magazines.magazine_name (
frequency smallint,
magazine_id varchar,
magazine_name varchar,
PRIMARY KEY (magazine_id,magazine_name)
);
Should I use allow filter annotation to have the following repository method get executed
#Query("SELECT * from magazine_name where magazine_id = ?0")
MagazineName findMagazineCQlQuery(String id);
because I get the folowing execption :
org.springframework.data.cassandra.CassandraInvalidQueryException:Query;
CQL[com.datastax.oss.driver.internal.core.cql.DefaultSimpleStatement#c78c2039];
Cannot execute this query as it might involve data filtering and thus may have unpredictable performance.
If you want to execute this query despite the performance unpredictability, use ALLOW FILTERING;
nested exception is
com.datastax.oss.driver.api.core.servererrors.InvalidQueryException:
Cannot execute this query as it might involve data filtering
and thus may have unpredictable performance.
If you want to execute this query despite the performance unpredictability, use ALLOW FILTERING
By the way, I know that I can use query methods or even findById method, but actually I am just experimenting with cql quires and try to learn about it.
--update
The domain object
#Table(value = "magazine_name")
#Data
#Builder
public class MagazineName {
#PrimaryKeyColumn(name = "magazine_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
private String magazineId;
#PrimaryKeyColumn(name = "magazine_name", ordinal = 1, type = PrimaryKeyType.CLUSTERED)
private String name;
}
I defined the table exactly like yours and here is my repository. I can query without error.
1. My Repository
public interface IMagazineDao extends CrudRepository<Magazine, String> {
#Query("SELECT * from magazine_name where magazine_id = ?0")
Magazine findMagazineCQlQuery(String id);
}
2. Application
#SpringBootApplication
public class Application implements CommandLineRunner {
#Autowired
private IMagazineDao magazineDao;
#Override
public void run(String... args) throws Exception {
this.magazineDao.save(new Magazine("magazine1", "name", (short) 1));
this.magazineDao.findMagazineCQlQuery("magazine1");
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. Magazine class
#Table(value = "magazine_name")
public class Magazine {
#PrimaryKeyColumn(name = "magazine_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
private String magazineId;
#PrimaryKeyColumn(name = "magazine_name", ordinal = 1, type = PrimaryKeyType.CLUSTERED)
private String name;
#Column
private Short frequency;
public Magazine() {
}
public Magazine(String magazineId, String name, Short frequency) {
this.magazineId = magazineId;
this.name = name;
this.frequency = frequency;
}
public String getMagazineId() {
return magazineId;
}
public void setMagazineId(String magazineId) {
this.magazineId = magazineId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Short getFrequency() {
return frequency;
}
public void setFrequency(Short frequency) {
this.frequency = frequency;
}
}

passing a name and List of object in feature file in cucumber

I want to pass something like this in feature file in cucumber
Feature: Testing different requests on the XLR CD API
Scenario: Check if the student application can be accessed by users
Scenario Outline: Create a new student & verify if the student is added
When I create a new student by providing the information studentcollege <studentcollege> studentList <studentList>
Then I verify that the student with <student> is created
Examples:
| studentcollege | studentList |
| abcd | [{student_name": "student1","student_id": "1234"},{student_name": "student1","student_id": "1234"}] |
I have class as
Class Student{
String name;
String id;
}
and step definition file is
#When("^When I create a new student by providing the information studentCollege (.*) studentList (.*)$")
public void generatestudent(String studentOwner, List<Student> listOfstudent) {
// need to fetch values in here from whatever is given in feature file
}
how to pass such values in feature file Example. so that can be retrieved in step definition function.
This can be done by using the #Transform annotation in the stepdefinition. Also the student list string in the feature file looks like a Json string, so easiest to parse using Gson.
Relevant scenario
Scenario Outline: Create a new student & verify if the student is added
When I create a new student by providing the information studentcollege <studentcollege> studentList <studentList>
Examples:
| studentcollege | studentList |
| abcd | [{"student_name": "student111","student_id": "1234"},{"student_name": "student222","student_id": "5678"}] |
Stefdefinition class
#When("^I create a new student by providing the information studentcollege (.*?) studentList (.*?)$")
public void iCreateANewStudentByProvidingTheInformation(String arg1, #Transform(StudentListTransformer.class)List<Student> arg3) {
System.out.println(arg1);
System.out.println(arg3);
}
Transformer class
public class StudentListTransformer extends Transformer<List<Student>>{
#Override
public List<Student> transform(String value) {
//Sample json -- [{'name': 'student100','id': '1234'},{'name': 'student200','id': '5678'}]
return new Gson().fromJson(value, ArrayList.class);
}
}
Student dataobject-
public class Student {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return "Student [name=" + name + ", id=" + id + "]";
}
}

Overriding/implementing getRowKey() and getRowData() methods, when there is a composite primary key which combines multiple columns as a row key

I have a table in MySQL database. Unfortunately, there is a composite primary key which is needed for JAAS authentication/authorization in GlassFish Server.
mysql> desc group_table;
+---------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| user_group_id | varchar(176) | NO | PRI | NULL | |
| group_id | varchar(15) | NO | PRI | NULL | |
+---------------+--------------+------+-----+---------+-------+
2 rows in set (0.05 sec)
The table contains data in the following format.
mysql> select * from group_table;
+-------------------------+------------+
| user_group_id | group_id |
+-------------------------+------------+
| you123#gmail.com | ROLE_ADMIN |
| you123#gmail.com | ROLE_USER |
| you123#ymail.com | ROLE_USER |
| you123#hotmail.com | ROLE_USER |
| you123#yahoo.com | ROLE_USER |
+-------------------------+------------+
5 rows in set (0.00 sec)
A <p:dataTable> with rowKey works fine , when lazy is set to false.
<p:dataTable rowKey="#{row.groupTablePK.userGroupId} #{row.groupTablePK.groupId}">
...
</p:dataTable>
GroupTablePK is an #Embeddable class (JPA). The details about this class is not needed I presume.
When lazy is however, enabled on a <p:dataTable>, the getRowKey() and the getRowData() methods need to be implemented.
How can this be done, when there is a composite primary key which requires a combination of columns as a row key - a unique row identifier?
#Named
#ViewScoped
public class UserAuthorityManagedBean extends LazyDataModel<GroupTable> implements Serializable {
private static final long serialVersionUID = 1L;
#Override
public Object getRowKey(GroupTable groupTable) {
return groupTable != null ? groupTable.getGroupTablePK() : null;
}
#Override
public GroupTable getRowData(String rowKey) {
List<GroupTable> list = (List<GroupTable>) getWrappedData();
System.out.println("rowKey : " + rowKey);
}
#Override
public List<GroupTable> load(int first, int pageSize, List<SortMeta> multiSortMeta, Map<String, Object> filters) {
//... setRowCount(rowCount);
//... Return a List<GroupTable> from a business Service.
}
}
The above implementations are left incomplete.
When a row is selected in the <p:dataTable> with these implementations, the sout statement inside the getRowData() method displays the following.
Info: rowKey : entity.GroupTablePK[ userGroupId=you123#gmail.com
Info: rowKey : groupId=ROLE_USER ]
The getRowKey() method returns an instance of GroupTablePK but the getRowData() method only accepts a String type parameter. It is not an object representing the composite primary key (hereby GroupTablePK) so that it can be type-cast to an appropriate object type (GroupTablePK) and based on which an instance of GroupTable may be obtained from the given List<GroupTable> and get the getRowData() method to return that instance of GroupTable.
How to proceed further?
The question is purely based on the immediate previous question :
java.lang.UnsupportedOperationException: getRowData(String rowKey) must be implemented when basic rowKey algorithm is not used
EDIT:
I have hashcode() and equals() implementations in addition to toString() in GroupTablePK. The toString() method in GroupTablePK returns return "entity.GroupTablePK[ userGroupId=" + userGroupId + ", groupId=" + groupId + " ]"; but the getRowData() method is invoked twice, when a row in a <p:dataTable> is selected. It returns the string representation of GroupTablePK in two parts in two subsequent calls. In the first call, it returns entity.GroupTablePK[ userGroupId=aaa and then in the second call, it returns groupId=ROLE_USER ].
It should instead return entity.GroupTablePK[ userGroupId=aaa, groupId=ROLE_USER ] at once in a single call.
This kind of comparison groupTable.getGroupTablePK().toString().equals(rowKey) is therefore not possible which I was thinking about prior to this post. Such as,
#Override
public GroupTable getRowData(String rowKey) {
List<GroupTable> list = (List<GroupTable>) getWrappedData();
for (GroupTable groupTable : list) {
if (groupTable.getGroupTablePK().toString().equals(rowKey)) {
return groupTable;
}
}
return null;
}
EDIT 2:
The following is the shortest possible example removing the JPA noise to reproduce the problem.
Attempted alternatively on,
PrimeFaces 3.5
PrimeFaces 4.0
PrimeFaces 5.0
PrimeFaces 5.1
PrimeFaces 5.2
The behaviour remains stationary on all of these versions of PrimeFaces.
The managed bean:
#Named
#ViewScoped
public class CompositeRowKeyManagedBean extends LazyDataModel<GroupTable> implements Serializable {
private List<GroupTable> selectedValues; // Getter & setter.
private static final long serialVersionUID = 1L;
public CompositeRowKeyManagedBean() {}
private List<GroupTable> init() {
List<GroupTable> list = new ArrayList<GroupTable>();
GroupTablePK groupTablePK = new GroupTablePK("aaa", "ROLE_ADMIN");
GroupTable groupTable = new GroupTable(groupTablePK);
list.add(groupTable);
groupTablePK = new GroupTablePK("bbb", "ROLE_USER");
groupTable = new GroupTable(groupTablePK);
list.add(groupTable);
groupTablePK = new GroupTablePK("ccc", "ROLE_USER");
groupTable = new GroupTable(groupTablePK);
list.add(groupTable);
groupTablePK = new GroupTablePK("ddd", "ROLE_USER");
groupTable = new GroupTable(groupTablePK);
list.add(groupTable);
groupTablePK = new GroupTablePK("eee", "ROLE_USER");
groupTable = new GroupTable(groupTablePK);
list.add(groupTable);
return list;
}
#Override
public List<GroupTable> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
List<GroupTable> list = init();
setRowCount(list.size());
return list;
}
#Override
public Object getRowKey(GroupTable groupTable) {
return groupTable != null ? groupTable.getGroupTablePK() : null;
}
#Override
public GroupTable getRowData(String rowKey) {
List<GroupTable> list = (List<GroupTable>) getWrappedData();
System.out.println("rowKey : " + rowKey);
for (GroupTable groupTable : list) {
if (groupTable.getGroupTablePK().toString().equals(rowKey)) {
return groupTable;
}
}
return null;
}
public void onRowEdit(RowEditEvent event) {
GroupTablePK groupTablePK = ((GroupTable) event.getObject()).getGroupTablePK();
System.out.println("grouoId : " + groupTablePK.getGroupId() + " : userGroupId : " + groupTablePK.getUserGroupId());
}
}
The data table :
<p:dataTable var="row"
value="#{compositeRowKeyManagedBean}"
lazy="true"
editable="true"
selection="#{compositeRowKeyManagedBean.selectedValues}"
rows="50">
<p:column selectionMode="multiple"></p:column>
<p:ajax event="rowEdit" listener="#{compositeRowKeyManagedBean.onRowEdit}"/>
<p:column headerText="GroupId">
<h:outputText value="#{row.groupTablePK.userGroupId}"/>
</p:column>
<p:column headerText="UserGroupId">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{row.groupTablePK.groupId}"/>
</f:facet>
<f:facet name="input">
<p:inputText value="#{row.groupTablePK.groupId}"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Edit">
<p:rowEditor/>
</p:column>
</p:dataTable>
When a row is attempted to edit, the onRowEdit() method is invoked. The getRowData() is invoked twice and produces a split of the row key in two subsequent calls as said earlier.
These are two domain classes GroupTable and GroupTablePK.
public class GroupTable implements Serializable {
private static final long serialVersionUID = 1L;
protected GroupTablePK groupTablePK;
public GroupTable() {}
public GroupTable(GroupTablePK groupTablePK) {
this.groupTablePK = groupTablePK;
}
public GroupTable(String userGroupId, String groupId) {
this.groupTablePK = new GroupTablePK(userGroupId, groupId);
}
public GroupTablePK getGroupTablePK() {
return groupTablePK;
}
public void setGroupTablePK(GroupTablePK groupTablePK) {
this.groupTablePK = groupTablePK;
}
#Override
public int hashCode() {
int hash = 0;
hash += (groupTablePK != null ? groupTablePK.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof GroupTable)) {
return false;
}
GroupTable other = (GroupTable) object;
if ((this.groupTablePK == null && other.groupTablePK != null) || (this.groupTablePK != null && !this.groupTablePK.equals(other.groupTablePK))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.GroupTable[ groupTablePK=" + groupTablePK + " ]";
}
}
public class GroupTablePK implements Serializable {
private String userGroupId;
private String groupId;
public GroupTablePK() {}
public GroupTablePK(String userGroupId, String groupId) {
this.userGroupId = userGroupId;
this.groupId = groupId;
}
public String getUserGroupId() {
return userGroupId;
}
public void setUserGroupId(String userGroupId) {
this.userGroupId = userGroupId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (userGroupId != null ? userGroupId.hashCode() : 0);
hash += (groupId != null ? groupId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof GroupTablePK)) {
return false;
}
GroupTablePK other = (GroupTablePK) object;
if ((this.userGroupId == null && other.userGroupId != null) || (this.userGroupId != null && !this.userGroupId.equals(other.userGroupId))) {
return false;
}
if ((this.groupId == null && other.groupId != null) || (this.groupId != null && !this.groupId.equals(other.groupId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.GroupTablePK[ userGroupId=" + userGroupId + ", groupId=" + groupId + " ]";
}
}
I ran your MCVE (kudos to that!) and reproduced it. The rowkey appears to be interpreted as a commaseparated string in the client side to cover the case when multiple selection is needed. This will fail if the string representation of a single rowkey contains a comma, as in your case. The rowkey argument you got in getRowData() is clear evidence of it: they are the results when the original value is split on comma.
So, to solve this problem, you need to make sure that the getRowKey().toString() doesn't contain a comma anywhere. Better use a different separator character. E.g. an underscore.
#Override
public Object getRowKey(GroupTable groupTable) {
GroupTablePK pk = groupTable != null ? groupTable.getGroupTablePK() : null;
return pk != null ? pk.getUserGroupId() + "_" + pk.getGroupId() : null;
}
From reading your question I am guessing that the getRowKey() method must return something that is uniquely identifiable to a single row. It is understandable that the underlying JPA entity that represents your row has a composite key object which is fine. The problem I think that is for a Java object to use anything as a key in a Map type collection, the key object must overload and define a proper implementation for the equals and hashCode methods.
I suspect that Primefaces probably is using a Map of some kind to retrieve values based on a key. The String type is usually a good candidate for unique key of an object because Strings are immutable and have proper implementations of equals and hashCode. They make a good candidate for this so if you must pass a String to getRowData then you can always provide a method on that object that returns a unique string for that object. This might be for instance a base 64 representation of the hashCode implementation you provide for your row data object.
If String is not a required parameter then simply implement equals and hashCode for composite key object and use that directly as your key.

generate Primefaces MenuModel from database

i want to ask how to make generate menumodel from database using recursive function.
i already make this class but it's not working. please help me,i already find and trying for a week .thanks
public class MenuDAOImpl extends ManagerBase<MenuMaster> implements MenuDAO {
private List<MenuMaster> list;
private List<MenuData> datas;
#Override
public MenuModel getMenu() {
MenuModel model = new DefaultMenuModel();
String[] orders = new String[]{"id"};
try {
list = getBySQLQuery("PARENT_MENU_ID=0", orders, 1000);
for (MenuMaster menuMaster : list) {
menuChild(menuMaster);
}
} catch (Exception e) {
}
return model;
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private List<MenuData> menuChild(MenuMaster master) {
List<MenuData> listChild = new ArrayList<MenuData>();
String[] orders = new String[]{"id"};
try {
MenuData data = new MenuData();
data.mm = master;
data.mms = getBySQLQuery("PARENT_MENU_ID=" + master.getParentMenuId(), orders, 1000);
listChild.add(data);
} catch (Exception e) {
}
return listChild;
}
public class MenuData {
private MenuMaster mm;
private List<MenuMaster> mms;
public MenuData() {
}
public MenuMaster getMm() {
return mm;
}
public void setMm(MenuMaster mm) {
this.mm = mm;
}
public List<MenuMaster> getMms() {
return mms;
}
public void setMms(List<MenuMaster> mms) {
this.mms = mms;
}
}
}
this is my database table (sorry i can't upload images)
ID | MENU_NAME | DISPLAY_NAME | URL |PARENT_MENU_ID |
1 | employee | Employee | /employee.xhtml | 0 |
2 | employeemenu| Employee | /employee.xhtml | 1 |
3 | utils | Utility | | 0 |
7 | asdf | asdf | | 6 |
6 | utilsmenu | test | | 3 |
5 | utilsdata | Admin Config | asdf | 3 |
4 | menu | Menu Editor | /utility/menu.xhtml | 3 |
Here's some code I had lying around, I create the menumodel by appending submenus and menuitems to his getChildren() property
private MenuModel model;
public MenuModel getModel() {
if(model != null) return model;
model = new DefaultMenuModel();
addDynamicMenus();
return model;
}
private void addDynamicMenus(){
if(modules == null){
modules = service.getModulesByUserLogin(loginBean.getUsername());
}
Submenu currfather = null;
for(SpFeModuleForUser s : modules){
if(currfather == null || (!currfather.getId().equals("menu_" + s.getModuleID()))){
currfather = new Submenu();
currfather.setLabel(Modules.getSingleton().getString(s.getModuleName()));
currfather.setId("menu_"+s.getModuleID());
model.addSubmenu(currfather);
}
MenuItem mi = new MenuItem();
mi.setValue(Modules.getSingleton().getString(s.getNAME()));
mi.setId("_" + s.getKey());
mi.setTarget("_self");
mi.setTitle(Modules.getSingleton().getString(s.getNAME() + "_Description"));
mi.setAjax(false);
mi.setUrl(url);
// Add parameters
UIParameter param = new UIParameter();
param.setName("moduleid");
param.setValue(s.getKey());
mi.getChildren().add(param);
mi.setProcess("#all");
currfather.getChildren().add(mi);
}
}

Array List in C# without a loop

I like to know how to initialise the array without the loops like for, foreach or any LINQ.
From the following code, need to find under 2m length cars within .Netframework using console application.
{
ArrayList = CarType new ArrayList();
CarType.Add(new CarList("Ford"));
((CarList)CarType[0]).Cars.Add(new Car("Focus", 2));
((CarList)CarType[0]).Cars.Add(new Car("Fiesta", 1));
CarType.Add(new CarList("Peugeout"));
((CarList)CarType[1]).Cars.Add(new Car("206", 1));
((CarList)CarType[1]).Cars.Add(new Car("407", 2));
RemoveLargeCars(CarType);
}
public static ArrayList RemoveLargeCars (ArrayList CarType)
{
//Array List should be here
return CarType;
}
It has got two classes as follows.
class Car
{
public string name;
public float length;
public Car(string newName, float newLength)
{
this.name = newName;
this.length = newLength;
}
}
Class CarList
{
public string CarType;
public ArrayList Pipes;
public CarList(string newCarType)
{
carType = newCarType;
Cars = new ArrayList();
}
}
Can you please let me know how to solve this.
Thanks in advance.
Use the static Adapter method on ArrayList
CarType = ArrayList.Adapter(CarList);
But that probably uses a loop internally, you can't get away from them, but at least this hides them.
Well, first of all you should use the generic list type List<T> instead of ArrayList, that will make the code simpler. (And best practive recommends properties rather than public fields):
class Car {
public string Name { get; set; }
public float Length { get; set; }
public Car(string newName, float newLength) {
Name = newName;
Length = newLength;
}
}
class CarList {
public string CarType { get; set; }
public List<Car> Cars { get; set; }
public CarList(string newCarType, List<Car> newCars) {
CarType = newCarType;
Cars = newCars;
}
public CarList(string newCarType) : this(newCarType, new List<Car>()) {}
}
Now use a List<CarList>:
List<CarList> CarType = new List<CarList>();
CarList ford = new CarList("Ford");
CarType.Add(ford);
ford.Cars.Add(new Car("Focus", 2));
ford.Cars.Add(new Car("Fiesta", 1));
CarList peugeot = new CarList("Peugeout");
CarType.Add(peugeot);
peugeot.Cars.Add(new Car("206", 1));
peugeot.Cars.Add(new Car("407", 2));
List<CarList> smallCars = RemoveLargeCars(CarType);
You can use extension methods to easily filter out cars based on a condition:
public static List<CarList> RemoveLargeCars(List<CarList> CarType) {
return CarType.Select(
t => new CarList(t.CarType, t.Cars.Where(c => c.Length < 2f).ToList()
) .ToList();
}
Note that the method doesn't change the original list, but creates a new list.

Resources