How to render enum values from dataclass on xhtml jsf page - java

i have an enum in my data-class as follows
public enum ProcStat
{
NOT_READY ((byte)-1, "Not Ready For Processing"),
READY_FOR_PROCESSING ((byte)0, "Ready For Processing"),
BEING_PROCESSED ((byte)1, "Being Processed"),
PROCESSED_SUCCESSFULLY ((byte)2, "Processed Successfully"),
MSG_SUPPRESSED ((byte)98, "Msg suppressed before processing"),
PROCESSED_ERROR ((byte)99, "Processed With Error");
private final Byte statByte;
private final String statusDesc;
ProcStat(Byte statByte, String statusDesc)
{
this.statByte = statByte;
this.statusDesc = statusDesc;
}
#Override
public String toString()
{
return statusDesc;
}
protected static ProcStat getProcStat(Byte procStat)
{
if (READY_FOR_PROCESSING.statByte.equals(procStat))
{
return READY_FOR_PROCESSING;
}
else if (BEING_PROCESSED.statByte.equals(procStat))
{
return BEING_PROCESSED;
}
else if (PROCESSED_SUCCESSFULLY.statByte.equals(procStat))
{
return PROCESSED_SUCCESSFULLY;
}
else if (MSG_SUPPRESSED.statByte.equals(procStat))
{
return MSG_SUPPRESSED;
}
else if (PROCESSED_ERROR.statByte.equals(procStat))
{
return PROCESSED_ERROR;
}
else
{
return NOT_READY;
}
}
public Byte getStatByte()
{
return this.statByte;
}
};
The Proc_Stat refers to a Number field in a DataBase table and i need to show a column on the page where it shows the corresponding String of the numeric proc_stat for each row.
This is how i render any other field of the same data-class on the xhtml page:
id="dataTable" name="dataTable" var="data"
How do i give output value for enum type?
do i give like this : value="#{data.procstat.toString()}" ??

I think you need to create method in one of your managed bean that does the same as getProcStat method. Something like:
public String getProcStat(Byte byte) {
return ProcState.getProcState(byte).toString();
}
In xhtml:
value="#{yourBean.getProcState(data)}"

Related

Flutter Plugin access native objects

