If I'm getting empty session I need to setup some values to play the action class. So, here is the method
public SearchFilters getFilters() {
return (SearchFilters) getSession().get("Filters");
}
I would like to check the session, if it's null, then I need to set the some values over here.
public SearchFilters getFilters() {
if(getSession().get("Filters").equals(null)){
---- //How to set the values and return ?
}
return (SearchFilters) getSession().get("Filters");
}
Use the code:
public SearchFilters getFilters() {
if(getSession().get("Filters") == null){
//How to set the values
getSession().put("Filters", new Filters());
}
// and return.
return (SearchFilters) getSession().get("Filters");
}
assumed you have injected the session into the action via implementing SessionAware.
The value is a free hand object which contains no value, but you could create a constructor to it and pass the value directly.
getSession() will return a new session if an existing session is not found. So you don't need to worry about this one ever returning null. Take note though, there's no get() method under HttpSession, it's getAttribute().
So you can do this:
public SearchFilters getFilters() {
if(getSession().getAttribute("Filters") == null) {
getSession().setAttribute("Filters", new SearchFilters());
}
return (SearchFilters) getSession().getAttribute("Filters");
}
Related
I'm trying to make mock that should return different value if the argument had concrete class. I created tableVerificationService mock object and created these when conditions.
Mockito.when(tableVerificationService.verify(Mockito.any())).thenReturn(true);
Mockito.when(tableVerificationService.verify(Mockito.any(DTable.class))).thenReturn(false);
But now it returns false in any case, even if i pass another from DTable object.
If i change order of these two lines, it will return true in all cases. Is there any way to make correct behavior?
You can use .thenAnswer() or .then() (shorter) to have more control of the returned value.
An example might visualize this better.
Let's assume we want to mock the Java class:
public class OtherService {
public String doStuff(String a) {
return a;
}
}
... and we want to return "even" if the passed String is even and "uneven" otherwise.
By using .then() we get access to the InvocationOnMock and can access the passed argument. This helps to determine the returned value:
class MockitoExampleTest {
#Test
void testMe() {
OtherService otherService = Mockito.mock(OtherService.class);
when(otherService.doStuff(ArgumentMatchers.anyString())).then(invocationOnMock -> {
String passedString = invocationOnMock.getArgument(0);
if (passedString.length() % 2 == 0) {
return "even";
} else {
return "uneven";
}
});
System.out.println(otherService.doStuff("duke")); // even
System.out.println(otherService.doStuff("egg")); // uneven
}
}
With this technique you can check the passed argument and determine if it's your concrete class and then return whatever value you want.
public GetChannelAccountRes getAccounts(GetChannelAccountReq request) {
LawAccountEntity account = new LawAccountEntity();
if(request.getTransactionCode().equals("yyyyyyy") && "1".equals(account.getAccountOwnerType())) {
UserParameter userParameter = userParameterRepository.findByGroupKeyAndKey("xxxxxxx","11111111");
}
return remoteChannelAccountInquiryService.getAccounts(request);
}
Hi, I have this code block. How can I add this userParameter value in request. I want to return something in if statement userParameter value and remoteChannelAccountInquiryService.getAccounts(request) value together.
Java, as a language, doesn't allow multiple return types, i.e. returning two values from the same method. If you want/have to return multiple things from the same method, you'll need to change your return type. The simplest would be to return a Map, i.e.
public Map<GetChannelAccountRes,UserParameter>getAccounts(GetChannelAccountReq request) {
Map<GetChannelAccountRes,UserParameter> map = new HashMap<>();
if (your condition) {
map.put(account, userParameter);
} else {
map.put(account, null); // or some other default value for userParameter
}
return map;
}
but then the caller would either have to iterate the map key/values, or know the key (i.e. the account)
Honestly, the better solution using Java would be to perform the if statement logic in its own method that returns UserParameter and then add the UserParameter as an optional argument to your existing method so that you're always only returning one object.
public UserParameter getUserParameter(GetChannelAccountReq request) {
UserParameter userParameter = null; // or some other default value
if(request.getTransactionCode().equals("yyyyyyy") &&
userParameter = "1".equals(account.getAccountOwnerType())) {
userParameterRepository.findByGroupKeyAndKey("xxxxxxx","11111111");
}
return userParameter;
}
public GetChannelAccountRes getAccounts(GetChannelAccountReq request, UserParameter... userParameter) {
if (userParameter[0] != null) {
// whatever logic that requires both request and userParameter goes here
}
return getChannelAccountRes
}
If the same caller calls both getUserParameter and getAccount, then it would have both objects, which is what I think you intend when you say you wanted both returned together. The varargs (...) parameter in getAccounts is a stylistic matter of taste, and is an array, which is why we check the first index for null. You can do the same thing without using var args like so.
public GetChannelAccountRes getAccounts(GetChannelAccountReq request) {
return getAccounts(request, null); // or some default value for UserParameter intstead of null
}
public GetChannelAccountRes getAccounts(GetChannelAccountReq request, UserParameter... userParameter) {
if (userParameter != null) {
// whatever logic that requires both request and userParameter goes here
}
return getChannelAccountRes
Using Spring cache abstraction, I want to cache the results of itemExists method calls. When an item is inserted by insertItem method, I want to put the value true in the cache.
class MyServiceImpl implements MyService {
private static final String CACHE_EXISTS_NAME = "existsCache";
#Override
#Cacheable(CACHE_EXISTS_NAME)
public boolean itemExists(Long id) {
// access the repository the check whether the item exists
}
#Override
#CachePut(cacheNames = CACHE_EXISTS_NAME, key = "#item.id")
public Item insertItem(Item item) {
...
}
}
How can I achieve what I need?
Its not supported. A work around could be to define #Cacheable on say your dao's finder method and then call it from itemExists method:
In the DAO:
#Cacheable(CACHE_EXISTS_NAME)
public Item findById(Long id) {
//..
}
In your service:
#Override
public boolean itemExists(Long id) {
if(null == dao.findById(id)) {
return false;
} else {
return true;
}
}
Note that since the method calls are proxied to support this, defining and calling finder inside the same object (service class in this case) will result in annotation being ignored.
I find your use case a bit disturbing. If you want to see if a particular item is in the cache, why don't you ask the cache rather than having those convoluted indirections? You could inject the Cache instance and asks for its content.
I guess that changing your code to the following might work but I really do not recommend that:
#Override
#CachePut(cacheNames = CACHE_EXISTS_NAME, key = "#item.id")
public boolean insertItem(Item item) {
...
return true;
}
I have a spring controller that I want a method to handle a certain request and then redirect to another one with keeping some value attached, so I will use RedirectAttributes on the first one and #ModalAttribute on the second, but the thing is I will not always have this modal attribute existing so I want to add it only if it exists.
#RequestMapping("/main")
public String getMain(Model model,HttpSession session,#ModalAttribute List<Loans> loansList){
if(session.getAttribute("user") != null){
if(session.getAttribute("current_start")!=null){
model.addAttribute("loans",loanDao.findAll((Integer) session.getAttribute("current_start")));
} else {
model.addAttribute("loans",loanDao.findAll(0));
session.setAttribute("current_start",0);
}
model.addAttribute("loan",new Loan());
model.addAttribute("countries",countryDao.findAll());
model.addAttribute("types",typeDao.findAll());
session.setAttribute("total_loans_number", loanDao.findCount());
return "main";
} else {
return "redirect:index";
}
}
and the redirecting one one is
#RequestMapping(value = "/search")
public String searchLoans(Model model,RedirectAttributes redirectAttributes,
#RequestParam String keyword){
redirectAttributes.addAttribute("loansList",loanDao.findAll(keyword));
return "redirect:/main";
}
but here the #ModalAttribute fails because it sometimes does not exist,sometimes I request main with out the loansList, how to make a condition to add it only if it exists ? or how to do this correctly ?
you can let spring populate your model attributes using #ModalAttribute annotation on methods:
#ModalAttribute("results")
public List<Loans> populateLoans() {
return new ArrayList<Loans>();
}
#RequestMapping("/main")
public String getMain(Model model,HttpSession session,#ModalAttribute("results") List<Loans> loansList){
if (CollectionUtils.isNotEmpty(loanList)) {
// do something if the loan list is not empty.
}
}
I have two classes
here's code
public class LoginServiceImplementation implements LoginService {
public boolean validateLogin(Login login)
{
LoginDao loginDao=DaoFactory.getLoginDao();
boolean b=loginDao.validateLogin(login);
System.out.println("id=="+login.getLoginId()+" uname=="+login.getuName()+" pass== "+login.getPassword());// values reset to null
return b;
}
}
public class LoginDaoImplementation implements LoginDao {
#Override
public Login validateLogin(Login login) {
Session session= Hibernate.getHibernateSession();
Query query= session.createQuery("from Login where uName= 'user' and password= 123");
//query.setParameter("uname", login.getuName());
//query.setParameter("pwd", login.getPassword());
//System.out.print(login.getuName());
//System.out.print(login.getPassword());
try
{
List<Login> logins=query.list();
System.out.print(logins.size());
if(logins.size()>0)
{
Login l=new Login();
l=logins.get(0);
login=l;
System.out.println("id=="+login.getLoginId()+" uname=="+login.getuName()+" pass== "+login.getPassword());/// ALL values getting printed
return login;
}
session.close();
return null;
}
catch(HibernateException x)
{
x.printStackTrace();
session.close();
return null;
}
}
}
when calling validatemethod of DaoImplementation class from serviceImplementation class, DaoImplementation class sets the values in the login object which is passed as parameter, but in serviceimplementation class i'm getting same old object with all values set to null.
Please reply with reason and solution.
thank you
login=l;
That does not work. You are just assigning a new object to the local variable login. This has no effect on the object that was previously stored in that variable (and that is visible to the outside world). Java does not support pass-by-reference, so you cannot re-assign variables outside of your scope.
You need to either copy all the data into that object (using setters), or (my preference) return a Login object from the method that the caller can use. (It is not clear if you are already doing that, part of the sample seems to return boolean, part seems to return a Login object).