Illegal state exception when putting in a Map - java

I don't understand why I get the infamous "IllegalStateException" whith the following code:
private void mergeQueryStrings(String url, Map parameterMap) {
String queryString = getQueryString(url);
if(queryString!=null){
String [] params = queryString.split("&");
for(String param:params){
parameterMap.put(param.split("=")[0], param.split("=")[1]);
}
}
}
Could anyone enlighten me?

You've supplied an unmodifiable map. For example, the ServletRequest#getParameterMap() is immutable. If you have no control over the supplied map, then you need to create a new map, put the new items in there, return it and use it instead.
private Map mergeQueryStrings(String url, Map parameterMap) {
Map newParameterMap = new HashMap(parameterMap);
String queryString = getQueryString(url);
if(queryString!=null){
String [] params = queryString.split("&");
for(String param:params){
newParameterMap.put(param.split("=")[0], param.split("=")[1]);
}
}
return newParameterMap;
}
If you were actually using the servlet request parameter map for this, then you'd like to replace the original one with help of a HttpServletRequestWrapper in a Filter. But that's a completely different story :)
Unrelated to the concrete problem, you should url-decode the query string parts before putting them in the new map.

Related

Description for String[] entries

so i'm working on a project and i need the following to work:
Let's say I have a String[] contatining out of f.e 3 values "0D", "0A", "01A0"
Now in the background I got like a defined description for each of these values and I want to show them in another string.
So in the end i want to call a method with String"0D" and the method returns me the description, in this example "speed"
same for the others, if i call the method with "0A" it returns String "Fuel Pressure"
Is there an efficient way for achieving this? Cause i've got a pretty long list and don't want to manually input all the descriptions to the commands..
Yeah a HashMap would work.
You could try this:
HashMap<String, String> valueDescription = new HashMap<>();
valueDescription.put("0D", "speed");
valueDescription.put("0A", "Fuel Pressure");
valueDescription.put("01A0", "Temperature");
public String getDescription(String value) {
if (valueDescription.containsKey(value)) {
return valueDescription.get(value);
} else {
return "Description not found";
}
}
I would consider using a hashmap of <String, String>. The key would be the command, and the value is the description.

Java - JSON output is not expected as what console suggests