I'm developing a Flutter plugin to implements an iOS SDK and an Android SDK in Flutter. In both native SDKs, there is an object called Peripheral, which is a complexe object extending and implementing other objects. If I want to use theses Objects, do I have to implement them in Flutter too ? Or can I just create an manipulate instances of those objects from dart.
Right now, I'm trying to manipulate instances by have a PeripheralObject that calls a function in constructor that will create an instance in native Java (for Android) of a peripheral, place it in a hash map, and return it's memory adress to dart. In dart, I keep the memory adress of the Java object and when I call a function, like getName, I pass to the method channel the java memory adress and with that, I can retrieve from the map my instance of the native object, call the method and send back the answer. Is it a good way of resolving the problem or is there other better way to do so ?
Here is my dart object:
class Peripheral {
late String _objectReference;
late String _localName, _uuid;
Peripheral({required String localName, required String uuid}) {
_uuid = uuid;
_localName = localName;
_newPeripheralInstance(localName, uuid);
}
Future<void> _newPeripheralInstance(String localName, String uuid) async {
_objectReference = (await PeripheralPlatform.instance.newPeripheralInstance(localName, uuid))!;
return;
}
String get objectReference => _objectReference;
Future<String?> getModelName() async {
return PeripheralPlatform.instance.getModelName(_objectReference);
}
Future<String?> getUuid() async {
return PeripheralPlatform.instance.getUuid(_objectReference);
}
}
Here is my Dart Method Channel :
class MethodChannelPeripheral extends PeripheralPlatform {
/// The method channel used to interact with the native platform.
#visibleForTesting
final methodChannel = const MethodChannel('channel');
#override
Future<String?> newPeripheralInstance(String localName, String uuid) async {
String? instance = await methodChannel.invokeMethod<String>('Peripheral-newPeripheralInstance', <String, String>{
'localName': localName,
'uuid': uuid
});
return instance;
}
#override
Future<String?> getModelName(String peripheralReference) {
return methodChannel.invokeMethod<String>('Peripheral-getModelName', <String, String>{
'peripheralReference': peripheralReference
});
}
#override
Future<String?> getUuid(String peripheralReference) {
return methodChannel.invokeMethod<String>('Peripheral-getUuid', <String, String>{
'peripheralReference': peripheralReference
});
}
}
And here is my Android Java file :
public class PluginPeripheral {
private static Map<String, Peripheral> peripheralMap = new HashMap<>();
public static void handleMethodCall(String method, MethodCall call, MethodChannel.Result result) {
method = method.replace("Peripheral-", "");
switch (method) {
case "newPeripheralInstance":
newPeripheralInstance(call, result);
break;
case "getModelName":
getModelName(call, result);
break;
case "getUuid":
getUuid(call, result);
break;
default:
result.notImplemented();
break;
}
}
private static void newPeripheralInstance(MethodCall call, MethodChannel.Result result) {
if (call.hasArgument("uuid") && call.hasArgument("localName")) {
String uuid = call.argument("uuid");
String localName = call.argument("localName");
if (localName == null || uuid == null) {
result.error("Missing argument", "Missing argument 'uuid' or 'localName'", null);
return;
}
Peripheral peripheral = new Peripheral(localName, uuid);
peripheralMap.put(peripheral.toString(), peripheral);
result.success(peripheral.toString());
}
}
private static void getModelName(MethodCall call, MethodChannel.Result result) {
if (call.hasArgument("peripheralReference")) {
String peripheralString = call.argument("peripheralReference");
if (peripheralString == null) {
result.error("Missing argument", "Missing argument 'peripheral'", null);
return;
}
Peripheral peripheral = peripheralMap.get(peripheralString);
if (peripheral == null) {
result.error("Invalid peripheral", "Invalid peripheral", null);
return;
}
result.success(peripheral.getModelName());
} else {
result.error("Missing argument", "Missing argument 'peripheralReference'", null);
}
}
private static void getUuid(MethodCall call, MethodChannel.Result result) {
if (call.hasArgument("peripheralReference")) {
String peripheralString = call.argument("peripheralReference");
if (peripheralString == null) {
result.error("Missing argument", "Missing argument 'peripheral'", null);
return;
}
Peripheral peripheral = peripheralMap.get(peripheralString);
if (peripheral == null) {
result.error("Invalid peripheral", "Invalid peripheral", null);
return;
}
result.success(peripheral.getUuid());
} else {
result.error("Missing argument", "Missing argument 'peripheralReference'", null);
}
}
}
The alternative way is to convert an object to a map in Android and back to an object in Flutter. Something like this:
Flutter/Dart:
class Device {
String? id;
String? name;
...
Device.fromMap(Map<String, dynamic> map) {
id = map['id'];
name = map['name'];
}
}
final map = await methodChannel.invokeMethod('requestDevice');
final device = Device.fromMap(map.cast<String, dynamic>());
Android/Kotlin:
data class Device(
val id: String,
val name: String?
) {
...
fun toMap(): Map<String, Any?> {
return mapOf(
"id" to id,
"name" to name
)
}
}
override fun onMethodCall(#NonNull call: MethodCall, #NonNull result: Result) {
...
result.success(device.toMap())
...
}

Update row if references is exist, otherwise delete using spring boot

