Java YAML Configuration to a custom hashmap - java

I am currently programming a bukkit plugin that stores a bunch of information about the player in a YAML configuration file. Now I want the plugin to read the YAML file when the server starts up and then add on the that information. I have my loader, but I cant use it because my plugin uses a custom map. Here is the code for the map:
Map<Integer, Map<String, Object>>
And here is the code to get the information from the file:
info = (Map<Integer, Map<String, Object>>) ticket.getConfigurationSection("tickets");
But when I try to run the plugin with that line of code i get this error:
Caused by: java.lang.ClassCastException: org.bukkit.configuration.MemorySection cannot be cast to java.util.Map
Full code is posted here: http://pastebin.com/Xgu8hwM0

The solution to this is not using a custom map. You already get a MemorySection from your configuration.
Work with that. Instead of casting you should use the method: getValues(boolean) which returns a Map<String, Object> containing all the relevant information and is specified by the Interface ConfigurationSection.
ticket.getConfigurationSection("tickets").getValues();
See also the relevant excerpt at bukkit's Configuration API Reference:
The getValues method will return the values in the
ConfigurationSection as a map, it takes a boolean which controls if
the nested maps will be returned in the map.

Yes I solved this. I HAD to use the Map<String, Object> but it worked because the way I had it(Map<Integer, Map<String, Object>>) that is the second part!

Related

parsing yaml without creating variables for each parameter

I am still quite new to programming and I really hope anyone can help me.
I would like to create a Map from a Yaml file. The problem is, I would like to make it optional which parameters are configured, so I do not want to create a class, in which all possible parameters are created as variables. I have used snakeyaml before, however as far as I know this is not an option in snakeyaml.
An example for my yaml file would look like this:
description: linter for microservices
meta:
pciScope: false
image:
name: helmcube
tag: 2.5.4
service:
type: 45
deployment:
replicaCount: 2
Do any of you have an idea how this could be realised? I have already searched for hours and could not find anything concerning that issue.
I hope anyone can help
Regards
Marie
Would getting a Properties instance be sufficient for you? Instead of creating your own Class with defined variables.
If you use Spring,
public class YamlPropertySourceFactory implements PropertySourceFactory {
#Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
}
https://www.baeldung.com/spring-yaml-propertysource
What's the best way to load a yaml file to Map(not an environment configuration file) in spring boot web project?
--- Edited ---
You now have a Properties, which you can in turn get a Hashmap out of:
Using external Lib Guava,
com.google.common.collect.Maps.fromProperties(Properties)
Or the Java Way:
Map properties = new Properties();
HashMap<String, String> map = new HashMap<String, String>(properties);
This stackoverflow shows you how to convert Properties into HashMap:
Converting java.util.Properties to HashMap<String,String>
Once you have a hasmap of configurations(Strings), you could compare against another hashamap of configurations (Strings)
If this does not help you, kindly update your question with clear incentives/example of what you are trying to achieve.

Convert Item to Map<String, AttributeValue> for DynamoDB in Java

Is there any Java API for DynamoDB to convert from Item to Map<String, AttributeValue> without implementing it on my own?
EDIT
item.asMap() will return Map<String, Object>, not Map<String, AttributeValue>. Just wondering is there any direct API for this?
Yeah, but I've managed to find it:
// Item item
InternalUtils.toAttributeValues(item)
However, above API is deprecated in newer DynamoDB library which basically delegates the call to ItemUtils which is not deprecated fortunately. So I ended up using this:
ItemUtils.toAttributeValues(item)
Hope this will help others in future!
You can use the method asMap:
Returns all attributes of the current item as a map.
Updated answer:
To get a Map<String, AttributeValue> you can use ItemUtils.toAttributeValue:
Converts an Item into the low-level representation; or null if the input is null.
as follow
Map<String, AttributeValue> map = ItemUtils.toAttributeValue(item);

Creating a map in config files

