How I can keep a variable session in JSF? - session

I have the following code:
if (httpServletR.getSession().getAttribute("ush_id") != null) {
rol_id = Integer.parseInt(httpServletR.getSession().getAttribute("rol_id").toString());
logger.info("Rol: "+rol_id);
Rol rl=new Rol();
rl.setRol_id(rol_id);
}
Where basically if the user exists the role is set, but when I try to recover the role from the bean:
public void selectmtvlista() throws Exception {
motivosolicitudDAO dao = new motivosolicitudDAO();
adminBean adm = new adminBean();
int rolid = adm.getRol_id();
try {
this.selectmotivosolicitud = dao.listarSelectMotivoSolicitud(rolid);
} catch (Exception e) {
throw e;
}
}
I do not recover the role defined in the first piece of code. and given that selectmtvlista () should return the list of options for the role, I return something else. So it would be best to keep rol_id in a session variable, but as establesco this variable and how they recovered from the Bean?
Any help, I am grateful.

Related

org.hibernate.MappingException: Could not locate CollectionPersister for role : com.jbk.Entity.Product.productName

`Whenever, I try to run below method it is giving above error
public static List<Product> productGettingWithSize(int size) {
Session session = factory.openSession();
List<Product> list = null;
try {
Criteria criteria = session.createCriteria(Product.class);
criteria.add(Restrictions.sizeEq("productName", size));
list = criteria.list();
if (list.isEmpty()) {
System.out.println("No Data Found..!!");
} else {
System.out.println(list);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
So, here in this code in DB productName is REDMI so, I m passing 5 as an size but, I m not getting the expected output.
So could anyone help me regarding this code or Can any anyone Tell how to use Restrictions(Size), all method related to size or can anyone send me the documentation where it is been explained explicitly.
Thank You...!!!
Expecting a solution on This..!!`

Error in forEach when use a consumer to avoid try-catch in forEach in Java8

I have a log() method to avoid try catch statement in forEach() below which was working in other code.
public <T> Consumer<T> log(LogConsumer<T, Throwable> logConsumer)
{
return i -> {
try
{
logConsumer.accept(i);
}
catch (Throwable e)
{
log("e = " + e);
}
};
}
#FunctionalInterface
public interface LogConsumer<T, E extends Throwable> {
void accept(T t) throws E;
}
Now I just want to use log in forEach below but I have the red rippled line in LINE such that
new Task.runJob(job, type))
I have red rippled line under job, type in
"runJob(Job, JobType) in Task cannot be applied to (java.lang.Object, < lambda parameter>)"
Now sure how to fix it to use log in forEach just to avoid
try-catch inside of it.
execute() {
Map<Job, JobType> map = getJobMap();
map.forEach( log((job, type)-> new Taks().runJob(job,type)) ); // LINE: error here
}
class Task {
public String runJob(Job job, JobType type) throws Exception
{
...
return result;
}
}
It happens because you cannot execute functions that throw exceptions using lambda expressions. You have to handle the exception using try-catch block. However, in order for your code to look more readable, create a function, that will handle the exception and return the desired result.
class Task {
public String runJob(Job job, JobType type)
{
try {
...
return result;
} catch (Exception e) {
log.error(e.getMessage());
}
return null;
}
}
In case if you care what will be the result, map it and filter for the result of your function is not null, otherwise, ignore it, but watch logs for any errors.
And then call it like shown below.
Notice: both ways work below, but the second way is more robust because you can handle the scenario when not all jobs were executed without exception.
execute() {
Map<Job, JobType> map = getJobMap();
// First way
map.forEach( log((job, type) -> new Taks().runJob(job,type)) );
// Another way
List<Object> batchResult = map.entrySet().stream()
.map((job, type) -> new Task().runJob(jon, type))
.filter(Objects::nonNull)
.collect(Collectors.toList());
if (batchResult.size() == map.size()) {
// everythings is ok (all operations resulted in non-null result
} else {
// Have to study logs and figure out what went wrong
}
}

DD anomaly, and cleaning up database resources: is there a clean solution?

Here's a piece of code we've all written:
public CustomerTO getCustomerByCustDel(final String cust, final int del)
throws SQLException {
final PreparedStatement query = getFetchByCustDel();
ResultSet records = null;
try {
query.setString(1, cust);
query.setInt(2, del);
records = query.executeQuery();
return this.getCustomer(records);
} finally {
if (records != null) {
records.close();
}
query.close();
}
}
If you omit the 'finally' block, then you leave database resources dangling, which obviously is a potential problem. However, if you do what I've done here - set the ResultSet to null outside the **try** block, and then set it to the desired value inside the block - PMD reports a 'DD anomaly'. In the documentation, a DD anomaly is described as follows:
DataflowAnomalyAnalysis: The dataflow analysis tracks local definitions, undefinitions and references to variables on different paths on the data flow.From those informations there can be found various problems. [...] DD - Anomaly: A recently defined variable is redefined. This is ominous but don't have to be a bug.
If you declare the ResultSet outside the block without setting a value, you rightly get a 'variable might not have been initialised' error when you do the if (records != null) test.
Now, in my opinion my use here isn't a bug. But is there a way of rewriting cleanly which would not trigger the PMD warning? I don't particularly want to disable PMD's DataFlowAnomalyAnalysis rule, as identifying UR and DU anomalies would be actually useful; but these DD anomalies make me suspect I could be doing something better - and, if there's no better way of doing this, they amount to clutter (and I should perhaps look at whether I can rewrite the PMD rule)
I think this is clearer:
PreparedStatement query = getFetchByCustDel();
try {
query.setString(1, cust);
query.setInt(2, del);
ResultSet records = query.executeQuery();
try {
return this.getCustomer(records);
} finally {
records.close();
}
} finally {
query.close();
}
Also, in your version the query doesn't get closed if records.close() throws an exception.
I think that DD anomaly note is more bug, than a feature
Also, the way you free resources is a bit incomplete, for example
PreparedStatement pstmt = null;
Statement st = null;
try {
...
} catch (final Exception e) {
...
} finally {
try{
if (pstmt != null) {
pstmt.close();
}
} catch (final Exception e) {
e.printStackTrace(System.err);
} finally {
try {
if (st != null) {
st.close();
}
} catch (final Exception e) {
e.printStackTrace(System.err);
}
}
}
moreover this is not right again, cuz you should close resources like that
PreparedStatement pstmt = null;
Throwable th = null;
try {
...
} catch (final Throwable e) {
<something here>
th = e;
throw e;
} finally {
if (th == null) {
pstmt.close();
} else {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (Throwable u) {
}
}
}

