Retrieving records from a hashmap - java

I have 2 forms , one form for registration and other form for searching records,deleting,etc.
In the registration form i put the registration details in to an object and then store it in a hashmap. In the second form i access the hashmap to delete ,search records according to the id saved(Key).
My problem is when i save a record and access it from the second form (access the hashmap), i get null pointer exception. (I get null pointer exception , even if i have a record saved to the searched key)
Here is what i have done:
Registration form code :
Maps storage=new Maps();
private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {
try{
String firstName=txtFirstName.getText();
String initials=txtInitials.getText();
String birthDay=cmbBirthDay.getSelectedItem().toString();
String birthMonth=cmbBirthMonth.getSelectedItem().toString();
String birthYear=txtBirthYear.getText();
String Gender=cmbGender.getSelectedItem().toString();
String address=txtAddress.getText();
String tele=txtTele.getText();
String membershipType="";
String paymentType="";
String memberid=txtMemberId.getText();
if(rbPlatinum.isSelected());{
membershipType=rbPlatinum.getText();
}
if(rbGold.isSelected());
{
membershipType=rbGold.getText();
}
if(rbSilver.isSelected());
{
membershipType=rbSilver.getText();
}
if(rbAnually.isSelected());{
paymentType=rbAnually.getText();
}
if(rbSemi.isSelected());{
paymentType=rbSemi.getText();
}
if(rbMonthly.isSelected());{
paymentType=rbMonthly.getText();
}
Members newMember=new Members(firstName,initials,birthDay,birthMonth,birthYear,Gender,memberid,address,tele,membershipType,paymentType);
storage.setMemberMap(memberid, newMember);
JOptionPane.showMessageDialog(frame,"Successfully Registered");
}catch(Exception e){
JOptionPane.showMessageDialog(frame,"ERROR!");
e.getStackTrace();
}
}
Here is the Maps Class(All the maps are in this class) :
public class Maps {
public Maps(){}
Map<String,Members> memberMap=new HashMap();
//returns the memberMap
public Map<String, Members> getMemberMap() {
return memberMap;
}
//add items to map
public void setMemberMap(String key,Members object) {
memberMap.put(key,object);
}
}
Here is the code which i use in the second form to search a record :-
Maps storage=new Maps();
private void btnSearchMemberActionPerformed(java.awt.event.ActionEvent evt) {
String memberID=txtSearchId.getText();
//get the record and display
txtArea.setText(storage.getMemberMap().get(memberID).toString());
}
What seems to be the problem here ?
Thank you for your time.

You are creating Maps storage=new Maps(); in both the forms. Maps has
Map<String,Members> memberMap=new HashMap();
as non static field. So whenever you create a new Maps() it will create a new memberMap inside.
An alternative would be have memberMap as static (shared variable) and provide static access methods to them
public class Maps {
private static Map<String,Members> memberMap=new HashMap<>();
public static Map<String, Members> getMemberMap() {
return memberMap;
}
public static void setMemberMap(String key,Members object) {
memberMap.put(key,object);
}
}
In this way, you can add items in one form
Maps.setMemberMap(memberid, newMember);
And get the same value from other form
Maps.getMemberMap().get(memberID);
Remember-
private static objects are not garbage collected, unless the holder class gets GCd. So unwanted items should be manually removed from the map, time to time.

Related

Printing all data from HashMap

