My problem is as follows:
My service loops over items that are passed as args. For each item, i make two calls. My first price call gives me 9999 which means nothing was returned. That's fine - that's possible. My stock call works perfectly and i get the correct stock value returned. On the second iteration, my price call returns the same value as the previous stock call.
So, i get 9999 for price, then 150 for stock, then 150 for price. What's throwing me is that the price out parm is 6th, whereas the stock out parm is 8th. No idea how it would retain that value in a different position.
It seems that my jdbctemplate isn't being cleared or it's storing previous out params. Here's the code involved:
MyService.java
#Service
public class MyService extends BaseService implements MyInterface{
protected static final Logger logger = LoggerFactory.getLogger(MyService.class);
#Autowired
private MyDAO myDAO;
public myResponse checkOrder(args...)
{
for(something in args){
// PRICE
// Grab price data
LinkedHashMap<String, Object> priceCallInParams = new LinkedHashMap<String, Object>();
priceCallInParams .put("param1", "param1val");
priceCallInParams .put("param2", "param2val");
priceCallInParams .put("param3", "param3val");
priceCallInParams .put("param4", "param4val");
priceCallInParams .put("param5", "param5val");
LinkedHashMap<String, Object> priceCallOutParams = new LinkedHashMap<String, Object>();
priceCallOutParams .put("price", "0");
logger.debug("Getting data...");
Map<String, Object> priceData = new HashMap<String, Object>();
priceData = myDAO.checkPrice(priceCallInParams , priceCallOutParams );
BigDecimal unitPrice = new BigDecimal(9999);
if (!priceData .get("PRCE").toString().trim().equals("")){
unitPrice = new BigDecimal(priceData.get("PRCE").toString().trim());
}
System.out.println("PRC - "+unitPrice);
// AVAILABLE STOCK
// Grab check stock data
LinkedHashMap<String, Object> checkStockInParms = new LinkedHashMap<String, Object>();
checkStockInParms.put("param1", "param1val");
checkStockInParms.put("param2", "param2val");
checkStockInParms.put("param3", "param3val");
checkStockInParms.put("param4", "param4val");
checkStockInParms.put("param5", "param5val");
checkStockInParms.put("param6", "param6val");
checkStockInParms.put("REQQTY", "123");
LinkedHashMap<String, Object> checkStockOutParms = new LinkedHashMap<String, Object>();
checkStockOutParms .put("AVAILQTY", "0");
checkStockOutParms .put("NEXTDUE"," ");
checkStockOutParms .put("NEXTQTY","0");
logger.debug("Getting data...");
Map<String, Object> checkStockDat = new HashMap<String, Object>();
checkStockDat = myDAO.checkStock(checkStockInParms , checkStockOutParms );
// Output quantity
int AvailQTY = Integer.valueOf(checkStockDat.get("AVAILQTY").toString().trim());
if (reqBIT.getRequestedQuantity()>AvailQTY) {
resBIT.setConfirmedQuantity(AvailQTY);
}
else {
resBIT.setConfirmedQuantity(reqBIT.getRequestedQuantity());
}
}
}
}
MyDAO.java
#Component
public class MyDAO extends BaseDAO{
protected static final Logger logger = LoggerFactory.getLogger(OrderDAO.class);
public Map<String, Object> checkStock(LinkedHashMap<String, Object> inparms, LinkedHashMap<String, Object> outparms){
StringBuilder builtSQL = new StringBuilder();
builtSQL.append("CALL ");
builtSQL.append("checkstock ");
// just generates our param string (?,?,?...)
builtSQL.append(DataUtilities.genParmPlaceholderStringFromTotal(inparms.size()+outparms.size()));
return executeStoredProcedure(builtSQL.toString(), inparms, outparms);
}
public Map<String, Object> checkPrice(LinkedHashMap<String, Object> inparms, LinkedHashMap<String, Object> outparms){
logger.debug("CheckPrcc Initiated");
StringBuilder builtSQL = new StringBuilder();
builtSQL.append("CALL ");
builtSQL.append("checkprice ");
// just generates our param string (?,?,?...)
builtSQL.append(DataUtilities.genParmPlaceholderStringFromTotal(inparms.size()+outparms.size()));
return executeStoredProcedure(builtSQL.toString(), inparms, outparms);
}
}
BaseDAO.java
public class BaseDAO{
#Autowired
protected JdbcTemplate jdbcTemplate;
protected static final Logger logger = LoggerFactory.getLogger(BaseDAO.class);
protected Map<String, Object> executeStoredProcedure(String SQL, LinkedHashMap<String, Object> inParams, LinkedHashMap<String, Object> outParams){
Map<String, Object> result = new HashMap<String, Object>();
List<SqlParameter> declaredParameters = new ArrayList<SqlParameter>();
for (Map.Entry<String, Object> entry : inParams.entrySet()) {
declaredParameters.add(new SqlParameter(entry.getKey().toString(), Types.CHAR));
}
for (Map.Entry<String, Object> entry : outParams.entrySet()) {
declaredParameters.add(new SqlOutParameter(entry.getKey().toString(), Types.CHAR));
}
result = jdbcTemplate.call(new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection connection)
throws SQLException {
CallableStatement callableStatement = connection.prepareCall(SQL);
int index = 0;
for (Map.Entry<String, Object> entry : inParams.entrySet()) {
index++;
callableStatement.setString(index, entry.getValue().toString());
}
for (Map.Entry<String, Object> entry : outParams.entrySet()) {
index++;
callableStatement.registerOutParameter(index, Types.CHAR);
}
return callableStatement;
}
}, declaredParameters);
return result;
}
}
My service is invoked from my rest controller, which pass the args (if that matters).
I've been racking my brain and can't find any information regarding this issue. I'm new to spring boot and Java. I don't believe i'm doing something too egregious.
In our situation, this was being caused our i-series. If no data is present to return, the system still returns 10 chars from memory - being the last value it just returned. The solution is to always populate the return value to clear the memory.
Not spring-boot after all!
Related
I have a variable
Map<String,Object> parameters; in a class. When saved and loaded from mongo, if this Object is of type Set, it is converted to List. How to retain it as Set?
Edit:
Adding more context
public class Param{
Map<String,Object> parameters;
public Param(Map<String, Object> parameters) {
this.parameters = parameters;
}
public Map<String, Object> getParameters() {
return parameters;
}
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
}
Saving as below
Set<String> obj = new HashSet<>();
obj.add("ab");
obj.add("cd");
Map<String, Object> parameters = new HashMap<>();
parameters.put("12",obj);
Param param = new Param(parameters);
MongoTemplate mongotemplate = ....
mongotemplate.insert(param);
while reading
MongoTemplate mongotemplate = ....
Query query = ...
Param mongoparam = mongotemplate
.find(query, Param.class).get(0);
Set<String> obj = (Set) mongoparam.get("12")
last line is throwing error that Arraylist cannot be cast to Set
I am working on REST API service and each time when exception is occured I need to show in logs params , method and class name where this exception happened. So i have singleton class with method
public void log(final String className,String methodName,final Map<String,String> params,final String cause) {
final StringBuilder result=new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(entry.getKey()+" "+entry.getValue()+" ");
}
log.info("\n\t\t\tClass: "+className+"\n\t\t\t Method: "+methodName+"\n\t\t\t Params: "+result.toString()+" \n\t\t\t "+"Reason: "+cause);
}
Example of use
public String checkSession(String sid) {
final Map<String, String> params = new HashMap<String, String>();
params.put("sid", sid);
if (sid.isEmpty()) {
logger.log(this.getClass().getSimpleName(), "checkSession", params, " not valid session");
return Enums.Error.WRONG_SESSION.toString();
}
}
However in each method I need to initialize this map with all params. How can I write method that will return Map for all methods?
For example I have two methods
public String createPass(String name,String surname) {
final Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("surname", surname);
}
public String checkSession(String sid) {
final Map<String, String> params = new HashMap<String, String>();
params.put("sid", sid);
}
And method that I need is something like
public HashMap<String,String> method(String args...){
final Map<String, String> params = new HashMap<String, String>
for(...)
map.put("parameter","parameterName");
}
I think the best you can do here is something like this:
public Map<String,String> paramsToMap(String... params){
final Map<String, String> map = new HashMap<>();
for(int i=0; i<params.length-1; i=i+2) {
map.put(params[i], params[i+1]);
}
return map;
}
And you call it this way:
public String createPass(String name, String surname) {
final Map<String, String> params = paramsToMap("name", name, "surname", surname);
}
public String checkSession(String sid) {
final Map<String, String> params = paramsToMap("sid", sid);
}
I wish we could use reflection, however the parameter names are removed at compile time and you are left with arg0, arg1, etc ... So it is not possible to achieve what you want using reflection. You have to input the parameter names yourself.
Also as a side note, I think you would be better off using a Map<String, Object> and let the log method sort out how to print it out to the logs. Probably using String.valueOf()
public List<UMRDTO> getDocumentLink(Session session)
{
List<UMRDTO> documentationList = null;
Query query = null;
query = session.createQuery(UMRSQLInt.DOCUMENTATION_LIST);
documentationList = query.list();
return documentationList;
}
Whenever I restart my app all the hashmap are empty and no data is present that in inputed earlier
I need to get the list i.e objectName , objectType and the documentationLink from the above query and then put the data (objectName,documentationLink) in the HashMap if the objectName is Domainname then the data to be put in domainDocumentationMap or if it is combo then in domainComboDocumentationMap
private static Map<String, String> domainDocumentationMap = null;
private static Map<String, String> domainComboDocumentationMap = null;
static
{
domainDocumentationMap = new HashMap<String, String>();
domainComboDocumentationMap = new HashMap<String, String>();
}
public static Map<String, String> getDomainDocumentationMap(){
return domainDocumentationMap;
}
public static void setDomainDocumentationMap(String objectName, String documentationLink) {
MMTUtil.domainDocumentationMap.put(objectName, documentationLink);
}
what query shall i write?
#RequestMapping("/regressionTest")
public String home(Model model, #ModelAttribute CleanupTitles cleanupTitles) {
applicationToEnvStatus = MappingUtil
.getApplicationToEnvStatusMapping(databaseOperation);
model.addAttribute("parameters", new Parameters());
model.addAttribute("cleanupTitle", cleanupTitles);
cleanupTitles.setTitles(databaseOperation.getTitle());
return "home";
}
MappingUtil class
public class MappingUtil {
private enum Environment {
dev, stage, prod
}
private static Map<String, String> applicationToStatus;
private static Map<String, List<String>> applicationToEnvStatus;
public static Map<String,List<String>> getApplicationToEnvStatusMapping(
DatabaseOperation databaseOperation) {
applicationToStatus = new HashMap<String, String>();
applicationToEnvStatus = new HashMap<String, List<String>>();
for (Environment e : Environment.values()) {
System.out.println(e.toString());
applicationToStatus = databaseOperation
.getApplicationToEnvMapping(e.toString());
for (Map.Entry<String, String> entry : applicationToStatus
.entrySet()) {
List<String> li = new ArrayList<String>();
li.add(e.toString());
li.add(entry.getValue());
applicationToEnvStatus.put(entry.getKey(), li);
}
//System.out.println(e.toString() + " " + applicationToStatus);
}
System.out.println(applicationToEnvStatus);
return applicationToEnvStatus;
}
Database call
public Map<String, String> getApplicationToEnvMapping(String envName) {
String sqlQuery = "select application_name,is_completed from (select application_name,is_completed from rtf_run_status where env='"
+ envName + "' order by date_created desc) where rownum<=3";
Map<String, String> applicationToStatus = new HashMap<String, String>();
jdbcTemplate.query(sqlQuery, new ResultSetExtractor<Map>() {
#Override
public Map extractData(ResultSet rs) throws SQLException,
DataAccessException {
while (rs.next()) {
applicationToStatus.put(rs.getString("application_name"),
rs.getString("is_completed"));
}
return applicationToStatus;
}
});
return applicationToStatus;
}
The controller is making 2 db calls to: a) MappingUtil.getApplicationToEnvStatus() and b) cleanupTitles.setTitles(). This results in view taking a lot of time to load. The result set returned from each query is around 4-5.
What would be the best approach to load view at a faster response time? Should I execute db calls in a new Thread or is there any better way of doing this?
I am trying to create a TreeMap with a generic type but I am unable to. I am doing this because my map can like these:
Map<String, QueryTerm> terms = new TreeMap<String, QueryTerm>();
Map<String, String> params = new TreeMap<String, String>();
So instead of creating multiple functions to handle the maps with different types I want to create one which both types.
How can I do this and what am I doing wrong?
Function:
private Map<String, ? extends Object> setDatumMap(UserSession session, String parameterName)
{
Map<String, ? extends Object> map = new TreeMap<String, ? extends Object>();
//Get comma delimited list of filter keys. Split them and use them to retrieve associated values.
String sFilters = (String) session.getAttribute(parameterName);
String[] filterList = sFilters.split(",");
for(String filterName : filterList)
{
String filterValue = (String) session.getAttribute(filterName);
if (filterValue != null && !filterValue.isEmpty())
{
filter.put(filterName, setQueryTermList(filterValue, ListType.BOOLEAN_LIST));
}
}
return filter;
}
You should simply instantiate the map like so:
Map<String, Object> map = new TreeMap<String, Object>();
You can't instantiate using a wildcard, and it's not necessary unless you expect that the compiler will cast to the appropriate class by guessing what value you are going to get. We didn't get there yet.
you need to change you this line :
private Map<String, ? extends Object> setDatumMap(UserSession session, String parameterName)
{
Map<String, ? extends Object> map = new TreeMap<String, ? extends Object>();
//rest of your code
To
private Map<String, Object> setDatumMap(UserSession session, String parameterName)
{
Map<String, Object> map = new TreeMap<String, Object>();
//rest of your code.
This will work.