Need guideline -
How to do hard delete when no reference is available and do soft delete when reference is available, this operation should be performed in a single method itself.
E.g.
I have 1 master table and 3 transactional tables and the master reference is available in all 3 transactional tables.
Now while deleting master row - I have to do the following: If master reference is available then update the master table row and if no master ref. is available delete the row.
I tried following so far.
Service Implementation -
public response doHardOrSoftDelete(Employee emp) {
boolean flag = iMasterDao.isDataExist(emp);
if(flag) {
boolean result = iMasterDao.doSoftDelete(emp);
} else {
boolean result = iMasterDao.doHardDelete(emp);
}
}
Second Approach:
As we know that while deleting a record if the reference is available then it throws ConstraintViolationException so simply we can catch it and check that caught exception is of type ConstraintViolationException or not, if yes then call doSoftDelete() method and return the response. So here you don't need to write method or anything to check the references. But I'm not sure whether it is the right approach or not. Just help me with it.
Here is what I tried again -
public Response deleteEmployee(Employee emp) {
Response response = null;
try{
String status= iMasterDao.deleteEmployeeDetails(emp);
if(status.equals("SUCCESS")) {
response = new Response();
response.setStatus("Success");
response.setStatusCode("200");
response.setResult("True");
response.setReason("Record deleted successfully");
return response;
}else {
response = new Response();
response.setStatus("Fail");
response.setStatusCode("200");
response.setResult("False");
}
}catch(Exception e){
response = new Response();
Throwable t =e.getCause();
while ((t != null) && !(t instanceof ConstraintViolationException)) {
t = t.getCause();
}
if(t instanceof ConstraintViolationException){
boolean flag = iMasterDao.setEmployeeIsDeactive(emp);
if(flag) {
response.setStatus("Success");
response.setStatusCode("200");
response.setResult("True");
response.setReason("Record deleted successfully");
}else{
response.setStatus("Fail");
response.setStatusCode("200");
response.setResult("False");
}
}else {
response.setStatus("Fail");
response.setStatusCode("500");
response.setResult("False");
response.setReason("# EXCEPTION : " + e.getMessage());
}
}
return response;
}
Dao Implementation -
public boolean isDataExist(Employee emp) {
boolean flag = false;
List<Object[]> tbl1 = session.createQuery("FROM Table1 where emp_id=:id")
.setParameter("id",emp.getId())
.getResultList();
if(!tbl1.isEmpty() && tbl1.size() > 0) {
flag = true;
}
List<Object[]> tbl2 = session.createQuery("FROM Table2 where emp_id=:id")
.setParameter("id",emp.getId())
.getResultList();
if(!tbl2.isEmpty() && tbl2.size() > 0) {
flag = true;
}
List<Object[]> tbl3 = session.createQuery("FROM Table3 where emp_id=:id")
.setParameter("id",emp.getId())
.getResultList();
if(!tbl3.isEmpty() && tbl3.size() > 0) {
flag = true;
}
return flag;
}
public boolean doSoftDelete(Employee emp) {
empDet = session.get(Employee.class, emp.getId());
empDet .setIsActive("N");
session.update(empDet);
}
public boolean doHardDelete(Employee emp) {
empDet = session.get(Employee.class, emp.getId());
session.delete(empDet);
}
No matter how many transactional tables will be added with master tbl reference, my code should do the operations(soft/hard delete) accordingly.
In my case, every time new transactional tables get added with a master reference I've do the checks, so Simply I want to skip the isDataExist() method and do the deletions accordingly, how can I do it in a better way?
Please help me with the right approach to do the same.
There's a lot of repeated code in the body of isDataExist() method which is both hard to maintain and hard to extend (if you have to add 3 more tables the code will double in size).
On top of that the logic is not optimal as it will go over all tables even if the result from the first one is enough to return true.
Here is a simplified version (please note that I haven't tested the code and there could be errors, but it should be enough to explain the concept):
public boolean isDataExist(Employee emp) {
List<String> tableNames = List.of("Table1", "Table2", "Table3");
for (String tableName : tableNames) {
if (existsInTable(tableName, emp.getId())) {
return true;
}
}
return false;
}
private boolean existsInTable(String tableName, Long employeeId) {
String query = String.format("SELECT count(*) FROM %s WHERE emp_id=:id", tableName);
long count = (long)session
.createQuery(query)
.setParameter("id", employeeId)
.getSingleResult();
return count > 0;
}
isDataExist() contains a list of all table names and iterates over these until the first successful encounter of the required Employee id in which case it returns true. If not found in any table the method returns false.
private boolean existsInTable(String tableName, Long employeeId) is a helper method that does the actual search for employeeId in the specified tableName.
I changed the query to just return the count (0 or more) instead of a the actual entity objects as these are not required and there's no point to fetch them.
EDIT in response to the "Second approach"
Is the Second Approach meeting the requirements?
If so, then it is a "right approach" to the problem. :)
I would refactor the deleteEmployeeDetails method to either return a boolean (if just two possible outcomes are expected) or to return a custom Enum as using a String here doesn't seem appropriate.
There is repeated code in deleteEmployeeDetails and this is never a good thing. You should separate the logic which decides the type of the response from the code that builds it, thus making your code easier to follow, debug and extend when required.
Let me know if you need a code example of the ideas above.
EDIT #2
Here is the sample code as requested.
First we define a Status enum which should be used as return type from MasterDao's methods:
public enum Status {
DELETE_SUCCESS("Success", "200", "True", "Record deleted successfully"),
DELETE_FAIL("Fail", "200", "False", ""),
DEACTIVATE_SUCCESS("Success", "200", "True", "Record deactivated successfully"),
DEACTIVATE_FAIL("Fail", "200", "False", ""),
ERROR("Fail", "500", "False", "");
private String status;
private String statusCode;
private String result;
private String reason;
Status(String status, String statusCode, String result, String reason) {
this.status = status;
this.statusCode = statusCode;
this.result = result;
this.reason = reason;
}
// Getters
}
MasterDao methods changed to return Status instead of String or boolean:
public Status deleteEmployeeDetails(Employee employee) {
return Status.DELETE_SUCCESS; // or Status.DELETE_FAIL
}
public Status deactivateEmployee(Employee employee) {
return Status.DEACTIVATE_SUCCESS; // or Status.DEACTIVATE_FAIL
}
Here is the new deleteEmployee() method:
public Response deleteEmployee(Employee employee) {
Status status;
String reason = null;
try {
status = masterDao.deleteEmployeeDetails(employee);
} catch (Exception e) {
if (isConstraintViolationException(e)) {
status = masterDao.deactivateEmployee(employee);
} else {
status = Status.ERROR;
reason = "# EXCEPTION : " + e.getMessage();
}
}
return buildResponse(status, reason);
}
It uses two simple utility methods (you can make these static or export to utility class as they do not depend on the internal state).
First checks if the root cause of the thrown exception is ConstraintViolationException:
private boolean isConstraintViolationException(Throwable throwable) {
Throwable root = throwable;
while (root != null && !(root instanceof ConstraintViolationException)) {
root = root.getCause();
}
return root != null;
}
And the second one builds the Response out of the Status and a reason:
private Response buildResponse(Status status, String reason) {
Response response = new Response();
response.setStatus(status.getStatus());
response.setStatusCode(status.getStatusCode());
response.setResult(status.getResult());
if (reason != null) {
response.setReason(reason);
} else {
response.setReason(status.getReason());
}
return response;
}
If you do not like to have the Status enum loaded with default Response messages, you could strip it from the extra info:
public enum Status {
DELETE_SUCCESS, DELETE_FAIL, DEACTIVATE_SUCCESS, DEACTIVATE_FAIL, ERROR;
}
And use switch or if-else statements in buildResponse(Status status, String reason) method to build the response based on the Status type.

