generate Primefaces MenuModel from database - jsf

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);
}
}

Related

display jsf 2D table

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;
}

Scout Eclipse AbstractGroupBox auto size

I would like to have AbstractGroupBox that will grep all place that is available.
For Example :
if my form is like this:
-----------------------------------------------------------
| ------------ ------------ ------------ |
| |some field| |some field| |some field| |
| ------------ ------------ ------------ |
| |
| ------------------------------------------------------ |
| | AbstractGroupBox | |
| ------------------------------------------------------ |
| |
| |
| |
| |
| |
| |
| |
| |
-----------------------------------------------------------
Now I would like to have AbstractGroupBox to take all height of the form data.
I know I need to add
#Override
protected boolean getConfiguredGridUseUiHeight() {
return false;
}
because it has no content. By default Fill Vertical is set to true.
By what I can understand I should set
#Override
protected double getConfiguredGridWeightY() {
return 1.0;
}
so grid cell will grep more space as Scout helps says.
But with all this set I still have small AbstractGroupBox.
How to set AbstractGroupBox that will grep all space available?
EDIT :
The layout is :
and my code is :
#Order(60.0)
public class ViewBox extends AbstractGroupBox {
#Override
protected String getConfiguredLabel() {
return TEXTS.get("ViewBox");
}
#Override
protected String getConfiguredBackgroundColor() {
return "364BFF";
}
#Override
protected int getConfiguredGridW() {
return 4;
}
#Override
protected double getConfiguredGridWeightY() {
return 1.0;
}
}
I am not sure to follow... This code works for me:
#Order(5000.0)
public class MyGroupBoxField extends AbstractGroupBox {
#Override
protected int getConfiguredGridW() {
return 2;
}
#Override
protected double getConfiguredGridWeightY() {
return 1.0;
}
}
Maybe I did not understood your use case, but this is what I get:

Populate table with nested Collections

