can't get Object when it is Selected - jsf

File: ServiceAnnonce.java
public List<Annonce> loadAnnonce( UserEntity idUser ) {
Query query = getEntityManger().createQuery( "select u from "
+ getPersistentClass().getSimpleName()
+ " u where u.annonceUser= :idUser" ).setParameter( "idUser", idUser );
List<Annonce> annonce = (List) query.getResultList();
return annonce;
}
File : DaoUser.java
public UserEntity loadUserByEmail( String email ) {
Assert.notNull( email );
UserEntity user = null;
Query query = getEntityManger().createQuery( "select u from "
+ getPersistentClass().getSimpleName()
+ " u where u.email= :email" ).setParameter( "email", email );
try {
user = (UserEntity) query.getSingleResult();
} catch ( NoResultException e ) {
}
return user;
}
File : ServiceUser.java
public Annonce annonceEnFonctionId( Annonce annonce, String email ) {
UserEntity user = userDao.loadUserByEmail( email );
List<Annonce> a = annonceDao.loadAnnonce( user );
Annonce an = annonce;
for ( int i = 0; i < a.size(); i++ ) {
if ( a.get( i ).getId() == (Long) an.getId() ) {
an = annonce;
}
}
return an;
}
File: flow.xml
<transition on="annonceID" to="annonceEnFonctionId">
<evaluate expression="userService.annonceEnFonctionId(annonce,user.getEmail())" result="flowScope.annonce" />
</transition>
File : OurAnnonce.java
<p:dataTable var="item" value="#{annonce}">
<p:column style="width:2%">
<h:commandButton value="show" action="annonceID" />
</p:column>
<p:column>
<h:outputText value="#{item.titre}" />
</p:column>
File:shwo.java
<p:dataTable var="valeur" value="#{annonce}">
<p:column headerText="Model">
<h:outputText value="#{valeur.titre}" />
</p:column>
</p:dataTable>
when i click Button show i should get more detail of annonce selected but i still get always the first annonce in DataBase any idea ??

Related

PF6 SelectOneMenu filter is not fired with "Paste" or with "CTRL + Backspace"

Using PrimeFaces 6, I am trying to filter my p:selectOneMenu when the user paste a value or when the user delete a value using CTRL + Backspace, in another word, when the value got changed anyhow.
Please find my below code.
<p:selectOneMenu id="providerURLDD" widgetVar="providerURLDD"
value="#{switchProviderBean.selectedProvider}"
panelStyle="width:240px" effect="fade" filter="true"
style="width:240px" filterMatchMode="contains"
required="true"
requiredMessage="#{msg['selectProvider']}">
<f:selectItem itemLabel="Select" />
<f:selectItems value="#{switchProviderBean.providerAccounts}"
var="providerAcc"
itemLabel="#{providerAcc.code}-#{providerAcc.switchAccountId}-#{providerAcc.name}"
itemValue="#{providerAcc.switchAccountId}" />
</p:selectOneMenu>
I also tried to use Javascript like this:
function getTextAreaSelection(textarea) {
var start = textarea.selectionStart,
end = textarea.selectionEnd;
return {
start: start,
end: end,
length: end - start,
text: textarea.value.slice(start, end)
};
}
function detectPaste(textarea, callback) {
textarea.onpaste = function() {
var sel = getTextAreaSelection(textarea);
var initialLength = textarea.value.length;
window.setTimeout(function() {
var val = textarea.value;
var pastedTextLength = val.length - (initialLength - sel.length);
var end = sel.start + pastedTextLength;
callback({
start: sel.start,
end: end,
length: pastedTextLength,
text: val.slice(sel.start, end)
});
}, 1);
};
}
var textarea = document.getElementById("switchProviderChoice:providerURLDD_filter");
detectPaste(textarea, function(pasteInfo) {
console.log('perform filter');
PF('providerURLDD').filter();
});

the view "Delete" or its master was not found asp.net mvc5