The code looks like this.
public class Album {
public String currentTitle;
public HashMap<String, List<Music>> albumList = new HashMap<String, List<Music>>();
//setting the album's title
public Album(String albumTitle) {
this.currentTitle = albumTitle; //represents object's name
albumList.put(currentTitle, null);
}
//add music to album
public void addMusicToThis(Music music) {
//only if value is empty
if(albumList.get(currentTitle) == null) {
albumList.put(currentTitle, new ArrayList<Music>());
}
albumList.get(currentTitle).add(music);
}
public void printMusicList() {
}
}
and I want to print all values for the specific album, like
Album album = new Album("Test1");
Album album2 = new Album("Test2");
album.addMusicToThis(something); //this code works fine
album2.addMusicToThis(something2);
album.printMusicList(); //maybe "something"
album2.printMusicList(); //maybe "something2"
but the hashMap's values are all set to List, and I can't find the way to print the musics out.
And assume that music's name is all set.
You just get the list for a particular string, and iterate it
for(Music m : albumList.get(this.currentTitle)) {
System.out.println(m.getName());
}
It's not really clear why you're using a Hashmap, though. Your key can never change.
You must iterate over the obtained list and print the individual entries
In Java 8 you can,
albumList.get(currentTitle).forEach((music) -> System.out.println(musice.getRequiredDetails)})
You can call albumList.entrySet() which is actually iterable, traverse it and print it however you like
I think you should add the albumTitle as an argument of the printMusicList function.
For example
public void printMusicList(String albumTitle) {
List<Music> musics = albumList.get(albumTitle);
for (Music music : musics) {
System.out.println(music);
}
}
or if you want to print it all
public void printMusicList() {
Set<String> keys = albumList.keySet();
for (String key : keys) {
List<Music> musics = albumList.get(key);
for (Music music : musics) {
System.out.println(music);
}
}
}

EhCache cached object modification

I've to implement caching with EhCache. Basic requirement is, I have to keep that cached object for fixed interval ( for now 1 hours in code below). So, I implemented the code as below:
Sample domain object:
import lombok.*;
#Getter
#Setter
#ToString
#AllArgsConstructor
public class City implements Serializable {
public String name;
public String country;
public int population;
}
Cache manager class:
import net.sf.ehcache.*;
public class JsonObjCacheManager {
private static final Logger logger = LoggerFactory.getLogger(JsonObjCacheManager.class);
private CacheManager manager;
private Cache objectCache;
public JsonObjCacheManager(){
manager = CacheManager.create();
objectCache = manager.getCache("jsonDocCache");
if( objectCache == null){
objectCache = new Cache(
new CacheConfiguration("jsonDocCache", 1000)
.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU)
.eternal(false)
.timeToLiveSeconds(60 * 60)
.timeToIdleSeconds(0)
.diskExpiryThreadIntervalSeconds(0)
.persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.LOCALTEMPSWAP)));
objectCache.disableDynamicFeatures();
manager.addCache(objectCache);
}
}
public List<String> getKeys() { return objectCache.getKeys();}
public void clearCache(){
manager.removeAllCaches();
}
public void putInCache(String key, Object value){
try{
objectCache.put(new Element(key, value));
}catch (CacheException e){
logger.error(String.format( "Problem occurred while putting data into cache: %s", e.getMessage()));
}
}
public Object retrieveFromCache(String key){
try {
Element element = objectCache.get(key);
if(element != null)
return element.getObjectValue();
}catch (CacheException ce){
logger.error(String.format("Problem occurred while trying to retrieveSpecific from cache: %s", ce.getMessage()));
}
return null;
}
}
It caches and retrieves the values very properly. But my requirement is, I must modify the object that I retrieve from cache for given key. What I'm getting is, if I modify the object that I retrieved from cache, then cached object for that key is also getting modified.
Below is the example:
public class Application {
public static void main(String[] args) {
JsonObjCacheManager manager = new JsonObjCacheManager();
final City city1 = new City("ATL","USA",12100);
final City city2 = new City("FL","USA",12000);
manager.putInCache(city1.getName(), city1);
manager.putInCache(city2.getName(), city2);
System.out.println(manager.getKeys());
for(String key: manager.getKeys()){
System.out.println(key + ": "+ manager.retrieveFromCache(key));
}
City cityFromCache = (City) manager.retrieveFromCache(city1.getName());
cityFromCache.setName("KTM");
cityFromCache.setCountry("NPL");
System.out.println(manager.getKeys());
for(String key: manager.getKeys()){
System.out.println(key + ": "+ manager.retrieveFromCache(key));
}
}
}
The output that I'm getting is:
[ATL, FL]
ATL: City(name=ATL, country=USA, population=12100)
FL: City(name=FL, country=USA, population=12000)
[ATL, FL]
ATL: City(name=KTM, country=NPL, population=12100)
FL: City(name=FL, country=USA, population=12000)
This means, whenever I'm retrieving and modifying the object for given key, it also being reflected in cached value.
What my requirement is, the cached object for given key should not be modified. Is there any way to achieve this? Or is it not correct way to implement EhCache? Or I'm missing some fundamental principle?
I'm using EhCache V2.10.3
Thank you!
When you use a cache that is storing its data on the heap and with direct object references, you need to copy the object before using it.
In general it is good practice not to mutate a value after handing over the object reference to the cache (or anybody else beyond your control).
Some caches do have a copy mechanism to protect the cached values from modification. E.g. in EHCache3 you can add copiers, see Serializers and Copiers.
Alternatively, change your design: When you have the need to mutate the value, maybe you can split the values into two objects, one that is caches, one that contains the data that needs mutating and make the latter containing the first.