How to Solve Deserialization error ask sdk

I'm attempting to convert the JSON output from my session and map it to a class that I've created using JAVA's ObjectMapper. When I run my tests on Lambda I get a Deserialisation error:
Deserialization error: com.amazon.ask.exception.AskSdkException
com.amazon.ask.exception.AskSdkException: Deserialization error
at com.amazon.ask.util.impl.JacksonJsonUnmarshaller.unmarshall(JacksonJsonUnmarshaller.java:50)
at com.amazon.ask.impl.AbstractSkill.execute(AbstractSkill.java:44)
at com.amazon.ask.AlexaSkill.execute(AlexaSkill.java:22)
at com.amazon.ask.SkillStreamHandler.handleRequest(SkillStreamHandler.java:71)
Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'AnswerIntent' as a subtype of [simple type, class com.amazon.ask.model.Request]: known type ids = [Alexa.Presentation.APL.UserEvent, AlexaHouseholdListEvent.ItemsCreated, AlexaHouseholdListEvent.ItemsDeleted, AlexaHouseholdListEvent.ItemsUpdated, AlexaHouseholdListEvent.ListCreated, AlexaHouseholdListEvent.ListDeleted, AlexaHouseholdListEvent.ListUpdated, AlexaSkillEvent.SkillAccountLinked, AlexaSkillEvent.SkillDisabled, AlexaSkillEvent.SkillEnabled, AlexaSkillEvent.SkillPermissionAccepted, AlexaSkillEvent.SkillPermissionChanged, AudioPlayer.PlaybackFailed, AudioPlayer.PlaybackFinished, AudioPlayer.PlaybackNearlyFinished, AudioPlayer.PlaybackStarted, AudioPlayer.PlaybackStopped, Connections.Request, Connections.Response, Display.ElementSelected, GameEngine.InputHandlerEvent, IntentRequest, LaunchRequest, Messaging.MessageReceived, PlaybackController.NextCommandIssued, PlaybackController.PauseCommandIssued, PlaybackController.PlayCommandIssued, PlaybackController.PreviousCommandIssued, SessionEndedRequest, System.ExceptionEncountered] (for POJO property 'request')
at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.amazon.ask.model.RequestEnvelope$Builder["request"])
at com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43)
at com.fasterxml.jackson.databind.DeserializationContext.invalidTypeIdException(DeserializationContext.java:1628)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownTypeId(DeserializationContext.java:1186)
at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._handleUnknownTypeId(TypeDeserializerBase.java:291)
at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._findDeserializer(TypeDeserializerBase.java:162)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedForId(AsPropertyTypeDeserializer.java:113)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:97)
at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserializeWithType(AbstractDeserializer.java:254)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeSetAndReturn(MethodProperty.java:151)
at com.fasterxml.jackson.databind.deser.BuilderBasedDeserializer.vanillaDeserialize(BuilderBasedDeserializer.java:269)
at com.fasterxml.jackson.databind.deser.BuilderBasedDeserializer.deserialize(BuilderBasedDeserializer.java:193)
at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3972)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2264)
at com.fasterxml.jackson.databind.ObjectMapper.treeToValue(ObjectMapper.java:2746)
at com.amazon.ask.util.impl.JacksonJsonUnmarshaller.unmarshall(JacksonJsonUnmarshaller.java:48)
... 3 more
I did checks to ensure that my "riddleItem" variable is not null. The JSON values are being mapped to the Person class which just returns properties of a person. The code is shown below and I've highlighted the line which the error occurs on:
public Optional<Response> handle(HandlerInput input) {
Map<String, Object> sessionAttributes = input.getAttributesManager().getSessionAttributes();
System.out.println("This a FIRST debug");
LOG.debug("This a FIRST debug");
boolean correctAnswer;
String speechText = null, response;
System.out.println("This a SECOND debug");
Map<String, String> riddleItem = (LinkedHashMap<String, String>)sessionAttributes.get(Attributes.RIDDLE_ITEM_KEY);
Person person;
// System.out.println("riddleItem " + riddleItem);
if(riddleItem != null)
{
person = MAPPER.convertValue(riddleItem, Person.class); // ERROR OCCURS ON THIS LINE
}
System.out.println("This a THIRD debug");
PersonProperty personProperty = PersonProperty.valueOf((String) sessionAttributes.get(Attributes.RIDDLE_PROPERTY_KEY));
int counter = (int) sessionAttributes.get(Attributes.COUNTER_KEY);
int riddleGameScore = (int) sessionAttributes.get(Attributes.RIDDLE_SCORE_KEY);
System.out.println("This a FOURTH debug");
IntentRequest intentRequest = (IntentRequest) input.getRequestEnvelope().getRequest();
correctAnswer = compareSlots(intentRequest.getIntent().getSlots(), getPropertyOfPerson(personProperty, person));
System.out.println("This a FIFTH debug " + correctAnswer);
if(correctAnswer)
{
riddleGameScore++;
response = getSpeechExpressionCon(true);
System.out.println("This a SIXTH debug " + response);
sessionAttributes.put(Attributes.RIDDLE_SCORE_KEY, riddleGameScore);
}
else
{
response = getSpeechExpressionCon(false);
System.out.println("This a SEVENTH debug " + response);
}
AnswerIntentHandler setup = new AnswerIntentHandler();
//
if(riddle.getAnswer() != null)
{
speechText = "Hello " + riddle.getAnswer();
}
return input.getResponseBuilder()
.withSimpleCard("RiddleSession", speechText)
.withSpeech(speechText)
.withShouldEndSession(true)
.build();
}
[Json Output of properties under "riddleItem" during Session]1
I know my the values being mapped aren't empty thus I'm at a complete loss of ideas as to what's going on as I've come up short with possible ideas as to what the problem might be.
I solved the problem as I came to realise that when mapping from JSON to a class, methods ('set' methods) for assigning the JSON values to the variables in the class must be created. A sample structure for example:
public class State {
public State() {}
public State(String name, String abbreviation, String capital, String statehoodYear, String statehoodOrder) {
this.name = name;
this.abbreviation = abbreviation;
this.capital = capital;
this.statehoodYear = statehoodYear;
this.statehoodOrder = statehoodOrder;
}
public String getName() {
return name;
}
public String getAbbreviation() {
return abbreviation;
}
public String getCapital() {
return capital;
}
public String getStatehoodYear() { return statehoodYear; }
public String getStatehoodOrder() {
return statehoodOrder;
}
public void setName(String name) {
this.name = name;
}
public void setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
}
public void setCapital(String capital) {
this.capital = capital;
}
public void setStatehoodYear(String statehoodYear) {
this.statehoodYear = statehoodYear;
}
public void setStatehoodOrder(String statehoodOrder) {
this.statehoodOrder = statehoodOrder;
}
}
The declaration of an empty constructor is necessary when making use of multiple constructors where, one is parametric. In some cases without the inclusion of such constructor an error may be thrown so, to avoid the possibility of said error, adding the constructor as a "Dummy" so to say, is essential.