I want to be able to upload a file then to download it or delete it. But when I try to delete it, I get this error:
The view 'Delete' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/FileUpload/Delete.aspx ,~/Views/FileUpload/Delete.ascx, ~/Views/Shared/Delete.aspx,~/Views/Shared/Delete.ascx, ~/Views/FileUpload/Delete.cshtml, ~/Views/FileUpload/Delete.vbhtml, ~/Views/Shared/Delete.cshtml ,~/Views/Shared/Delete.vbhtml .
[HttpGet]
public ActionResult Delete( string deletedfile)
{
string current_usr = User.Identity.GetUserId();
string fullPath = Request.MapPath("~/Files/" + current_usr + "/" + deletedfile);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
ViewBag.Message="Deleted";
}
var items = GetFiles();
return View(items);
}
// GET: FileUpload
public ActionResult Index()
{
var items = GetFiles();
return View(items);
}
// POST: FileUpload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
try
{
string current_usr = User.Identity.GetUserId();
//string path = Path.Combine(Server.MapPath("~/Files/"),
// Path.GetFileName(file.FileName));
var folder = Server.MapPath("~/Files/" + current_usr + "/");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
string path = Path.Combine(String.Format(folder),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
var items = GetFiles();
return View(items);
}
public FileResult Download(string downloadedfile)
{
string current_usr = User.Identity.GetUserId();
var FileVirtualPath = "~/Files/" + current_usr + "/" + downloadedfile;
return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}
private List<string> GetFiles()
{
string current_usr = User.Identity.GetUserId();
var dir = new System.IO.DirectoryInfo(Server.MapPath("~/Files/" + current_usr + "/"));
System.IO.FileInfo[] fileNames = dir.GetFiles("*.*");
List<string> items = new List<string>();
foreach (var file in fileNames)
{
items.Add(file.Name);
}
return items;
}
The View :
<h2> File Upload </h2>
#model List<string>
#using (Html.BeginForm("Index", "FileUpload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file"> Upload </label>
<input type="file" name="file" id="file" />
<br /><br />
<input type="submit" value="Upload" />
<br /><br />
#ViewBag.Message
<br />
<h2>Documents list</h2>
<table style="width:100%">
<tr>
<th> File Name </th>
<th> Link </th>
</tr>
#for (var i = 0; i <= (Model.Count) - 1; i++)
{
<tr>
<td>#Model[i].ToString() </td>
<td>#Html.ActionLink("Download", "Download", new { downloadedfile = Model[i].ToString() }) </td>
<td>
#Html.ActionLink("Delete", "Delete", new { deletedfile = Model[i].ToString() })
</td>
</tr>
}
</table>
}
The issue is that your Delete Controller method is calling View() at the end. That method will attempt to find a view file with the name of the controller method. If you want to show the list of files after the delete you can redirect to your index action like this:
[HttpGet]
public ActionResult Delete(string deletedfile)
{
string current_usr = User.Identity.GetUserId();
string fullPath = Request.MapPath("~/Files/" + current_usr + "/" + deletedfile);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
ViewBag.Message = "Deleted";
}
return RedirectToAction("Index");
}
See this link from the microsoft Docs for more detail on redirecting
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/views/asp-net-mvc-views-overview-cs

Filter for JSF table

I would like to add filter for JSF table and limit the values based on filter value.
<h:inputText id="search" value="#{accounts.searchString}"></h:inputText>
<h:commandButton value="Search" action="#{accounts.search()}">
<f:ajax execute="search" render="output"></f:ajax>
</h:commandButton>
I suppose that the best way will be to add the filter value into the SQL query:
SELECT * FROM CUSTOMERS ORDER BY %S %S offset ? limit ?
Full code: http://pastebin.com/eEeTWEqK
How I can implement this for the code into the link?
PS. I modified the code this way:
<div class="div_input_style">
<h:inputText id="search" class="input_style" value="#{accounts.searchString}"></h:inputText>
<h:commandButton class="theSpan" value="Search by title">
<f:ajax execute="search" render="output"></f:ajax>
</h:commandButton>
</div>
public List<AccountsObj> list(int firstRow, int rowCount, String sortField, boolean sortAscending) throws SQLException
{
String SqlStatement = null;
if (ds == null)
{
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null)
{
throw new SQLException();
}
String sortDirection = sortAscending ? "ASC" : "DESC";
SqlStatement = "SELECT * FROM ACCOUNT "
+ " WHERE ? IS NULL OR ? IN (USER_NAME, FIRST_NAME, LAST_NAME)"
+ " ORDER BY %S %S offset ? limit ? ";
String sql = String.format(SqlStatement, sortField, sortDirection);
PreparedStatement ps = null;
ResultSet resultSet = null;
List<AccountsObj> resultList = new ArrayList<>();
try
{
conn.setAutoCommit(false);
boolean committed = false;
ps = conn.prepareStatement(sql);
ps.setString(1, searchString);
ps.setString(2, searchString);
ps.setInt(3, firstRow);
ps.setInt(4, rowCount);
resultSet = ps.executeQuery();
resultList = ProcessorArrayList(resultSet);
conn.commit();
committed = true;
}
finally
{
ps.close();
conn.close();
}
return resultList;
}

How to update center layout unit in PrimeFaces

