Spring mvc category tree - java

I have category tree.My category has n number subcategories.How do list recursion category on jsp?
List<Category> categories = categoryService.findAll();
modelMap.put("categories",categories)

Using JSTL, try something like this:
Simple List of Items
<c:forEach var="category" items="${categories}">
${category.id} -> ${category.name}
</c:forEach>
Nested List of Items
If you have nested categories, try something like the following custom tag.
public class CategoryDisplayTag extends TagSupport
{
public int doStartTag() throws JspException
{
Category rootCategory = new Category();
printEachCategory(rootCategory);
return SKIP_BODY;
}
private void printEachCategory(Category category)
{
JspWriter out = pageContext.getOut();
try
{
out.write("Category: " + category.getName());
for (Category c : category.getCategories())
{
out.write("Sub-category: " + c.getName());
printEachCategory(c);
}
}
catch (IOException e1)
{
throw new RuntimeException(e1);
}
}
}

Related

Java for loop executed twice

I am experiencing some troubles when executing a for loop. The loop is called twice. Here is the code that does the work:
import java.util.ArrayList;
import java.util.List;
public class PoolItemMapper {
public List<Item> mapJsonObjectsToItems(JsonResponse jsonResponse) {
int count = 0;
List<Item> itemsList = new ArrayList<>();
List<Item> js = jsonResponse.getItems();
for (Item item : jsonResponse.getItems()) {
itemsList.add(addNormalItemProperties(item, new Item()));
count++;
}
System.out.println("Call count: " + count);
return itemsList;
}
private Item addNormalItemProperties(Item oldItem, Item newItem) {
if(oldItem.getMembersReference().getItems().size() <= 0) {
return oldItem;
} else if (oldItem.getMembersReference().getItems().size() > 0) {
for (SubItem subItem: oldItem.getMembersReference().getItems()) {
oldItem.getSubItems().add(creteNewSubItem(subItem));
}
}
return oldItem;
}
private Item creteNewSubItem(SubItem oldItem) {
Item i = new Item();
i.setDynamicRatio(oldItem.getDynamicRatio());
i.setEphermal(oldItem.getEphermal());
i.setInheritProfile(oldItem.getInheritProfile());
i.setLogging(oldItem.getLogging());
i.setRateLimit(oldItem.getRateLimit());
i.setRatio(oldItem.getRatio());
i.setSession(oldItem.getSession());
i.setAddress(oldItem.getAddress());
i.setName(oldItem.getName());
i.setState(oldItem.getState());
return i;
}
}
The list has a size of 134, so I receive an output of two times 'Call count 134'. This results in having duplicates in the list.
Here are the POJOs:
JSON response where getItems() for the foor loop is called:
public class JsonResponse {
private String kind;
private String selfLink;
private List<Item> items = new ArrayList<Item>();
public JsonResponse() {
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getSelfLink() {
return selfLink;
}
public void setSelfLink(String selfLink) {
this.selfLink = selfLink;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
The Item class is a simple DTO, containing only variables and their getters/setters:
Here is where the method is invoked:
itemTree = new PoolTreeBuilderImpl().buildTree(j);
itemTree.stream().forEach(i -> {
System.out.println("[PARENT] " + i.getData().toString());
i.getData().getSubItems().stream().forEach(si -> {
System.out.println(" [CHILD] " + si.toString());
});
});
}
and the PoolTreeBuilderImpl calls:
#Override
public List<TreeNode<Item>> buildTree(JsonResponse jsonResponse) {
List<TreeNode<Item>> itemTree = new ArrayList<>();
List<Item> mappedItems = new PoolItemMapper().mapJsonObjectsToItems(jsonResponse);
for (Item i : mappedItems) {
TreeNode<Item> item = new TreeNode<>(i);
if (i.getSubItems().size() > 0) {
for (Item subItem : i.getSubItems()) {
item.addChild(subItem);
}
}
itemTree.add(item);
}
return itemTree;
}
Could someone explain me why this loop is called twice resulting in having each subitem twice in the list?
Update
When executing this code, I don't have the duplicates:
List<Item> mappedItems = new PoolItemMapper().mapJsonObjectsToItems(jsonResponse);
mappedItems.forEach(i -> {
System.out.println("[PARENT] " + i.toString());
i.getMembersReference().getItems().forEach(s -> {
System.out.println(" [CHILD] " + s.toString());
});
});
The problem lies in the JsonResponse object, which is always the same. The objects within the JsonResponse list are modified twice, so there are duplicates. That is why (#Joakim Danielson) there is the second parameter newItem.
Additionally I had to change the signature of the buildTree method of the TreeBuilder to accept a list of Items, the one returned by the mapper.

how can I erase some specific word from a strind and stored it in a temporary variable and send that variable to my query

Here I wrote three file called "fruit.jsp", "fruitcontroller.java" and "fruitshopDAO.java". In fruit.jsp I am getting some value from browser, the value is like " Fruit Shop - Groth Center". I want to erase the "Groth Center" from my data. and stored it into another variable.And Finally pass that variable to the query. All my files are listed below, Please help me to solve this problem.
/fruit.jsp
function loadDividendSchemes()
{
var scheme = $('#txt_growth_scheme').val(); /* Fruit Shop - Groth Center */
$.ajaxSetup({async:true});
$.post("/getFruitShop", {scheme : ""+scheme+""}, function(data)
{
var result1 = $.trim(data);
var obj = jQuery.parseJSON(result1);
}, "text");
}
/fruitcontroller.java
#RequestMapping(value="/getFruitShop")
public void getFruitShop(HttpServletRequest request, HttpServletResponse response) throws Exception
{
PrintWriter writer = response.getWriter();
Gson gson = new Gson();;
try
{
String requestUrl = request.getRequestURL().toString();
if(!AdvisorkhojUtils.isValidUrl(requestUrl, "getFruitShop"))
{
response.sendRedirect(request.getContextPath() + "/page-not-found?invalidUrl=" + requestUrl);
return;
}
String scheme = request.getParameter("scheme"); /* value "Fruit Shop - Groth Center" from the jsp file */
if(scheme == null || StringHelper.isEmpty(scheme)){scheme = "fruit shop - Growth";}
scheme = scheme.trim();
List<String> schemeList = mutualFundPerformanceDAO.getFruitShop(scheme); /* send scheme = "Fruit Shop - Groth Center" to fruitshopDAO.java */
response.setContentType("application/json");
writer.println(gson.toJson(schemeList));
writer.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
/fruitshopDAO.java
public List<String> getFruitShop(String scheme)
{
Session session = null;
Query query = null;
List<String> list = null;
/* How can I erase "Groth Center" from scheme and stored remaining string into a new variable called "findshop" and send it to below query */
/* I want something like "findshop = Fruit Shop -" */
try
{
session = HibernateUtils.getAdvisorkhojAmfiSession();
session.getTransaction().begin();
query = session.createSQLQuery( "from scheme_mapping where fruitshop like 'findshop%'");
query.setMaxResults(25);
list = query.list();
session.getTransaction().commit();
}
catch(Exception ex)
{
session.getTransaction().rollback();
ex.printStackTrace();
}
return list;
}
}
I guess this is what you need.
String findShop = scheme.substring(0, scheme.indexOf("-"));
Further pass it into the query as :
"from scheme_mapping where fruitshop like :findShop").setParameter("findShop", findShop+"%");

List iterator returning zero

i am trying to iterate records from a table using the list iterator but it is returning zero records . i have used a setter getter class and trying to fetch records into a jsp page
code is as follows :
java function :
public List<product> getProducts()
{
List<product> prod=new ArrayList<product>();
try
{
conn = obj.connect();
String sql="select product.product_name , product.price , product.image_url "
+ "from category , product "
+ "where product.category_id=category.category_id and product.product_brand like 'LG%'";
rs=cs.executeQuery(sql);
while(rs.next())
{
p.setPname(rs.getString(1));
p.setPrice(rs.getString(2));
p.setImg(rs.getString(3));
}
prod.add(p);
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(Exception k)
{
k.printStackTrace();
}
return prod;
}
jsp code :
operations op=new operations();
product p=new product();
List<product> list=op.getProducts();
%>
<title>LG Mobiles</title>
</head>
<body>
<b><font color="blue">Total Records Fetched : <strong><%=list.size()%></strong></font></b>
QUERY is running fine in sql , i checked and confirmed
below is the small segment from setter getter class product.java
public void setPname(String pname)
{
this.pname=pname;
}
public String getPname()
{
return pname;
}
public void setPrice(String price)
{
this.price=price;
}
public String getPrice()
{
return price;
}
Move prod.add(p); inside the while loop. As you are not adding object everytime. Also you need to create new object of p in loop everytime.
while(rs.next())
{
product p = new product();
p.setPname(rs.getString(1));
p.setPrice(rs.getString(2));
p.setImg(rs.getString(3));
prod.add(p);
}
you have to remove , from category and product using as
String sql="select product.product_name , product.price , product.image_url "
+ "from category as product "
+ "where product.category_id=category.category_id and product.product_brand like 'LG%'"
or
you also try this one
prod=cs.executeQuery(sql);
Iterator it=prod.iterator;
while(it.next())
{
---------------
}

Resultant list of hibernate select query does get cast to the corresponding bean class

The following query was generated by hibernate
Select sum(B.c_rejected_count) as y0_,B.c_date as y1_,B.c_node_site_id as y2_,
A.c_sccp_addr as y3_ from tb_sccp_addr A inner join tb_dm_sccp_rej_day B on
A.c_sccp_addr_id=B.c_sccp_addr_fk group by A.c_date, A.c_node_site_id,
B.c_sccp_addr, B.c_sccp_addr_id ;
My Beanclass has following data:
private Date date;
private long rejectedCount;
private int nodeSiteId;
private String sccpAddress;
when I cast the resultant list of select query to my beanclass, I get a cast exception
java.lang.ClassCastException
Please identify what is going wrong and how to solve it
I am using Java reflection
//function initialises select query
private void initializeSelectQuery()
{
log(Level.DEBUG, "Entering initializeSelectQuery");
Class classname = beanclass.getMappedClass();
crit = hibernateSession.createCriteria(classname);
if(group.getAggregate().equals("SUM"))
{
projectionList.add(Projections.sum(beanDefinition
.getPropertyForColumn(group.getColumnName())));
}
else
{
projectionList.add(Projections.groupProperty(beanDefinition
.getPropertyForColumn(group.getColumnName())));
}
crit.setProjection(projectionList);
crit.setMaxResults(10);
}
public List executeSelectQuery() {
log(Level.DEBUG, "Entering executeSelectQuery");
List datalist = null;
try {
tx = hibernateSession.beginTransaction();
if (crit != null) {
datalist = crit.list();
}
tx.commit();
} catch (MappingException e) {
e.printStackTrace();
System.out.println(e.getMessage());
} catch (HibernateException e) {
e.printStackTrace();
}
log(Level.DEBUG, "Exiting executeSelectQuery");
return datalist;
}
You don't seem to use any result transformer (such as AliasToBeanResultTransformer) for your query. So, since it uses a projection list, your query returns a List<Object[]>. there is no way Hibernate can know that it must return instances of your bean class. Either you transform the List<Object[]> into what you want explicitely, or you use a ResultTransformer.

Selection doesn't work in extendedDataTable, RichFaces 4 + JSF 2.0

I have an app with RichFaces 4.0.0.Final and JSF 2.0. When I try to use selection in extendedDataTable, it doesn`t work.
<rich:extendedDataTable
id="shipmentList" value="#{shipmentListBean.shipmentList}" var="shipment"
rowClasses="#{shipment.paymentDate == null ? 'unpaidShipment' : null}"
selectionMode="single" noDataLabel="#{msgs.emptyList}"
selection="#{shipmentListBean.selection}"
style="width: 1200px; font-size: 10px; ">
ShipmentListBean:
#ManagedBean
#ApplicationScoped
public class ShipmentListBean implements Serializable {
private Collection<Object> selection = null;
public ShipmentListBean() {
}
public List<ShipmentValueObject> getShipmentList() {
....
}
public Collection<Object> getSelection() {
return selection;
}
public void setSelection(Collection<Object> selection) {
this.selection = selection;
}
}
Why in method selSelection(Collection selection) empty collection come when I select row in table?
you can use selection like this
in ShipmentListBean
private SimpleSelection selection = new SimpleSelection();
// now time to get a selected Row id from the extendedDataTable.
// this method you can call on any button after selecting the row from the extendedDataTable
public void selectedRecord(){
try{
Iterator<Object> iterator = getSelection().getKeys();
while(iterator.hasNext()){
// Here you will get all the selected roes id from the Data table
Object obj = iterator.next();
info("GET SELECTED ROWS ID ::::: " + obj.toString());
}
}catch(Exception e){
e.printStackTrace();
}
}

Categories