I'm new to Java and writing APIs.
I basically have two things: a HashMap called db that should be returned as a JSON and an ArrayList called defaultParameters. Basically what the application does are the following:
db basically contains an array of objects of key-value pairs that should be returned as a JSON when a user makes a GET request to this address.
defaultParameters is basically a list of default key-value pairs. If there is no key-value pair within that object, then that object takes in that default key-value pair.
I was able to get it to display on the console, but for some reason, the updated values are not appearing in the JSON when I do the get request.
Here are the relevant code snippets:
private static ArrayList<Item> DB = new ArrayList<>();
private static HashMap<String, String> defaultValues = new HashMap<>();
private void updateAllItems(){
for(Item item : DB){
for(Map.Entry entry : defaultValues.entrySet()){
String currentField = (String) entry.getKey();
String currentValue = (String) entry.getValue();
item.addField(currentField, currentValue);
}
}
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getAllItems() {
updateAllItems();
for(Item item : DB){
// Test code that I added
item.printItem();
}
return Response.ok(DB).build();
}
Snippets of the Item class
public class Item {
private HashMap<String, String> item = new HashMap<>();
public void addField(String key, String value){
item.put(key, value);
}
public void printItem(){
for(Map.Entry entry : item.entrySet()){
String currentField = (String) entry.getKey();
String currentValue = (String) entry.getValue();
System.out.println(currentField + ": " + currentValue);
}
}
}
Doing the POST request and doing the GET request yields the following:
On the console (Something: notsomething) is new:
seller: Mrs. Fields
price: 49.99
title: Cookies
category: 42
something: notsomething
The JSON response however:
[{"category":"42","seller":"Mrs. Fields","price":"49.99","title":"Cookies"}]
The JSON is missing the new key-value pair that the console has. I'm trying to have the JSON reflect what the console is doing. Anyone have any ideas?
Alright, after some thinking, I figured out what to do.
I changed my code from
public class Item {
to
public class Item extends HashMap<String, String> {
and removed
private HashMap<String, String> item = new HashMap<>();
which means I had to change item to this. I figured since that I'm going to be using each instance as a hashmap, I may as well extend the hashmap that will change the instance of the item too.
Thanks for everyone's help. The comment gave me some more insight of what I was trying to do which led to a solution.

How to access map key/value pair contained in a ModelMap object from jsp Spring MVC

I have a ModelMap variable "model", the value object contained in the model map itself is a HashMap.
Controller code:
public String func(ModelMap model)
{
HashMap<String, List<String> aMap = new HashMap<String, List<String>();
ArrayList<String> aList = new ArrayList<String>();
....// give aList some data
aMap.put("keystring", aList);
model.addAttribute("aMap", aMap);
String view = "test";
return view;
}
test.jsp code:
var data = '${aMap}';
// I know this gets the entire aMap including its key ("keystring")
// and the value (aList)
var key ='${aMap}.key';
alert(key);
var value ='${aMap}.value';
alert(value);
I also tried:
var va= data.key; // also tried data[key], data['key']
alert(va);
but they all printed either an empty string or undefined. However, if I printed "data", then I can see the entire map.
How do I access aMap's key ("keyString") and the value (aList) from test.jsp script part ? Any help will be appreciated.
You might want to take a look at this solution
How to iterate HashMap using JSTL forEach loop?
It also seems that in your method should not be #ResponseBody since you are returning a view name.

How to edit Hibernate Search java Source Code, or maybe a workaround?

I am trying to add FullTextFilters to my FullTextQuery in hibernate and there is only the method FullTextFilter.setParameter(String name, Object value)
I am trying to make a flexible, generic function to add filters to the query based on the entity its searching for, some have one parameter, some have two for their filters, so I would like to add a method to FullTextFilterImpl; setParameters(String[] names, String[] value) where I can pass in the names of all the parameters and probably a multidimensional array of the values for each parameter to transform my current code of
If( "checking which entity it is"){
fullTextQuery.enableFullTextFilter("FilterName").setParameter("firstFilter", "val1").setParameter("secondFilter", "val2");
}
else if("this entity's filter only has one parameter"){
fullTextQuery.enableFullTextFilter("FilterName").setParameter("firstFilter", "val1");
}
I tried creating a subclass of FullTextFilterImpl and putting a setParameters function in it, but the way this code is set up I'm not sure how to utilize it as FullTextQuery.enableFullTextFilter(filterName) returns a FullTextFilter object and then you call the setParameter() on that object. I'm not sure how I would get in the middle of that to do a setParameters
EDIT: I have downloaded the hibernate-search source code and added the following method to FullTextFilterImpl which I think will do what I want, but when I go to build it (even just the out-of-the-box project) I get all these checkstyle Only one new line is allowed at the end of a file errors. Is there something I'm missing from the hibernate quick-build guide.
public FullTextFilter setParameters(Map<String, List<String>> params){
for (String key : params.keySet()) {
List<String> values = params.get(key);
for(int i=0; i< values.size() ; i++){
parameters.put(key, values.get(i));
}
}
return this;
}
You can easily pass a Map of attributes to your custom Filter, the signature is:
FullTextFilter setParameter(String name, Object value);
so you could do
filter.setParameter( "myMap", properties );
where properties is an hashmap.
About the compilation error message:
Only one new line is allowed at the end of a file
is a message from checkstyle, it verifies code style is conforming to the Hibernate code style.
It's very simple to fix: there are multiple empty lines at the end of the source file, delete them. The error message should tell you what file needs to be polished.
if i correctly understand you question you need Builder pattern
here an example you could use :
public class FullTextFilter {
String[] keys;
Object[] objects;
private FullTextFilter(String[] keys, Object[] objects) {
}
public static FullTextFilterBuilder builder(){
return new FullTextFilterBuilder();
}
public static class FullTextFilterBuilder {
private Map<String, Object> parameters = new HashMap<String, Object>();
public FullTextFilterBuilder setParameter(String key, Object value){
parameters.put(key, value);
return this;
}
public FullTextFilter build(){
return new FullTextFilter(parameters.keySet().toArray(new String[0]), parameters.values().toArray(new Object[0]));
}
}
}
and then using it like this :
FullTextFilter filter = FullTextFilter.builder().setParameter("", new Object()).setParameter("", new Object()).build();
tell if that's what you are looking for.
if not i'll delete my answer
I presume you want this:
fullTextQuery.enableFullTextFilter("FilterName").setParameter("firstFilter", "val1").setParameter("secondFilter", "val2");
fullTextQuery{
name:"FilterName"
,parameters:["filter1":"value1", "filter2":"value2"]
}
static FullTextQuery enableFullTextFilter(String name){...}
FullTextQuery setParameter(String key, String value){
parameters.put(key, value);
return this;
}
assuming a parameters hashmap.
seeing as I was a little off base.. cant you do something like this?
setFilters (HashMap<String, String> filters) {
FullTTextFilter fl = FullTextQuery.enableFullTextFilter("filtername");
for (String key : filters.keySet()) {
fl.setParameter(key, filters.get(key));
}
}

Can you reference a java variable from a string?

Hi I have a strange question about java. I will leave out the background info so as not to complicate it. If you have a variable named fname. And say you have a function returning a String that is "fname". Is there a way to say reference the identifier fname via the String "fname". The idea would be something like "fname".toIdentifier() = value but obviously toIdentifier isn't a real method.
I suppose a bit of background mite help. Basically I have a string "fname" mapped to another string "the value of fname". And I want a way to quickly say the variable fname = the value of the key "fname" from the map. I'm getting the key value pair from iterating over a map of cookies in the form . And I don't want to do "if key = "fname" set fname to "value of fname" because I have a ton of variables that need to be set that way. I'd rather do something like currentkey.toIdentifer = thevalue. Weird question maybe I'm overlooking a much easier way to approach this.
Why don't you just use a simple hashmap for this?
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("fname", "someValue");
...
String value = mapping.get(key); //key could be "fname"
In a way you're describing what reflection is used for:
You refer to an object's fields and methods by name.
Java Reflection
However, most of the time when people ask a question like this, they're better off solving their problem by re-working their design and taking advantage of data structures like Maps.
Here's some code that shows how to create a Map from two arrays:
String[] keyArray = { "one", "two", "three" };
String[] valArray = { "foo", "bar", "bazzz" };
// create a new HashMap that maps Strings to Strings
Map<String, String> exampleMap = new HashMap<String, String>();
// create a map from the two arrays above
for (int i = 0; i < keyArray.length; i++) {
String theKey = keyArray[i];
String theVal = valArray[i];
exampleMap.put(theKey, theVal);
}
// print the contents of our new map
for (String loopKey : exampleMap.keySet()) {
String loopVal = exampleMap.get(loopKey);
System.out.println(loopKey + ": " + loopVal);
}
Here's a link to the JavaDoc for Map.

Categories