I am trying to load contents of file in the center layout. On selection event of tree node. But I am not able to display it in the center layout. When i refresh the page then also it is not displaying the contents of file.
This is my xhtml page.I am going wrong somewhere?
<h:body>
<h:form id="form">
<h:commandLink id="back" action="Welcome?faces-redirect=true" type="link"/>
<p:layout fullPage="true">
<p:layoutUnit position="west" size="200" header=
"document List" resizable="true" closable="false" collapsible="false">
<h:outputText value="Searched document's " />
<p:tree value="#{searchContent.root}" var="node" dynamic="true" selectionMode="single"
selection="#{searchContent.singleSelectedNode}">
<p:treeNode >
<h:outputText value="#{node}" />
</p:treeNode>
<p:ajax event="select" listener="#{searchContent.onNodeSelect}"/>
</p:tree>
</p:layoutUnit>
<p:layoutUnit position="east" size="200" header=
"extra" resizable="true" closable="false" collapsible="false">
<h:outputText value="Uploaded by Author's Name" />
</p:layoutUnit>
<p:layoutUnit position="center">
<!-- <h:panelGroup id ="test">-->
<h:outputText value="#{searchContent.fileData}" />
<!-- </h:panelGroup>-->
</p:layoutUnit>
</p:layout>
</h:form>
</h:body>
and here is my managed bean of this page.on select event I am getting the name of the node.And I am reading the file contents line by line. I am getting the contents properly but not able to display in layout
public void onNodeSelect(NodeSelectEvent event) throws FileNotFoundException, IOException {
String path = null;
FileInputStream fis = null;
COSDocument cosdocument = null;
Document doc = new Document();
TreeNode treeNode = event.getTreeNode();
String namecheck = treeNode.toString();
System.out.println("\t" + namecheck);
String name = null, fullname = null, filePath = null;
System.out.println("treeNode contains:" + treeNode);
System.out.println("Node Data ::" + treeNode + " :: Selected");
int _icnt = 0;
while (_icnt < treeList.size()) {
name = treeList.get(_icnt);
System.out.println("Name :" + name);
fullname = field.get(_icnt);
System.out.println("Full Name:" + fullname);
//String nodeTokens[] = name.split(Pattern.quote("."));
if (namecheck.equalsIgnoreCase(name)) {
System.out.println("*******************************");
break;
}
System.out.println(MessageFormat.format("Icnt is:{0}", _icnt++));
}
System.out.println("After while loop");
/*
Database Call to get the filePath based on fileName
from f.getName() .
*/
String result = UserDAO.getFileName(fullname);
System.out.println("Result" + result);
if (!(result.equals(""))) {
File f = new File(result);
if (f.isFile()) {
if (f.getName().endsWith(".docx")) {
try {
fileData = null;
path = f.getAbsolutePath();
fis = new FileInputStream(f.getAbsolutePath());
XWPFDocument document = new XWPFDocument(fis);
List<XWPFParagraph> paragraphs = document.getParagraphs();
for(XWPFParagraph paras : paragraphs){
fileData = paras.getText();
System.out.println("File data of docx file is:"+fileData);
}
System.out.println("Path is:" + path);
} catch (Exception e) {
System.err.println("Exception in reading docx file is:");
e.printStackTrace();
} finally {
fis.close();
}
} else if (f.getName().endsWith(".doc")) {
try{
fileData = null;
path = f.getAbsolutePath();
System.out.println("Path is:" + path);
fis = new FileInputStream(f.getAbsolutePath());
HWPFDocument hwpfDoc = new HWPFDocument(fis);
WordExtractor wrdExtract = new WordExtractor(hwpfDoc);
String[] paragraphText = wrdExtract.getParagraphText();
for (String paragraph : paragraphText) {
fileData = paragraph;
System.out.println("File Data of doc file is:" + fileData);
}
}
catch(Exception ex){
System.err.println("Exception in reading doc file is:");ex.printStackTrace();
}
finally{
fis.close();
}
} else {
if (f.getName().endsWith(".pdf")) {
try{
fileData = null;
path = f.getAbsolutePath();
System.out.println("Path is:" + path);
PDFParser parser = new PDFParser(new FileInputStream(f.getAbsolutePath()));
parser.parse();
cosdocument = parser.getDocument();
PDFTextStripper stripper = new PDFTextStripper();
fileData = stripper.getText(new PDDocument(cosdocument));
System.out.println("File Data of pdf is:"+fileData);
}catch(Exception ex){
System.err.println("Exxception in reading pdf is:");ex.printStackTrace();
}
finally{
cosdocument.close();
}
} else {
if (f.getName().endsWith(".txt")) {
fileData = null;
path = f.getAbsolutePath();
System.out.println("Path is:" + path);
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
while ((line = br.readLine()) != null) {
fileData = line;
System.out.println("fileData:" + fileData);
}
System.out.println("fileData:" + fileData);
}
}
}
}
}
}
You don't update content you want to be refreshed.
<p:ajax event="select" listener="#{searchContent.onNodeSelect}" update="form:fileData"/>
Add id to your h:outputText
<p:layoutUnit position="center">
<h:outputText id="fileData" value="#{searchContent.fileData}" />
</p:layoutUnit>
Related:
How to update a layoutUnit in PrimeFaces
How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Controlling cart with session

