#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?
Related
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!
To attribute Map below in a class that i want to save and read from Dyanmodb, using DynamoDBMapper.
Map<String, Map<String, Transition>> twf;
public class Transition {
public String fst;
public Permission pm;
public List<Action> ac;
}
public class Action {
private String mdl;
private String dsc;
private String nm;
// email address or any other data
private Map<String, String> data;
}
i have tried DynamoDBTypeConverted to convert to String, that results in json string that has " escaped as \" and unreadable in dyanmodb. I wanted to store as json
I implemented with understanding that Dyanmodb supports Map, but i still get error :
Exception processing message: not supported; requires #DynamoDBTyped or #DynamoDBTypeConverted
public class TimeSheetWorkFlowConverter implements
DynamoDBTypeConverter<Map<String, Object>, Map<String, Map<String, Transition>>> {
#Override
public Map convert(Map<String, Map<String, Transition>> object) {
// Map obj = mapper.readValue(object, Map.class);
String newJson = null;
Map objectJson = null;
try {
newJson = mapper.writeValueAsString(object);
objectJson = mapper.readValue(newJson, Map.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return objectJson;
}
#SuppressWarnings("unchecked")
#Override
public Map<String, Map<String, Transition>> unconvert(Map<String, Object> object) {
Map<String, Map<String, Transition>> wf = new HashMap<>();
if (object != null && !object.isEmpty())
for (Entry<String, Object> entry : object.entrySet()) {
String key = entry.getKey();
Map<String, Transition> value = mapTransition(entry.getValue());
wf.put(key, value);
}
return wf;
}
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?
Hello I want to ask about web service, how to show values from database to Map<>?
here is my code
#GET
#Path("/jurusan/{kode_jurusan}")
#Produces(MediaType.APPLICATION_JSON)
public Map getMatkulByjurusan(#PathParam("kode_jurusan") String kode_jurusan){
Map<String, Object> rs = new HashMap<String, Object>();
rs.put("Pesan", "Berhasil");
System.out.println("Jurusan "+kode_jurusan);
try {
createConnection();
MyMap matkul =(MyMap) jt.queryObject("select matkul from tb_matkul where kode_jurusan = ?", new Object[] {kode_jurusan}, new MyMap());
closeConnection();
if(matkul != null){
rs.put("result", matkul);
}
} catch (Exception e) {
rs.put("Pesan", "Gagal karena : " +e.getMessage());
}
return rs;
}
}
but when I try to acess http://localhost:9090/Service/matkul/jurusan/40 I get the following message:
{"Pesan":"Gagal karena : Incorrect result size: expected 1, actual 14"}
this MyMap class
public class MyMap implements Serializable, RowMapper{
private static final long serialVersionUID = -8840406844877458198L;
public HashMap<String, Object> map = new HashMap<String, Object>();
public HashMap<String, Object> getMap() {
return map;
}
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
MyMap dto=new MyMap();
int rowCount = rs.getMetaData().getColumnCount();
for (int i = 1; i <= rowCount; i++) {
dto.map.put(rs.getMetaData().getColumnLabel(i), rs.getObject(i));
}
return dto;
}
public void put(String name, Object o){
map.put(name, o);
}
public Object get(String name){
return map.get(name);
}
public String getString(String name){
return (String)map.get(name);
}
public Integer getInt(String name){
return (Integer)map.get(name);
}
public Date getDate(String name){
return (Date)map.get(name);
}
public BigDecimal getBigDecimal(String name){
return (BigDecimal)map.get(name);
}
}
Use queryForList method instead queryObject.
you can find an example to map multiple rows to list using jdbcTemplate from here .
Looks like the problem is on the database query, as the exception says, the query is expecting only 1 row as result and it produces 14.
Moreover, depending on which framework are you using you should probably provide a way to serialize the MyMap class