Spring MVC #SessionAttributes

here's my code for the controller:
I have put my object in a map in the "doLogin" method below and I am trying to access it in my "logout" function but I am getting null value when I am trying to fetch value of my session attribute using "map.get(key)"
#Controller
#SessionAttributes(value={"session1"})
public class CredentialsController {
#Autowired
private Authentication authenticationDao;
#Autowired
private User userDao;
#RequestMapping(value="/start",method=RequestMethod.GET) //Default Method
public String doStart(#ModelAttribute CredentialsBean credentialsBean)
{
return "login";
}
#RequestMapping(value="/login",method=RequestMethod.GET) //Default Method
public String doLogin(#ModelAttribute CredentialsBean credentialsBean,Map<String,Object> map)
{
String result="";
if(credentialsBean!=null){
if(authenticationDao.authenticate(credentialsBean)){
String userType=authenticationDao.authorize(credentialsBean.getUserID());
if(userType.equalsIgnoreCase("A")){
CredentialsBean cBean= authenticationDao.changeLoginStatus(credentialsBean, 1);
map.put("session1",cBean); ----->Here I am putting the object inside a map .
result= "admin";
//map.put("username",credentialsBean.getProfileBean().getFirstName());
}
else{
CredentialsBean cBean=authenticationDao.changeLoginStatus(credentialsBean, 1);
map.put("session1",cBean.getUserID());
//System.out.println(cBean.getUserID());
result= "customer";
//map.put("username",credentialsBean.getProfileBean().getFirstName());
}
}
else{
result="ERROR";
}
}
return result;
}
#RequestMapping(value="/logout",method=RequestMethod.GET) //Default Method
public String doLogout(Map<String,Object > map)
{
CredentialsBean credentialsBean=(CredentialsBean)map.get("session1");
//System.out.println(userID);
System.out.println(credentialsBean.getUserID());
if(credentialsBean!=null){
if(userDao.logout(credentialsBean.getUserID())){
return "logout";
}
else{
return "error1";
}
}
else{
return "error";
}
}
}
Here is the way I would do it:
in your doLogin method you should add HttpSession session:
#RequestMapping(value="/login",method=RequestMethod.GET) //Default Method
public String doLogin(#ModelAttribute CredentialsBean credentialsBean, HttpSession session)
{
String result="";
if(credentialsBean!=null){
if(authenticationDao.authenticate(credentialsBean)){
String userType=authenticationDao.authorize(credentialsBean.getUserID());
if(userType.equalsIgnoreCase("A")){
CredentialsBean cBean= authenticationDao.changeLoginStatus(credentialsBean, 1);
// add object to session
session.setAttribute("session1",cBean);
result= "admin";
//map.put("username",credentialsBean.getProfileBean().getFirstName());
}
else{
CredentialsBean cBean=authenticationDao.changeLoginStatus(credentialsBean, 1);
session.setAttribute("session1",cBean);
result= "customer";
}
}
else{
result="ERROR";
}
}
return result;
}
Note, that you should add to session objects of the same type in order to safely retrieve it later (because now you added different objects cBean and cBean.getUserID() for the same key session1)
Then in your logout:
#RequestMapping(value="/logout",method=RequestMethod.GET) //Default Method
public String doLogout(HttpSession session)
{
CredentialsBean credentialsBean=(CredentialsBean)session.getAttribute("session1");
.....
}
But anyway, since you're implementing login\logout here I encourage you to learn more about Spring Security.

error play framework

Good evening, I have a problem with my web application in java app, I would like to create a new object "appuntamento", that object is also linked to another object "people." My idea is to initially choose a value for the "people" and then bring it back in the form editAppuntamento.
Here is the code of the controller object "appointment"
//show list people
public static Result scegliCliente(int page, String sortBy, String order, String filter, String filterNome, String filterTel, Long idApp) {
return ok(
scegliCliente.render(People.pagePeople(page, 25, sortBy, order, filter, filterNome, filterTel), sortBy, order, filter, filterNome, filterTel, idApp));
}
//redirect to method editappuntamento
public static Result sceltaCliente(Long idCliente, Long idApp) {
models.Appuntamento app = models.Appuntamento.find.byId(idApp);
People cliente = People.find.byId(idCliente);
app.cliente = cliente;
return redirect(
controllers.appuntamenti.routes.GestioneApp.editAppuntamento(idApp, idCliente)
);
}
//method edit appuntamento
public static Result editAppuntamento(Long idApp, Long idCliente) {
Form<Appuntamento> thisForm = Form.form(Appuntamento.class).fill(Appuntamento.find.byId(idApp));
return ok(
editAppuntamento.render(thisForm, idApp, idCliente)
);
}
//save object
public static Result saveAppuntamento(Long idAppuntamento, Long idCliente) {
Form<Appuntamento> thisForm = Form.form(Appuntamento.class).bindFromRequest();
if(thisForm.hasErrors()) {
Logger.debug("form: "+thisForm);
flash("error","Tipo e Data obbligatori.");
return badRequest(editAppuntamento.render(thisForm, idAppuntamento, idCliente));
}
People people = People.find.byId(idCliente);
Appuntamento appuntamento = thisForm.get();
appuntamento.cliente = people;
if(idAppuntamento == 0){
appuntamento.save();
}else{
appuntamento.update();
}
return redirect( controllers.appuntamenti.routes.GestioneApp.list(0,"","","","",""));
}
what is wrong?
thanks so much

Categories