My cart is working fine in localhost but when i have hosted in cloud hosting it is not working well problem is that when i click add to cart button it will add one product with one quantity but when i add another product in the cart again it will override the previous one and show only one product in cart when i have added on last.. i don't know whats wrong with the sessions it will override the session again i guess. And another problem is that my my update cart button's functionalities and delete button functionalities in cart is not working it throw exception
Object reference not set to an instance of an object.
I have a controller name shoppingCartController here is the code
namespace Medi.Areas.User.Controllers
{
public class ShoppingCartController : Controller
{
ArrayList arr = new ArrayList();
int id;
BLL.IRepository<tbl_Product> de = new BLL.IRepository<tbl_Product>();
public ActionResult Index()
{
return View();
}
private int isExisting(int id)
{
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
if (cart[i].Pr.ProductID == id)
return i;
return -1;
}
public ActionResult Delete(int id)
{
int index = isExisting(id);
List<Items> cart = (List<Items>)Session["cart"];
cart.RemoveAt(index);
Session["cart"] = cart;
return PartialView("_pvCart");
}
public ActionResult OrderNow(string q)
{
if (Session["cart"] == null)
{
List<Items> cart = new List<Items>();
cart.Add(new Items(de.GetById(Convert.ToInt32(q)), 1));
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart,"Quantity","Quantity");
// cart[1]
}
else
{
id = Convert.ToInt32(q);
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity++;
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart, "Quantity", "Quantity");
}
return View("Cart");
}
[HttpPost]
public ActionResult UpdateCart(int[] ProductID,int [] quantity )
{
int[] x = new int[4];
int[] y = new int[4];
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
{
x[i] = ProductID[i];
y[i] = quantity[i];
updcart(x[i],y[i]);
}
Session["cart"] = cart;
return PartialView("_pvCart");
}
public void updcart(int id,int quantity) {
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity = quantity;
Session["cart"] = cart;
}
}
}
and here is the view name Cart.cshtml
#{
ViewBag.Title = "Cart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("UpdateCart", "ShoppingCart", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }))
{
#Html.AntiForgeryToken()
<br />
<br />
<div id="MyData">
#{Html.RenderPartial("_pvCart");}
</div>
<br /><br />
<input id="updatecart" type="submit" value="update Cart" />
}
and here is the partial view code
#using Medi.Models;
<script src="~/Scripts/metro.min.js"></script>
<table class="table hovered" cellpadding=" 2" cellspacing="2" border="1px">
<tr class="info">
<th></th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
#{
decimal s = 0;
}
#foreach (Items item in (List<Items>)Session["cart"])
{
<input id="ProductID" name="ProductID" type="hidden" value="#item.Pr.ProductID" />
s = s + (Convert.ToInt32(item.Pr.Price) * item.Quantity);
<tr>
<th>#Ajax.ActionLink("Delete", "Delete", new { id = item.Pr.ProductID }, new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }, new { #class = "mif-cross" })</th>
<td>#item.Pr.ProductName</td>
<td>#item.Pr.Price</td>
<td>
<input name="quantity" id="quantity" type="text" style="width:25px;" value="#item.Quantity" />
</td>
<td>#(item.Pr.Price * item.Quantity)</td>
</tr>
}
</table><br />
<hr />
<table cellpadding="1px" cellspacing="1px" style="float:right;">
<tr align="center" colspan="5" style="background-color:gray;">
<td><h3 style="padding:1px;">Total</h3></td>
<td> <h3 style="padding:1px;">Rs #s</h3></td>
</tr>
</table>
here is the model class
using BOL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Medi.Models
{
public class Items
{
tbl_Product pr = new tbl_Product();
public tbl_Product Pr
{
get { return pr; }
set { pr = value; }
}
int quantity;
public int Quantity { get; set; }
public Items()
{
}
public Items(tbl_Product product, int quantity)
{
this.Pr = product;
this.Quantity = quantity;
}
}
}
i have also write this code in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
<sessionState mode="InProc"/>

Resources