Reputation: 48
I have one JSON file i am converting it to JAVA Object using Object Mapper as given below :-
String agentName = Request.getAgentName();
ObjectMapper mapper = new ObjectMapper();
agent = mapper.readValue(new File(agentName), Agent.class);
these is working fine, but the problem is, for each and every request i am converting json to java object, I want to do it one time when my web server starts. How can i do it, these is a rest application.
Upvotes: 0
Views: 119
Reputation: 48
I think these will work, i will create an object of agents class in my ServletContextListner class and under the method contextInitialized, i will create object of agents class by passing the list of all the agents.
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ipaylabs.eme.vo.main.Agent;
public class Agents {
private static Agents theInstance;
private static Map<String, Agent> AGENTS_MAP;
public Agents(String[] agentList) {
this.AGENTS_MAP = new HashMap<>();
for(String agentName : agentList) {
initAgent(agentName);
}
}
public Agent getAgent(String agentName) {
if (!AGENTS_MAP.containsKey(agentName)) {
initAgent(agentName);
}
return AGENTS_MAP.get(agentName);
}
private static void initAgent(String agentName) {
ObjectMapper mapper = new ObjectMapper();
Agent agent = null;
try {
agent = mapper.readValue(new File(agentName), Agent.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
AGENTS_MAP.put(agentName, agent);
}
}
Upvotes: 0
Reputation: 1688
This could be a possible solution using a Singleton class with a map holding all your agents initialized on request.
public class Agents {
private static Agents theInstance;
private final Map<String, Agent> AGENTS_MAP;
private Agents() {
this.AGENTS_MAP = new HashMap<>();
}
public static Agents getInstance() {
if (theInstance == null) {
theInstance = new Agents();
}
return theInstance;
}
public Agent getAgent(String agentName) {
if (!AGENTS_MAP.containsKey(agentName) {
initAgent(agentName);
}
return AGENTS_MAP.get(agentName);
}
// TODO handle errors
private static void initAgent(String agentName) {
ObjectMapper mapper = new ObjectMapper();
Agent agent = mapper.readValue(new File(agentName), Agent.class);
AGENTS_MAP.put(agentName, agent);
}
}
Upvotes: 1
Reputation: 4643
You can use @PostConstruct
to initialization of your variables:
@PostConstruct
public void initApplication() {
String agentName = Request.getAgentName();
ObjectMapper mapper = new ObjectMapper();
agent = mapper.readValue(new File(agentName), Agent.class);
}
Upvotes: 0