I have to convert the following NamedSqlParameterSource in Hibernate:-
final List<MenuActionMapping> menusList;
MapSqlParameterSource sqlParams = new MapSqlParameterSource();
menusList = namedParameterJdbcTemplate.query("call sp_proc()",sqlParams ,new RowMapper<MenuActionMapping>() {
#Override
public MenuActionMapping mapRow(ResultSet resultset, int i)
throws SQLException {
MenuActionMapping menuActionMapping=new MenuActionMapping();
menuActionMapping.setMenuKey(resultset.getString("KMM_MENU_KEY"));
menuActionMapping.setDisplayName(resultset.getString("KMM_DISPLAY_NAME"));
menuActionMapping.setMenuActionFlag(resultset.getInt("KMM_ACTION_FLAG"));
menuActionMapping.setMenuActive(resultset.getInt("KMM_ACTIVE"));
menuActionMapping.setMenuLevel(resultset.getInt("str_len"));
String str=resultset.getString("menu_actions");
String [] actions=str.split(",");
if(resultset.getInt("KRMM_ACTIVE")==1)
{
menuActionMapping.setActive(true);
}
else
{
menuActionMapping.setActive(false);
}
for(String strAct:actions)
{
if(strAct.equals("ADD"))
{
menuActionMapping.setAddCheckBox(true);
menuActionMapping.setAddCheckBoxDisabled("true");
}
if(strAct.equals("VIEW"))
{
menuActionMapping.setViewCheckBox(true);
menuActionMapping.setViewCheckBoxDisabled("true");
}
if(strAct.equals("DELETE"))
{
menuActionMapping.setDeleteCheckBox(true);
menuActionMapping.setDeleteCheckBoxDisabled("true");
}
if(strAct.equals("EDIT"))
{
menuActionMapping.setEditCheckBox(true);
menuActionMapping.setEditCheckBoxDisabled("true");
}
if(strAct.equals("DOWNLOAD"))
{
menuActionMapping.setDownloadCheckBox(true);
menuActionMapping.setDownloadCheckBoxDisabled("true");
}
}
return menuActionMapping;
}
});
System.out.println(menusList);
return menusList;
I dont have idea about how namedJdbcTemplate and Map Row Works so i am getting a Problem..
I also wrote alternate code in hibernate but it doesnt work:-
final List<MenuActionMapping> menusList;
Query query= getSession().createSQLQuery("call kyc.sp_proc()");
menusList=query.list();
System.out.println(menusList);
return menusList;
I think I am not setting MenuAction Mapping Object so how to achive the purpose?
Also I want to Manipulate the columns before setting it into the object how can i do it in hibernate....
The main code that is troubling me is this:-
String str=resultset.getString("menu_actions");
String [] actions=str.split(",");
if(resultset.getInt("KRMM_ACTIVE")==1)
{
menuActionMapping.setActive(true);
}
else
{
menuActionMapping.setActive(false);
}
for(String strAct:actions)
{
if(strAct.equals("ADD"))
{
menuActionMapping.setAddCheckBox(true);
menuActionMapping.setAddCheckBoxDisabled("true");
}
if(strAct.equals("VIEW"))
{
menuActionMapping.setViewCheckBox(true);
menuActionMapping.setViewCheckBoxDisabled("true");
}
if(strAct.equals("DELETE"))
{
menuActionMapping.setDeleteCheckBox(true);
menuActionMapping.setDeleteCheckBoxDisabled("true");
}
if(strAct.equals("EDIT"))
{
menuActionMapping.setEditCheckBox(true);
menuActionMapping.setEditCheckBoxDisabled("true");
}
if(strAct.equals("DOWNLOAD"))
{
menuActionMapping.setDownloadCheckBox(true);
menuActionMapping.setDownloadCheckBoxDisabled("true");
}
How to set mutiple attribute based in 1 column in hibernate...
namedJdbcTemplate helps you to reduce the boilerplate code like getting,closing connection etc while Row mapper helps you to iterate over returned result set and map it to desired Java class.
Check this http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/
Thanks To #Pratik on How to map columns in hibernate with class attributes?
I got the answer to my question i can achieve the same as row mappper of jdbc template in hibernate using BasicTransformerAdapter in hibernate. My code is as follows:-
final List<MenuActionMapping> menusList;
menusList = getSession().createSQLQuery("CALL kyc.sp_proc()").setResultTransformer(new BasicTransformerAdapter() {
private static final long serialVersionUID = 1L;
#Override
public Object transformTuple(Object[] tuple, String[] aliases)
{
MenuActionMapping menuActionMapping=new MenuActionMapping();
menuActionMapping.setMenuId((Integer)tuple[0]);
menuActionMapping.setMenuKey((String)tuple[1]);
menuActionMapping.setDisplayName((String)tuple[3]);
menuActionMapping.setMenuActionFlag((Integer)tuple[5]);
final Boolean b=(Boolean)tuple[6];
menuActionMapping.setMenuActive(b? 1 : 0);
final BigInteger big=(BigInteger) tuple[9];
menuActionMapping.setMenuLevel(big.intValue());
String str=(String)tuple[10];
String [] actions=str.split(",");
if(b==true)
{
menuActionMapping.setActive(true);
}
else
{
menuActionMapping.setActive(false);
}
for(String strAct:actions)
{
if(strAct.equals("ADD"))
{
menuActionMapping.setAddCheckBox(true);
menuActionMapping.setAddCheckBoxDisabled("true");
}
if(strAct.equals("VIEW"))
{
menuActionMapping.setViewCheckBox(true);
menuActionMapping.setViewCheckBoxDisabled("true");
}
if(strAct.equals("DELETE"))
{
menuActionMapping.setDeleteCheckBox(true);
menuActionMapping.setDeleteCheckBoxDisabled("true");
}
if(strAct.equals("EDIT"))
{
menuActionMapping.setEditCheckBox(true);
menuActionMapping.setEditCheckBoxDisabled("true");
}
if(strAct.equals("DOWNLOAD"))
{
menuActionMapping.setDownloadCheckBox(true);
menuActionMapping.setDownloadCheckBoxDisabled("true");
}
}
return menuActionMapping;
}
}).list();
Related
I have a class name HibernateSessionManager which have static method
public static HibernateSessionManager current;
I trying to mock
public Mbc_session getMBCSessionByGuid(String sessionGuid) {
try {
return HibernateSessionManager.current.withSession(hibernateSession -> {
return hibernateSession.get(Mbc_session.class, sessionGuid);
});
}
catch (Exception e) {
logger.error().logFormattedMessage(Constants.MBC_SESSION_GET_ERROR_STRING,
e.getMessage()); throw new DAOException(ErrorCode.MBC_1510.getCode(), ErrorCode.MBC_1510.getErrorMessage() + ",Operation: getMBCSessionByGuid");
}
}
i am using following function in #before
public static void initMocks(Session session) {
HibernateSessionManager.current = mock(HibernateSessionManager.class,Mockito.RETURNS_DEEP_STUBS);
HibernateTransactionManager.current = mock(HibernateTransactionManager.class,Mockito.RETURNS_DEEP_STUBS);
doCallRealMethod().when(HibernateTransactionManager.current).withTransaction(any(), any());
doCallRealMethod().when(HibernateSessionManager.current).withSession(any(Consumer.class));
// Mockito.when(HibernateSessionManager.current.withSession((Consumer<Session>) any(Function.class))).thenCallRealMethod();
when(HibernateSessionManager.current.getSession()).thenReturn(session);
}
My test case is following
#Test public void test_getMBCSessionByGuid() {
Mbc_session mbcSession = new Mbc_session();
String sessionGuid = "session GUID";
when(HibernateSessionManager.current.getSession()).thenReturn(session);
// when(sessionFactory.getCurrentSession()).thenReturn(session);
when(session.get(Mbc_session.class, sessionGuid)).thenReturn(mbcSession);
Mbc_session mbcSession2 = mbc_sessionDao.getMBCSessionByGuid(sessionGuid);
assertNull(mbcSession2);
}
it passed but coverage is not touching following code
return hibernateSession.get(Mbc_session.class, sessionGuid);
here is my withSession code
public void withSession(Consumer<Session> task) {
Session hibernateSession = getSession();
try {
task.accept(hibernateSession);
} finally {
HibernateSessionManager.current.closeSession(hibernateSession);
}
}
openSession
public Session getSession() {
Session threadCachedSession = threadSession.get();
if (threadCachedSession != null) {
if (!threadCachedSession.isOpen()) { throw new
IllegalStateException("Session closed outside of
HibernateSessionManager.");
}
return threadCachedSession;
} return sessionFactory.openSession();
}
Looking at the code and assuming it compiles, I believe the problem is that you have two withSession(...) methods and in the code posted you are trying to mock the wrong one. Here are their signatures:
// You should NOT mock this one
void withSession(Consumer<Session> task) {
...
}
// You should mock this one instead
Mbc_session withSession(Function<Session, Mbc_session> task) {
...
}
It was easy to guess as the getMBCSessionByGuid method contains the snippet below with the Function<Session, Mbc_session> being passed as an argument to withSession(...) instead of Consumer<Session>:
return HibernateSessionManager.current.withSession(hibernateSession -> {
// something is returned which means a Function is passed, not a Consumer
return hibernateSession.get(Mbc_session.class, sessionGuid);
});
As an easy fix, you can just add the following to the test:
doCallRealMethod().when(HibernateSessionManager.current).withSession(any(Function.class));
and remove the existing mock configuration with a Consumer:
doCallRealMethod().when(HibernateSessionManager.current).withSession(any(Consumer.class));
P.S. Just in case, I can easily reproduce the issue on my machine.
When I create the CustomCheckBoxGroup field, all options of the field are displayed. But if I select one or more options and then save them, they are not saved in Magnolia. I suspect that wrong dataProvider is initialized (JcrDatasource instead of OptionListProvider).
form:
properties:
checkboxGroup:
$type: customCheckBoxGroupField
What is wrong here?
public class CustomCheckBoxGroupFieldFactory<T> extends AbstractOptionGroupFieldFactory<CustomCheckBoxGroupFieldDefinition<T>, Set<T>> {
private final static String STORES = "stores";
public CustomCheckBoxGroupFieldFactory(
CustomCheckBoxGroupFieldDefinition<T> definition,
ComponentProvider componentProvider,
SelectFieldSupport<Set<T>> selectFieldSupport) {
super(definition, componentProvider, selectFieldSupport);
}
#Override
public CheckBoxGroup<T> createFieldComponent() {
CheckBoxGroup<T> items = new CheckBoxGroup<T>("Test");
items.setItems((Collection)(this.selectStores()));
items.setItemCaptionGenerator(
item -> ((Option) item).getName() //((Option) item).getLabel()
);
return items;
}
public HasValue<Set<T>> createField() {
return this.createFieldComponent();
}
private Collection<Option> selectStores() {
List<Option> options = new ArrayList<>();
try {
Session session = MgnlContext.getJCRSession(STORES);
Node parent = session.getNode("/");
for (Node storeNode : NodeUtil.getNodes(parent, NodeTypes.Content.NAME)) {
if (storeNode.hasProperty(PROPERTY_NAME_DISPLAY_NAME)) {
Option option = new Option();
option.setValue(storeNode.getIdentifier());
option.setLabel(storeNode.getProperty(PROPERTY_NAME_DISPLAY_NAME).getString());
option.setName(storeNode.getProperty(PROPERTY_NAME_DISPLAY_NAME).getString());
options.add(option);
}
}
} catch (RepositoryException e) {
log.error("Cannot preselect already configured workspaces.", e);
}
return options;
}
}
I have a method which does multiple validations which are dependent on earlier one. This is purely a REST Service with no form/frontend. e.g.
public Json processPayment(User user, Amount amount, CardData cardData) {
Json result = new Json();
Json userResult = validateUser(user);
if (userResult.isNotValid())
result.put("errorCode", userResult.get("errorCode");
result.put("message", userResult.get("message");
return result;
}
Merchant merchant = getMerchant(user);
Json merchantResult = validateMerchant(user);
if (merchantResult.isNotValid())
result.put("errorCode", merchantResult.get("errorCode");
result.put("message", merchantResult.get("message");
return result;
}
Json limitsResult = validateLimits(user, merchant, amount);
if (limitsResult.isNotValid())
result.put("errorCode", limitsResult.get("errorCode");
result.put("message", limitsResult.get("message");
return result;
}
// Like above there are few more steps.
.
.
.
// All validations are fine process transaction.
Json transactionResult = processTransaction(user, merchant, amount, cardData);
if (transactionResult.isNotValid())
result.put("errorCode", transactionResult.get("errorCode");
result.put("message", transactionResult.get("message");
} else {
result.put("message", "Transaction Successful");
result.put("referenceNumber, transactionResult.get("rrn");
}
return result;
}
In each step, if the results are invalid then it should return immediately with the error message otherwise continue to next step.
Due to multiple steps, this method has become too big and almost impossible to do unit testing.
I want to break this method into smaller ones. I have already moved all the business logic of each step into separate methods but still the flow remains in this big method.
Sonarlint CC is 47 which is a big worry.
Please suggest what would be the right approach to handle this.
Thank you.
Here is a little example which could be a solution for you.
The main idea is each validation step shares one common context. This context holds every information of your validation process.
Next you have a queue of validators. Each represents one validation step. A validator changes the context (like adding the merchant object), calls your validation methods and changes the result of the context if necessary.
The validation process itself just iterates over the queue looking for a failing validator.
Just run this code. Maybe it helps:
import java.util.*;
interface PaymentValidatorInterface {
public boolean validate(PaymentValidationContext context);
}
class PaymentValidationContext {
String result = "";
String user;
int cardData;
String merchant;
public PaymentValidationContext(String user, int cardData) {
this.user = user;
this.cardData = cardData;
}
}
class PaymentValidator {
public static boolean validateUser(PaymentValidationContext context) {
if (context.user == null) {
context.result += "User is wrong\n";
return false;
}
return true;
}
public static boolean validateMerchant(PaymentValidationContext context) {
context.merchant = context.user + "#" + context.cardData;
if (context.merchant.length() <= 3) {
context.result += "Marchant is wrong\n";
return false;
}
return true;
}
public static boolean finishValidation(PaymentValidationContext context) {
context.result += "Everything is fine.\n";
return true;
}
}
public class Processor {
private final static Queue<PaymentValidatorInterface> validators = new LinkedList<>();
static {
validators.add(PaymentValidator::validateUser);
validators.add(PaymentValidator::validateMerchant);
validators.add(PaymentValidator::finishValidation);
}
public String processPayment(String user, int cardData) {
PaymentValidationContext context = new PaymentValidationContext(user, cardData);
validators.stream().anyMatch(validator -> !validator.validate(context));
return context.result;
}
// For testing -------
public static void main(String[] args) {
Processor p = new Processor();
System.out.print(p.processPayment("Foobar", 1337)); // ok
System.out.print(p.processPayment(null, 1337)); // fails
System.out.print(p.processPayment("", 1)); // fails
}
}
You can write doValidation() function like the following.
private doValidation(Json validationResult, Json result) {
if (validationResult.isNotValid())
result.put("errorCode", validationResult.get("errorCode");
result.put("message", validationResult.get("message");
return false;//validation failed
}
return true;//validation passed
}
and Call this method from processPayment() method.
public Json processPayment(User user, Amount amount, CardData cardData) {
Json result = new Json();
if( !doAllValidations(user,amount,cardData, result) )
return result;
// All validations are fine process transaction.
Json transactionResult = processTransaction(user, merchant, amount, cardData);
if (transactionResult.isNotValid())
result.put("errorCode", transactionResult.get("errorCode");
result.put("message", transactionResult.get("message");
} else {
result.put("message", "Transaction Successful");
result.put("referenceNumber, transactionResult.get("rrn");
}
return result;
}
Finally you can move all validations to some other method if you want.
public bool doAllValidations(User user, Amount amount, CardData cardData, result) {
Json userResult = validateUser(user);
if (!doValidation(userResult, result))
return result;
Merchant merchant = getMerchant(user);
Json merchantResult = validateMerchant(user);
if (!doValidation(merchantResult, result))
return result;
Json limitsResult = validateLimits(user, merchant, amount);
if (!doValidation(limitsResult, result))
return result;
....
}
With Rhino 17R4, we can create properties in javascript using Object.defineProperty() method.
public class MyGlobalObject : org.mozilla.javascript.ScriptableObject
{
public static org.mozilla.javascript.Script ___compiledScript = null;
public MyGlobalObject()
{
org.mozilla.javascript.Context con = org.mozilla.javascript.Context.enter();
try
{
con.initStandardObjects(this);
string strScript = "Object.defineProperty(this,\r\n 'onload', \r\n{ set : function(val){this.set_onload(val);},\r\n get : function(){return this.get_onload();}, enumerable: true, configurable: true});";
this.defineFunctionProperties(new string[] { "set_onload", "get_onload" }, typeof(MyGlobalObject), org.mozilla.javascript.ScriptableObject.DONTENUM);
org.mozilla.javascript.Script sc = con.compileString(strScript, "", 1, null);
object result_onload = con.evaluateString(this, "this.onload == undefined;", "", 1, null); // make sure it is not defined.
Console.WriteLine("onload is undefined? : {0}", result_onload);
// Define Properties Now.
sc.exec(con, this);
con.evaluateString(this, "this.onload= function(){var t1 = 1;};", "", 1, null);
object onloadobjectXYZ = con.evaluateString(this, "this.onload;", "", 1, null); // get function now.
Console.WriteLine("Onload object : {0} is found", onloadobjectXYZ);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
org.mozilla.javascript.Context.exit();
}
private object __onloadFunction;
public object get_onload()
{
Console.WriteLine("get_onload() called!");
return this.__onloadFunction;
}
//[org.mozilla.javascript.annotations.JSSetter]
public void set_onload(object _val)
{
Console.WriteLine("set_onload() called!");
this.__onloadFunction = _val;
}
public override string getClassName()
{
return "Global";
}
}
How can I create FunctionObject which is identical to "onloadobjectXYZ" in pure rhino object operation (not by using script like'strScipt')? It seems that it may be able to create FunctionObject for setter and getter, but I could not find a good example. Does anyone know how to define properties?
Thank you in advance!
defineProperty with java Method setter / getter is slightly different from object.defineProprty()
this.defineProperty("onload", null, javaonloadGetMethod, javaonloadSetMethod, ScriptableObject.PERMANENT);
This works for me as a workaround.
Why localPlayerList gaves me an error? Thank You (my error is signed with localPlayerList
public OfflinePlayer findPlayer(String paramString)
{
Object localObject = this.plugin.getServer().getOfflinePlayer(paramString);
if(!((OfflinePlayer) localObject).hasPlayedBefore())
{
localObject = this.plugin.getServer().getPlayer(paramString);
}
if(localObject == null)
{
PlayerList localPlayerList = this.plugin.getPlayerList(true);
for(PlayerList.Entry localEntry : localPlayerList)
{
String str = paramString.toLowerCase();
if(localEntry.name.toLowerCase().startsWith(str))
{
localObject = this.plugin.getServer().getOfflinePlayer(localEntry.name);
break;
}
}
}
return (OfflinePlayer) localObject;
}
Judging by the PlayerList.Entry mentioned in the for loop, PlayerList probably implements java.util.Map, which means to iterate around the entries it should be called like this:
for(PlayerList.Entry localEntry : localPlayerList.entrySet())