I´m looking for a solution for my problem.
I have a table that needs to be like this.
--------------------------------------------------------------|
| | Title 3 |
Title 1 |Title 2|---------------------------------------------|
| | SubTitle 1 |SubTitle 2|SubTitle 3|SubTitle 4|
--------------------------------------------------------------|
| | | | | |
Val A1 | ValB1 | ValC1 | ValC1 | ValC1 | ValC1 |
| | | | | |
|-------|------------|----------|----------|----------|
| | | | | |
| ValB2 | ValC2 | ValC2 | ValC2 | ValC2 |
| | | | | |
--------------------------------------------------------------|
| | | | | |
| | | | | |
Val A2 | ValB3 | ValC3 | ValC3 | ValC3 | ValC3 |
| | | | | |
| | | | | |
----------------------------------------------------------------
My goal it´s to make a table appear like I did above.
I´m using JSF and Primefaces 4.0.
I have this struture of class.
Class Master {
private List<ClassA> classesA
// getter and setter
}
Class A {
private List<ClassB> classesB
// getter and setter and fields
}
Class B {
private List<ClassC> classesC
// getter and setter and fields
}
Class C {
// getter and setter and fields
}
So I tried to make with two datatables or using ui:repeat, but I don´t know what´s going to be the best choose. And the titles the owns like this.
Class A have title 1, Class B have title 2 and Class C have title 3 and subtitle 1,2,3 and 4.
Or use binding.
To be more easier to understand I put a picture about how I need to create the table.
Can someone help me?
Thanks
If you are sure that the object structure won't change in future then simple solution is to go for ui:repeat with nested tables, rowspan and colspan. But if the object structure often changes and you need to do it more than one time then go for custom component.If you need olap features then i suggest you to go for pivot4j or something similar.
update: see the xhtml below it creates the body of the table.
<table border="4" cellspacing="4" cellpadding="10">
<tr>
<th rowspan="2">A</th>
<th rowspan="2">B</th>
<th colspan="4">C</th>
</tr>
<tr>
<th>p1</th>
<th>p2</th>
<th>p3</th>
<th>p4</th>
</tr>
<ui:repeat var="classa" value="#{master.classesA}" varStatus="astat">
<ui:repeat var="classb" value="#{classa.classesB}" varStatus="bstat">
<ui:repeat value="#{classb.classesC}" var="classc" varStatus="cstat">
<tr>
<h:panelGroup rendered="#{bstat.index eq 0 and cstat.index eq 0}">
<td rowspan="#{classa.colSpan}" >
<h:outputText value="#{classa.property}" />
</td>
</h:panelGroup>
<h:panelGroup rendered="#{cstat.index eq 0}">
<td rowspan="#{classb.classesC.size()}">
<h:outputText value="#{classb.property}" />
</td>
</h:panelGroup>
<td>
<h:outputText value="#{classc.prop1}" />
</td>
<td>
<h:outputText value="#{classc.prop2}" />
</td>
<td>
<h:outputText value="#{classc.prop3}" />
</td>
<td>
<h:outputText value="#{classc.prop4}" />
</td>
</tr>
</ui:repeat>
</ui:repeat>
</ui:repeat>
</table>
and classes should look like this
public class A {
private List<B> classesB;
private String property;
public List<B> getClassesB() {
return classesB;
}
public void setClassesB(List<B> classesB) {
this.classesB = classesB;
}
public A(String pro) {
classesB= new ArrayList<B>();
property=pro;
}
public void addClassB(B b){
classesB.add(b);
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public int getColSpan(){
int size=0;
for(B b : classesB){
size+=b.getClassesC().size();
}
return size;
}
}
public class B {
private List<C> classesC;
private String property;
public B(String pro) {
this.classesC = new ArrayList<C>();
this.property=pro;
}
public List<C> getClassesC() {
return classesC;
}
public void setClassesC(List<C> classesC) {
this.classesC = classesC;
}
public void addClassC(C c){
classesC.add(c);
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
public class C {
private String prop1;
private String prop2;
private String prop3;
private String prop4;
public C(String prop1, String prop2, String prop3, String prop4) {
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
this.prop4 = prop4;
}
public void setProp1(String prop1) {
this.prop1 = prop1;
}
public void setProp2(String prop2) {
this.prop2 = prop2;
}
public void setProp3(String prop3) {
this.prop3 = prop3;
}
public void setProp4(String prop4) {
this.prop4 = prop4;
}
public String getProp1() {
return prop1;
}
public String getProp2() {
return prop2;
}
public String getProp3() {
return prop3;
}
public String getProp4() {
return prop4;
}
}
Test data in Master class.
private List<A> classesA;
#PostConstruct
public void init() {
classesA = new ArrayList<A>();
A a1 = new A("a1");
A a2 = new A("a2");
classesA.add(a1);
classesA.add(a2);
B b11 = new B("b11");
B b12 = new B("b12");
B b21 = new B("b21");
a1.addClassB(b11);
a1.addClassB(b12);
a2.addClassB(b21);
C c111 = new C("a", "b", "c", "d");
C c112 = new C("d", "e", "f", "g");
C c121 = new C("g", "h", "i", "j");
C c211 = new C("k", "l", "m", "n");
C c212 = new C("o", "p", null, null);
b11.addClassC(c111);
b11.addClassC(c112);
b12.addClassC(c121);
b21.addClassC(c211);
b21.addClassC(c212);
}
public List<A> getClassesA() {
return classesA;
}
public void setClassesA(List<A> classesA) {
this.classesA = classesA;
}
You can use dataTable with subTable (and you can add columns in row if needed).

ServiceStack OrmLite How can I achieve automatic setting of foreign key/related properties?

I have created the following example to test Foreign Keys and up to this point, it works well. What I would like to be able to do, is use this framework that I built to set the property of the relationship and have it Save the child object when the Parent is saved and automatically set the PrimaryKey and Foreign Key.
The DataManager class exposes the Connection
public class DataManager
{
DataManager()
{
OrmLiteConfig.DialectProvider = SqliteDialect.Provider;
ConnectionString = SqliteFileDb;
updateTables();
}
private void updateTables()
{
using (var dbConn = OpenDbConnection())
{
dbConn.DropAndCreateTable<Person>();
dbConn.DropAndCreateTable<PhoneNumber>();
}
}
public static string SqliteFileDb = "~/App_Data/db.sqlite".MapAbsolutePath();
private static DataManager manager;
public static DataManager Manager {
get
{
if (manager == null)
manager = new DataManager();
return manager;
}
}
public IDbConnection InMemoryDbConnection { get; set; }
public IDbConnection OpenDbConnection(string connString = null)
{
connString = ConnectionString;
return connString.OpenDbConnection();
}
protected virtual string ConnectionString { get; set; }
protected virtual string GetFileConnectionString()
{
var connectionString = SqliteFileDb;
return connectionString;
}
}
These are my POCO's with the BaseClass used to Achieve my results:
public class Person : LiteBase
{
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
private List<PhoneNumber> numbers;
public List<PhoneNumber> PhoneNumbers {
get
{
if (numbers == null)
numbers = GetList<PhoneNumber>(p => p.Person == Id);
return numbers;
}
}
}
public class PhoneNumber
{
public string Number { get; set; }
public string Description { get; set; }
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
[References(typeof (Person))]
public int Person { get; set; }
public void AddPerson(Person person)
{
Person = person.Id;
}
}
public class LiteBase:INotifyPropertyChanged
{
public List<T> GetList<T>(Expression< Func<T,bool>> thefunction) where T : new()
{
var objects = new List<T>();
using (var conn = Data.DataManager.Manager.OpenDbConnection())
{
objects = conn.Where<T>(thefunction);
}
return objects;
}
public T GetItem<T>(Expression<Func<T, bool>> thefunction) where T : new()
{
T obj = new T();
using (var conn = Data.DataManager.Manager.OpenDbConnection())
{
obj = conn.Where<T>(thefunction).FirstOrDefault<T>();
}
return obj;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Simple Class to Create Person and PhoneNumber objects
public class PersonManager
{
public void CreatePerson(string name, string surname, string number)
{
using (var conn = DataManager.Manager.OpenDbConnection())
{
var pnum = new PhoneNumber { Number = number };
var person = new Person
{
Name=name,
Surname = surname,
};
conn.Save<Person>(person);
var id = conn.GetLastInsertId();
person.Id = (int)id;
pnum.AddPerson(person);
conn.Save<PhoneNumber>(pnum);
}
}
public List<Person> GetPeople()
{
List<Person> people;
using (var conn = DataManager.Manager.OpenDbConnection())
{
people = conn.Select<Person>();
}
return people;
}
public List<PhoneNumber> GetNumbers()
{
List<PhoneNumber> numbers;
using (var conn = DataManager.Manager.OpenDbConnection())
{
numbers = conn.Select<PhoneNumber>();
}
return numbers;
}
}
And here is the usage:
var manager = new PersonManager();
manager.CreatePerson("John", "Doe", "12345679");
manager.CreatePerson("Jack", "Smith", "12345679");
manager.CreatePerson("Peter", "Jones", "12345679");
manager.CreatePerson("Dan", "Hardy", "12345679");
var people = manager.GetPeople();
var numbers = manager.GetNumbers();
for (int i = 0; i < people.Count; i++)
{
Console.WriteLine("{0} {1} {2}",
people[i].Name,people[i].Surname,people[i].Id);
}
for (int n = 0; n < numbers.Count; n++)
{
Console.WriteLine("PN: {0} {1}",
numbers[n].Number,numbers[n].Person);
}
for (int p = 0; p < people.Count; p++)
{
var person = people[p];
Console.WriteLine("{0}: {1} {2} {3}",
person.Id,person.Name,person.Surname,person.GetItem<PhoneNumber>(x=>x.Person==person.Id).Number);
}
The output is as I expected :
John Doe 1
Jack Smith 2
Peter Jones 3
Dan Hardy 4
PN: 12345679 1
PN: 12345679 2
PN: 12345679 3
PN: 12345679 4
1: John Doe 12345679
2: Jack Smith 12345679
3: Peter Jones 12345679
4: Dan Hardy 12345679
What I really would like to be able to do is the following:
var john = new Person
{
Name = "John",
Surname = "Smith",
PhoneNumber = new PhoneNumber { Number = "123456789" }
};
conn.Save<Person>(john);
var number = john.PhoneNumber.Number
Is this at all possible?
By default OrmLite v3 blobs all complex types properties in a string field and you need to explicitly set all references.
In the next major v4 release (ETA late Nov 2013), OrmLite adds some support for external references with the [Reference] attribute, which lets you tell OrmLite these properties should be stored in an external table and not blobbed, e.g:
public class Customer
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
[Reference]
public CustomerAddress PrimaryAddress { get; set; }
[Reference]
public List<Order> Orders { get; set; }
}
This will allow you to call db.SaveReferences() to save the reference properties, e.g:
var customer = new Customer
{
Name = "Customer 1",
PrimaryAddress = new CustomerAddress {
AddressLine1 = "1 Humpty Street",
City = "Humpty Doo",
State = "Northern Territory",
Country = "Australia"
},
Orders = new[] {
new Order { LineItem = "Line 1", Qty = 1, Cost = 1.99m },
new Order { LineItem = "Line 2", Qty = 2, Cost = 2.99m },
}.ToList(),
};
Assert.That(customer.Id, Is.EqualTo(0)); //Id is not saved yet
//Inserts customer, populates auto-incrementing customer.Id
//Specify `references:true` to populate the ForeignKey ids and
//save the related rows as well, e.g:
db.Save(customer, references:true);
Assert.That(customer.Id, Is.GreaterThan(0));
Assert.That(customer.PrimaryAddress.CustomerId, Is.EqualTo(customer.Id));
Assert.That(customer.Orders.All(x => x.CustomerId == customer.Id));
Saving References manually
For more fine-grained control you can also choose which references you want to save, e.g:
db.Save(customer); //Doesn't save related rows
//1:1 PrimaryAddress Reference not saved yet
Assert.That(customer.PrimaryAddress.CustomerId, Is.EqualTo(0));
//1:1 PrimaryAddress Reference saved and ForeignKey id populated
db.SaveReferences(customer, customer.PrimaryAddress);
//1:Many Orders References saved and ForeignKey ids populated
db.SaveReferences(customer, customer.Orders);
Loading all related rows with the entity
You can then load the master row and all its references with db.LoadSingleById, e.g:
var dbCustomer = db.LoadSingleById<Customer>(customer.Id);
dbCustomer.PrintDump();
Assert.That(dbCustomer.PrimaryAddress, Is.Not.Null);
Assert.That(dbCustomer.Orders.Count, Is.EqualTo(2));

How do insert a record into a from a string using split function in MVC4?

Hi all i have a string like this which i am passing an ajax function to my controller action method
Brand1~1001=>undefined_undefined|
Category1~2001=>1001_Brand1|
Category2~2002=>1001_Brand1|
Product3~3003=>2002_Category2|
Product4~3004=>Product3~3003|
Product5~3005=>2002_Category2|
Product6~3006=>2002_Category2|
and i have an Menus table in db i had added that as an entity model to my project
Menus
[MenuID],[MenuName],[ParentID]
and i have model like this
public class MenuItems
{
public List<MenuItems> GetALL { get; set; }
public int MenuId { get; set; }
public string MenuName { get; set; }
public int parentId { get; set; }
}
now i want to split the string i have and insert into the above table like this
[MenuID],[MenuName],[ParentID]
1001 ,Brand1 ,null
2001 ,category1 ,1001
2002 ,category2 ,1001
3003 ,product3 ,2002
3004 ,product4 ,3003
3005 ,product5 ,2002
3006 ,product6 ,2002
in the above string Brand1~1001=>undefined_undefined| here Brand1~1001 is the parentmenu and 1001 is the id of the menu
Category1~2001=>1001_Brand1| and here Category1~2001 is the sub menu of the 1001_Brand1 i think you all got waht i amtrying to do can any one help me here please
what i amtrying
public ActionResult MenuDrag()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MenuDrag(string menustring)
{
if (!String.IsNullOrEmpty(menustring))
{
string[] menus = menustring.Split('|');
foreach (var m in menus)
{
string[] list = m.Split('>');
//stuck from here confused what to do next and how do i insert the data in my accordingly
}
}
return View();
}
You are almost there just replace your post method with this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MenuDrag(string menustring)
{
MenuItems items = new MenuItems();
//check the string for empty
if (!String.IsNullOrEmpty(menustring))
{
string[] menus = menustring.Split('|');
foreach (var m in menus)
{
if (m != "")
{
string[] list = m.Split('>');
string[] menu = list[0].Split('~');
string[] parents = list[1].Split('~');
items.MenuItemID = Convert.ToInt16(menu[1]);
items.MenuName = menu[0].ToString();
if (parents[0] == "undefined")
{
items.ParentID = 0;
db.MenuItems.Add(items);
db.SaveChanges();
}
else
{
int parentid=Convert.ToInt16(parents[0]);
var menuid = from me in db.MenusMains where me.MenuItemID == parentid select new { MenuID = me.MenuID };
foreach (var id in menuid)
{
items.ParentID = Convert.ToInt16(id.MenuID);
}
db.MenuItems.Add(items);
db.SaveChanges();
}
}
}
}
return View();
}
}
i had used
if (m != "")
{
}
since u may get an index out of bound exception there since when in your string at this
string[] menus = menustring.Split('|');
u will get an empty ('|') you have to handle this
hope this works

Resources