We have one application where we use configuration files and they have fields as arrays and normal variables:
metadata {
array=["val1", "val2"]
singleValue=2.0
}
Now, I know how to extract these above values like
config.getStringList("metadata.array").asScala.toArray
and config.getString("metadata.singleValue)
But, is there any way I can define maps here so that I can find value wrt desired key from that map.
This config is an object of
public interface Config extends com.typesafe.config.ConfigMergeable
You can use config.getConfig("metadata") to obtain a (sub)config object.
Converting the (sub)config to a map is something you'll have to do yourself. I would use config.entrySet() to obtain the entries as key-values, and load it into a map that way.
I haven't tried compiling/testing this code, but something like this should work:
Map<String,Object> metadata = new HashMap<>();
for (Map.Entry<String,ConfigValue> entry : config.entrySet()) {
metadata.put(entry.getKey(), entry.getValue().unwrapped());
}

Spring Configuration creating complex data structure with yaml

Using yaml in my Spring-boot application (with snakeyaml dependency 1.16) I am attempting to create a #ConfigurationProperties based off of my application.yml file. I want to create a data structure like the json below which is a Map with String Keys and Array values.
mapName: {
"key1": ["elem0","elem1"],
"key2": ["hello","world"]
}
Attempting to create a Spring configuration class as follows
#Component
#ConfigurationProperties(prefix = "channel-broker")
#EnableConfigurationProperties
public class BrokerConfiguration {
private Map<String, Set<String>> broker = new HashMap<>();
public Map<String, Set<String>> getBroker() {
return broker;
}
}
I have tried the following for my yaml
channel-broker:
broker: {message-delivery: ['all'], facebook: ['client1']}
Attempt two
channel-broker:
message-delivery: ['all']
facebook: ['client1']
Attempt three
channel-broker:
message-delivery:
- ['all']
facebook:
- ['client1']
I have also tried initializing the HashMap in the #ConfigurationProperties class as such ... new HashMap<String, Set<String>> this didn't work either
All attempts result in this error which makes me believe its an error when converting to the object not that there is anything wrong with the yaml syntax.
Caused by: org.springframework.beans.InvalidPropertyException: Invalid
property 'brokerTest[message-delivery][0]' of bean class
[my.classpackage.clasname]:
Property referenced in indexed property path
'brokerTest[message-delivery][0]' is neither an array nor a List nor a
Map; returned value was [all]
Is it possible to create such an object? How would I accomplish this
-UPDATE-
If I change the Set to an ArrayList (or List interface) this works but that isn't what I'm looking for. changed to this
private Map<String, ArrayList<String>> brokerTest = new HashMap<>();
but need this doesn't work with Set interface either:
private Map<String, HashSet<String>> brokerTest = new HashMap<>();
This issue was being caused by the format of the yaml file. The following structure allowed me to build my graph like data structure out of yaml
channel-broker:
broker:
message-delivery:
all
facebook:
client1,client2
The Set doesn't want anything extra surrounding the key. Note if your Set will contain multiple values you can add a comma to separate them. Just like Json the last element will not have a comma after.
What you are looking for is this :
channel-broker: {broker: {message-delivery:['all', ...], facebook:['client1', ...]}}
see Complete idiot's introduction to yaml
If you use [] then it's an array so arraylist works, for hashset/hashmap you need to use {} brackets.
channel-broker: {
broker: {
message-delivery:{'all', '123'},
facebook:{'client1', 'cleant2'}
}
}
will work for hashset.
(hashmap example)

Java Map issue in Spring MVC

I have a spring MVC application(RestFul), The controller has a method/API which returns
Map<Long, List<Long>>.
I need to call the above API in another web application. To do this I have written a client program which will internally call
the API and return the data.
But instead of sending
Map<Long, List<Long>>
it always sends data in
Map<String, List<String>>.
Can't I send directly
Map<Long, List<Long>>
If I create a BO/TO(Java Bean) and which has a property of type Map>
then I am able to get the data in proper format
Below is the code snippet.
public Map<Long, List<Long>> get(Long sourceId){
Map<Long, List<Long>> map = null;
// codes to perform operation and putting data into map.
return map;
}
Can you please suggest what is the issue ?
Anything sent over the wire is a String ... but your code picking up the response should convert it to long. Well it would if it were a spring-mvc controller with the correct method signature.
Are you using Javascript? Try to use the javascript parseFloat method on your JSON data

Categories