Passing values from database in "allowableValues"?

I am using Swagger version 2 with Java Spring. I have declared a property and it works fine and it generates a drop down list of value I assigned.
#ApiParam(value = "Pass any one Shuttle provider ID from the list", allowableValues = "1,2,3,4,10")
private Long hotelId;
Now, I need a way to populate this list which is passed in allowableValues from my database as it could be random list as well as huge data. How can I assign list of values dynamically from database in this allowableValues?
This question is bit old, I too faced the same problem so thought of adding here which may help some one.
//For ApiModelProperty
#ApiModelProperty(required = true, allowableValues = "dynamicEnum(AddressType)")
#JsonProperty("type")
private String type;
Created a component which implements ModelPropertyBuilderPlugin
#Component
#Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1)
public class ApiModelPropertyPropertyBuilderCustom implements ModelPropertyBuilderPlugin {
private final DescriptionResolver descriptions;
#Autowired
public ApiModelPropertyPropertyBuilderCustom(DescriptionResolver descriptions) {
this.descriptions = descriptions;
}
public void apply(ModelPropertyContext context) {
try {
AllowableListValues allowableListValues = (AllowableListValues) FieldUtils.readField(context.getBuilder(),
"allowableValues", true);
if(allowableListValues!=null) {
String allowableValuesString = allowableListValues.getValues().get(0);
if (allowableValuesString.contains("dynamicEnum")) {
String yourOwnStringOrDatabaseTable = allowableValuesString.substring(allowableValuesString.indexOf("(")+1, allowableValuesString.indexOf(")"));
//Logic to Generate dynamic values and create a list out of it and then create AllowableListValues object
context.getBuilder().allowableValues(allowableValues);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean supports(DocumentationType delimiter) {
return SwaggerPluginSupport.pluginDoesApply(delimiter);
}
}
Similary for ApiParam we can create component which will implement ParameterBuilderPlugin
#Override
public void apply(ParameterContext context) {
#SuppressWarnings("Guava") final Optional<ApiParam> apiParam =
context.resolvedMethodParameter().findAnnotation(ApiParam.class);
if (apiParam.isPresent()) {
final String allowableValuesString = apiParam.get().allowableValues();
//Your logic here
context.parameterBuilder().allowableValues(allowableValues);
}
}
You need to create constructor in SwaggerConfiguration class.
#Autowire service and withdraw data you need from database
assign this to final variable
assign this final variable to allowableValues in annotation
enjoy not efficient api
private final String allowableValues;
public SwaggerConfiguration() {
List<YourEntitiy> list = someService.findAll();
//code to get every value you need and add create comma separated String
StringJoiner stringJoiner = new StringJoiner(",");
stringJoiner.add(list.get(0).getValue());
this.allowableValues = stringJoiner.toString();
}
#ApiParam(allowableValues = allowableValues)
But I think it's bad idea getting all ids from database just to create allowable values. Just validate in api method if that id exist and/or Create new api to get ids from database, use pagination from Spring Data project, like PageImpl<> javadocs

Java - Access Object's Array List through HashMap (Key is object)

I am trying to loop through a HashMap, then for each key I want to access the object (Shipment) that is associated to the key and access my array list for further analysis purposes. Each object/key in HashMap has the same array list (metricList). I cannot seem to access it, though I have checked the private/public thing. Can someone point me in the right direction?
I think I need to maybe get the class of my object and then use the method "getList"... I tried with no luck.
This is a sample of the code (removed irrelevant parts) if it helps:
This is my object:
public class Shipment{
//Members of shipment
private final String shipment;
public Date creationDate;
public int creationTiming;
public int processingTiming;
public ArrayList<Integer> metricList;
public void createArrayList() {
// create list
metricList = new ArrayList<Integer>();
// add metric to list
metricList.add(creationTiming);
metricList.add(processingTiming);
}
public ArrayList<Integer> getList() {
return metricList;
}
}
This is the class where I create a hashMap and run through different analysis:
public class AnalysisMain {
public static Map<String, Shipment> shipMap = new HashMap();
public static void main(String[] args) {
try {
... // Different calls to analysis
}
catch {}
}
}
This is where the issue occurs (it does not recognize that I already have a "metricList", asking if I want to create local variable)
public class Metric_Analysis{
public static void analyze() throws Exception{
ResultSet rs;
try {
rs = getSQL("SELECT * FROM TEST_METRICS");
}
catch(Exception e) {
//Pass the error
throw new java.lang.Exception("DB Error: " + e.getMessage());
}
Iterator<Map.Entry<String, Shipment>> iterator = shipMap.entrySet().iterator();
while(iterator.hasNext()){
Iterator<String> metricIterator = metricList.iterator();
//Above is the Array List I want to access and loop through
//I will then perform certain checked against other values on a table...
while (metricIterator.hasNext()) {
//I will perform certain things here
}
}
}
}
You need to get the List out of your Shipment.
You can access the object from the iterator with: iterator.next();
This will also set the pointer to the next Entry in your List/Map.
Change your code:
Iterator<Map.Entry<String, Shipment>> iterator = shipMap.entrySet().iterator();
while(iterator.hasNext()){
// Get the Entry from your Map and get the value from the Entry
Entry<String, Shipment> entry = iterator.next();
List<Integer> metricList = entry.getValue().getList();
Iterator<String> metricIterator = metricList.iterator();
//Above is the Array List I want to access and loop through
//I will then perform certain checked against other values on a table...
while (metricIterator.hasNext()) {
//I will perform certain things here
}
}

Cache in GWT app/widget with HTML5 localStorage

I am trying to incorporate a data cache for one of my GWT widgets.
I have a datasource interface/class which retrieves some data from my backend via RequestBuilder and JSON. Because I display the widget multiple times I only want to retrieve the data once.
So I tried to come with an app cache. The naive approach is to use a HashMap in a singleton object to store the data. However I also want to make use of HTML5's localStorage/sessionStorage if supported.
HTML5 localStorage only supports String values. So I have to convert my object into JSON and store as a string. However somehow I can't come up with a nice clean way of doing this. here is what I have so far.
I define a interface with two functions: fetchStatsList() fetches the list of stats that can be displayed in the widget and fetchStatsData() fetches the actual data.
public interface DataSource {
public void fetchStatsData(Stat stat,FetchStatsDataCallback callback);
public void fetchStatsList(FetchStatsListCallback callback);
}
The Stat class is a simple Javascript Overlay class (JavaScriptObject) with some getters (getName(), etc)
I have a normal non-cachable implementation RequestBuilderDataSource of my DataSource which looks like the following:
public class RequestBuilderDataSource implements DataSource {
#Override
public void fetchStatsList(final FetchStatsListCallback callback) {
// create RequestBuilderRequest, retrieve response and parse JSON
callback.onFetchStatsList(stats);
}
#Override
public void fetchStatsData(List<Stat> stats,final FetchStatsDataCallback callback) {
String url = getStatUrl(stats);
//create RequestBuilderRquest, retrieve response and parse JSON
callback.onFetchStats(dataTable); //dataTable is of type DataTable
}
}
I left out most of the code for the RequestBuilder as it is quite straightforward.
This works out of the box however the list of stats and also the data is retrieved everytime even tough the data is shared among each widget instance.
For supporting caching I add a Cache interface and two Cache implementations (one for HTML5 localStorage and one for HashMap):
public interface Cache {
void put(Object key, Object value);
Object get(Object key);
void remove(Object key);
void clear();
}
I add a new class RequestBuilderCacheDataSource which extends the RequestBuilderDataSource and takes a Cache instance in its constructor.
public class RequestBuilderCacheDataSource extends RequestBuilderDataSource {
private final Cache cache;
publlic RequestBuilderCacheDataSource(final Cache cache) {
this.cache = cache;
}
#Override
public void fetchStatsList(final FetchStatsListCallback callback) {
Object value = cache.get("list");
if (value != null) {
callback.fetchStatsList((List<Stat>)value);
}
else {
super.fetchStatsList(stats,new FetchStatsListCallback() {
#Override
public void onFetchStatsList(List<Stat>stats) {
cache.put("list",stats);
callback.onFetchStatsList(stats);
}
});
super.fetchStatsList(callback);
}
}
#Override
public void fetchStatsData(List<Stat> stats,final FetchStatsDataCallback callback) {
String url = getStatUrl(stats);
Object value = cache.get(url);
if (value != null) {
callback.onFetchStatsData((DataTable)value);
}
else {
super.fetchStatsData(stats,new FetchStatsDataCallback() {
#Override
public void onFetchStatsData(DataTable dataTable) {
cache.put(url,dataTable);
callback.onFetchStatsData(dataTable);
}
});
}
}
}
Basically the new class will lookup the value in the Cache and if it is not found it will call the fetch function in the parent class and intercept the callback to put it into the cache and then call the actual callback.
So in order to support both HTML5 localstorage and normal JS HashMap storage I created two implementations of my Cache interface:
JS HashMap storage:
public class DefaultcacheImpl implements Cache {
private HashMap<Object, Object> map;
public DefaultCacheImpl() {
this.map = new HashMap<Object, Object>();
}
#Override
public void put(Object key, Object value) {
if (key == null) {
throw new NullPointerException("key is null");
}
if (value == null) {
throw new NullPointerException("value is null");
}
map.put(key, value);
}
#Override
public Object get(Object key) {
// Check for null as Cache should not store null values / keys
if (key == null) {
throw new NullPointerException("key is null");
}
return map.get(key);
}
#Override
public void remove(Object key) {
map.remove(key);
}
#Override
public void clear() {
map.clear();
}
}
HTML5 localStorage:
public class LocalStorageImpl implements Cache{
public static enum TYPE {LOCAL,SESSION}
private TYPE type;
private Storage cacheStorage = null;
public LocalStorageImpl(TYPE type) throws Exception {
this.type = type;
if (type == TYPE.LOCAL) {
cacheStorage = Storage.getLocalStorageIfSupported();
}
else {
cacheStorage = Storage.getSessionStorageIfSupported();
}
if (cacheStorage == null) {
throw new Exception("LocalStorage not supported");
}
}
#Override
public void put(Object key, Object value) {
//Convert Object (could be any arbitrary object) into JSON
String jsonData = null;
if (value instanceof List) { // in case it is a list of Stat objects
JSONArray array = new JSONArray();
int index = 0;
for (Object val:(List)value) {
array.set(index,new JSONObject((JavaScriptObject)val));
index = index +1;
}
jsonData = array.toString();
}
else // in case it is a DataTable
{
jsonData = new JSONObject((JavaScriptObject) value).toString();
}
cacheStorage.setItem(key.toString(), jsonData);
}
#Override
public Object get(Object key) {
if (key == null) {
throw new NullPointerException("key is null");
}
String jsonDataString = cacheStorage.getItem(key.toString());
if (jsonDataString == null) {
return null;
}
Object data = null;
Object jsonData = JsonUtils.safeEval(jsonDataString);
if (!key.equals("list"))
data = DataTable.create((JavaScriptObject)data);
else if (jsonData instanceof JsArray){
JsArray<GenomeStat> jsonStats = (JsArray<GenomeStat>)jsonData;
List<GenomeStat> stats = new ArrayList<GenomeStat>();
for (int i = 0;i<jsonStats.length();i++) {
stats.add(jsonStats.get(i));
}
data = (Object)stats;
}
return data;
}
#Override
public void remove(Object key) {
cacheStorage.removeItem(key.toString());
}
#Override
public void clear() {
cacheStorage.clear();
}
public TYPE getType() {
return type;
}
}
The post got a little bit long but hopefully clarifies what I try to reach. It boils down to two questions:
Feedback on the design/architecture of this approach (for example subclassing RequestBilderDataSource for cache function, etc). Can this be improved (this is probably more related to general design than specifically GWT).
With the DefaultCacheImpl it is really easy to store and retrieve any arbitrary objects. How can I achieve the same thing with localStorage where I have to convert and parse JSON? I am using a DataTable which requires to call the DataTable.create(JavaScriptObject jso) function to work. How can I solve this without to many if/else and instance of checks?
My first thoughts: make it two layers of cache, not two different caches. Start with the in-memory map, so no serialization/deserialization is needed for reading a given object out, and so that changing an object in one place changes it in all. Then rely on the local storage to keep data around for the next page load, avoiding the need for pulling data down from the server.
I'd tend to say skip session storage, since that doesn't last long, but it does have its benefits.
For storing/reading data, I'd encourage checking out AutoBeans instead of using JSOs. This way you could support any type of data (that can be stored as an autobean) and could pass in a Class param into the fetcher to specify what kind of data you will read from the server/cache, and decode the json to a bean in the same way. As an added bonus, autobeans are easier to define - no JSNI required. A method could look something like this (note that In DataSource and its impl, the signature is different).
public <T> void fetch(Class<T> type, List<Stat> stats, Callback<T, Throwable> callback);
That said, what is DataTable.create? If it is already a JSO, you can just cast to DataTable as you (probably) normally do when reading from the RequestBuilder data.
I would also encourage not returning a JSON array directly from the server, but wrapping it in an object, as a best practice to protect your users' data from being read by other sites. (Okay, on re-reading the issues, objects aren't great either). Rather than discussing it here, check out JSON security best practices?
So, all of that said, first define the data (not really sure how this data is intended to work, so just making up as I go)
public interface DataTable {
String getTableName();
void setTableName(String tableName);
}
public interface Stat {// not really clear on what this is supposed to offer
String getKey();
void setKey(String key);
String getValue();
String setValue(String value);
}
public interface TableCollection {
List<DataTable> getTables();
void setTables(List<DataTable> tables);
int getRemaining();//useful for not sending all if you have too much?
}
For autobeans, we define a factory that can create any of our data when given a Class instance and some data. Each of these methods can be used as a sort of constructor to create a new instance on the client, and the factory can be passed to AutoBeanCodex to decode data.
interface DataABF extends AutoBeanFactory {
AutoBean<DataTable> dataTable();
AutoBean<Stat> stat();
AutoBean<TableCollection> tableCollection();
}
Delegate all work of String<=>Object to AutoBeanCodex, but you probably want some simple wrapper around it to make it easy to call from both the html5 cache and from the RequestBuilder results. Quick example here:
public class AutoBeanSerializer {
private final AutoBeanFactory factory;
public AutoBeanSerializer(AutoBeanFactory factory) {
this.factory = factory;
}
public String <T> encodeData(T data) {
//first, get the autobean mapped to the data
//probably throw something if we can't find it
AutoBean<T> autoBean = AutoBeanUtils.getAutoBean(data);
//then, encode it
//no factory or type needed here since the AutoBean has those details
return AutoBeanCodex.encode(autoBean);
}
public <T> T decodeData(Class<T> dataType, String json) {
AutoBean<T> bean = AutoBeanCodex.decode(factory, dataType, json);
//unwrap the bean, and return the actual data
return bean.as();
}
}

Categories

Resources