Linq to entities in asp.net and generic delete method

I am having trouble creating generic delete method, not even sure if this possible. I have a delete method which will delete record from db based on entity type and row id value (pk),
that works ok but it needs to know the type in advance. In some cases I can only get object
type using Object.GetType() at runtime (like from viewstate) and that is when trouble starts. Here is my method that works when type is known, is there a way to modify it so that it will use Object.GetType() instead of T ?
public void Delete<T>(long Id) where T : class,new()
{
#region PerformaneMonitor
IDbEntities Db=null;
T item=null;
try
{
Db = this.GetDatabase();
item = new T();
Type itemType = item.GetType();
EntityContainer entityContainer = Db.MetadataWorkspace.GetEntityContainer(Db.DefaultContainerName, DataSpace.CSpace);
var entity = entityContainer.BaseEntitySets.First(b => b.ElementType.Name == itemType.Name);
if (entity.ElementType.KeyMembers.Count == 0)
{
throw new Exception("Unable to delete a record witout unique id");
}
string PrimaryKeyName = entity.ElementType.KeyMembers[0].Name;
itemType.GetProperty(PrimaryKeyName).SetValue(item, Id, null);
}
catch (Exception ex)
{
Close(Db);
throw(ex);
}
this.Delete<T>(item, Db);
Close(Db);
#region PerformaneMonitor
}
so I am trying to convert it to Delete(object EntityType,long Id ) but no luck.
Here what it looks like :
public void Delete(object target,long Id)
{
#region PerformaneMonitor
IDbEntities Db = null;
try
{
Db = this.GetDatabase();
Type itemType = (Type)target;
EntityContainer entityContainer = Db.MetadataWorkspace.GetEntityContainer(Db.DefaultContainerName, DataSpace.CSpace);
var entity= entityContainer.BaseEntitySets.First(b => b.ElementType.Name == itemType.Name);
if (entity.ElementType.KeyMembers.Count == 0)
{
throw new Exception("Unable to delete a record witout unique id");
}
string PrimaryKeyName = entity.ElementType.KeyMembers[0].Name;
itemType.GetProperty(PrimaryKeyName).SetValue(target, Id, null);
}
catch (Exception ex)
{
Close(Db);
throw (ex);
}
this.Delete(target, Db);
Close(Db);
//_method_tag_end_
#region PerformaneMonitor
}
I am getting 'Object does not match target type' on
this line:
itemType.GetProperty(PrimaryKeyName).SetValue(target, pkey, null);
the object target is actaul instance of specific type which I do in the calling method from Type of object and using reflection and pass to this function but still I have no idea what type it is at run time.
If someone can help it will be greatly appreciated.
It sounds like you should do something along these lines: (Sorry, can't test to make sure it works as written.)
object o = itemType.GetProperty(PrimaryKeyName);
MethodInfo mi = o.GetType().GetMethod("SetValue");
mi.Invoke(o, new object [] { Id, null });

Roles.IsUserInRole() on My Base page class

I have a base page (inherited from System.Web.UI.Page and all my pages inherit from this base page) in my .Net web application and at the moment if I put the following methods
protected void CheckAllowedRole(string UserName, List<string> AllowedRoles)
{
try
{
bool IsAllowed = false;
foreach (string item in AllowedRoles)
{
if (Roles.IsUserInRole(UserName, item))
IsAllowed = true;
}
if (!IsAllowed)
Response.Redirect("~/Members/Error.aspx", false);
}
catch (Exception err)
{
Response.Redirect("~/Members/Error.aspx", false);
}
}
for somereason it doesn't know the role is!?!? Return. I even pass the username into this methods and still doesn't work either.
But if I take this code and put into my page which inherited from this base page works well (no issue). Any ideas? Is there any restriction on the Roles (or Membership provider in the base class).
Thanks
instead of providing the user name why don't you try this:
protected void CheckAllowedRole(List<string> AllowedRoles)
{
try
{
if (!Page.User.Identity.IsAuthenticated)
throw new Exception("Unauthenticated User");
string name = Page.User.Identity.Name;
bool IsAllowed = false;
foreach (string item in AllowedRoles)
{
IsAllowed = Roles.IsUserInRole(name, item);
}
if (!IsAllowed)
Response.Redirect("~/Members/Error.aspx", false);
}
catch (Exception err)
{
Response.Redirect("~/Members/Error.aspx", false);
}
}

Resources