I have a request parameter like
usrInfo:fname=firstname&lname=lastname&company=&addressLine1=wewqe&addressLine2=wqewqe&city=qweqwe&country=United+States
I want to extract values for each name.
I have written below method but it is failing when there is no value for its corresponding name pair.
private String getRequestParamavalue(SlingHttpServletRequest request, String requestParameter, String requestParamName) {
String reqParamValue = null;
if (StringUtils.isNotBlank(request.getParameter(requestParameter))) {
String[] reqParams = request.getParameter(requestParameter).split("&");
Map<String, String> requestParamMap = new HashMap<>();
String value;
for (String param : reqParams) {
String name = param.split("=")[0];
value = StringUtils.isEmpty(param.split("=")[1]) ? "" : param.split("=")[1];
requestParamMap.put(name, value);
}
reqParamValue = requestParamMap.get(requestParamName);
}
return reqParamValue;
}
Please, give me an advice on this. Thanks.
#Kali Try this
for (String param : reqParams) {
String name = param.split("=")[0];
value = param.split("=").length == 1 ? "" : param.split("=")[1];
requestParamMap.put(name, value);
}
Why not simply do request.getParameter(requestParamName), the HTTPServlet Parent class does the parsing for you.
Related
I am finding a solution for get each single key value of a JSONObject dynamicaly.
I have a JSON file like this:
{
"RESPONSE":{
"A":"test",
"B":{
"C":"0",
"D":"1"
},
"E":{
"F":"2",
"G":"3"
}
}
}
I wish to create a Hashmap that contains the key and the value of the objects, like this example:
legend:
key = value
"A" = "test"
"B" = "{"C":"0", "D":"1"}"
"B.C" = "0"
"B.D" = "1"
"E" = "{"F":"2","G":"3"}"
"E.F" = "2"
"E.G" = "3"
I have tried writing this code:
private static HashMap<String, Object> createJsonObjectsHashMapOfConfigFile(String jsonFilePath,
String JsonObjectToIterate) throws Exception {
HashMap<String, Object> jHashMap = new HashMap<>();
JSONObject jsonConfigFile = SimulatorUtil.readJsonFromFile(jsonFilePath); // Returns the Json file
JSONObject jsonConfigObj = jsonConfigFile.getJSONObject(JsonObjectToIterate); // JsonObjectToIterate -->
// "RESPONSE"
Iterator<?> configIter = jsonConfigObj.keys();
String currentDynamicKey = "";
while (configIter.hasNext()) {
currentDynamicKey = (String) configIter.next();
Object currentDynamicValue = jsonConfigObj.get(currentDynamicKey);
jHashMap.put(currentDynamicKey, currentDynamicValue);
logger.info(" ---> " + jHashMap.toString());
}
return jHashMap;
}
but it get only the first level key ("A", "B", "E").
I must use org.json.
Can anyone help me?
Thanks,
Luca
{
"0":"",
"54049":"ОП.мз-61а",
"100606":"КМ-41",
"100609":"МТ-41",
"100612":"ЕМ-41",
"100684":"ХК-51",
"100685":"ЕМ-51",
"100687":"КМ-51",
"100688":"МТ-51",
"100718":"ХК-51/1",
"100719":"ХК-51/2",
"100748":"ТС-61",
"100749":"ТС-61/1",
"100750":"ТС-61/2",
"100754":"ЕМ-61",
"100758":"ІМ-61/1МБ",
"100759":"ІМ-61/2ГТ",
"100760":"МБ-61",
"100767":"ТС-51",
"100770":"ТС-41",
"100777":"ТС.м-61",
"100778":"МТ.м-61",
"100779":"ЕМ.м-61",
"100780":"ТМ.м-61",
"100781":"ТМ.м-62",
"100782":"ГМ.м-61",
"100783":"ВІ.м-61",
"100786":"ХМ.м-61"
}
You'll need to iterate over the JSONObject keys and compare the value until a match.
final String knownValue = "TC-41";
final Iterator<String> iterable = jsonObject.keys();
while (iterable.hasNext()) {
String key = iterable.next();
if (jsonObject.getString(key).equals(knownValue)) {
// key has the value you are looking for
return;
}
}
Use JSON Classes for parsing
JSONObject mainObject = new JSONObject(Your_Sring_data);
String id = mainObject .getString("100770");
//here in this **id** string you can get value for **"TC-41"**
I'm trying to get param values passed to a Java Servlet but the string returned is not correct. I'm storing the values in a Map and checking if the key exists.
Map params;
params = request.getParameterMap();
String id = params.get("id").toString();
String data = params.get("data").toString();
System.out.println("streaming" + data + " with id of " + id);
Yet if I call this servlet via http://localhost:8080/Serv/stream/data?data=hereisdata&id=you my output looks like this:
streaming[Ljava.lang.String;#5e2091d3 with id of [Ljava.lang.String;#36314ab8
What am I missing?
EDIT: as the suggested answers are not working, I'm including the entire class as I'm likely messing something up within the class:
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import Engine.Streamer;
public class AnalyzerController {
private Map params;
private String pathInfo;
private HttpServletRequest request;
public AnalyzerController(HttpServletRequest request)
{
this.params = request.getParameterMap();
this.pathInfo = request.getPathInfo();
}
public void processRequest()
{
System.out.println("procing with " + pathInfo);
switch(pathInfo){
case "/stream/data":
if(params.containsKey("id") && params.containsKey("data")) processStream();
break;
}
}
private void processStream()
{
System.out.println("we are told to stream");
String data = request.getParameter("data");
String id = request.getParameter("id");
Streamer stream = new Streamer();
stream.streamInput(data, "Analyzer", id);
}
}
This line specifically is throwing the NPE: String data = request.getParameter("data");
If you look at the docs of the Request#getParameterMap(), it returns a Map of the type Map<String, String[]>. Therefore, you need to take out the first element from the value String[] array returned from the map.
String id = params.get("id")[0];
Ofcourse, you can avoid all this and directly get the parameters from the request objects using the Request#getParameter() method.
String id = request.getParameter("id");
Edit: Looking at your class code, it seems that the instance variable request is not initialized. Initialize that in the constructor like this:
public AnalyzerController(HttpServletRequest request)
{
this.request = request; // Initialize your instance variable request which is used in the other methods.
this.params = request.getParameterMap();
this.pathInfo = request.getPathInfo();
}
You can get the required parameters instead of the whole map
String id = request.getParameter("id");
String data = request.getParameter("data");
Try something like this.
String data = ((String)params.get("data"));
Or directly from the Request.
String data = request.getParameter("data");
You can use request object plus it's method for to get data usinggetParameter() of you can use getParameterValues() if multiple data are from page.
String id = request.getParameter("id")
String data = request.getParameter("data")
why are you using Map ?
Any special need of it or any reason ?
or you can use like this :
String id = params.get("id")[0];
I have string variable String temp="acc=101&name=test"; and now how to get the value of name param from temp string.
temp.split("&")[1].split("=")[1]
public static Map<String, String> getParamMap(String query)
{
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params)
{
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
return map;
}
String temp="acc=101&name=test";
Map<String, String> map = getParamMap(temp);
for(Object object :map.keySet()){
System.out.println("key= "+object +" value= "+map.get(object));
}
System.out.println(map.get("name"));
Here is a non-general way
String str = "name=";
System.out.println(temp.substring(temp.indexOf(str) + str.length()));
It could be implemented in more general way of course:
String temp = "acc=101&name=test";
StringTokenizer st = new StringTokenizer(temp, "&");
String paramName = "name";
String paramValue = "";
while(st.hasMoreElements()) {
String str = st.nextToken();
if (str.contains(paramName)) {
paramValue = str.substring(str.indexOf(paramName) + paramName.length() + 1);
break;
}
}
System.out.println(paramValue);
You can use a method like below
public static String getValue(String queyStr, String paraamName){
String[] queries=queyStr.split("&");
for(String param:queries){
if(param.indexOf(paraamName)!=-1)
return param.split("=")[1];
}
return null;
}
And call the method like
getValue(temp, "name")
public static void main(String[] args)
{
String temp = "acc=101&name=test";
System.out.println(temp.split("&")[1].split("=")[1]);
}
If you are looking for a way to parse GET-Parameters out of an URL:
public static Map<String, String> splitQuery(URL url) throws UnsupportedEncodingException {
Map<String, String> query_pairs = new LinkedHashMap<String, String>();
String query = url.getQuery();
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}
return query_pairs;
}
You can access the returned Map using <map>.get("name"), with the URL given in your question this would return "test".
Assuming you have constant format :
String temp="acc=101&name=test";
String result =temp.substring(temp.lastIndexOf("=")+1,temp.length());
//result is test
String temp="acc=101&name=test";
String[] split = temp.split("&");
String[] name = split[1].split("=");
System.out.println(name[1]);
I would put the whole parameter in a HashMap so it is easy to get the values.
HashMap<String, String> valuemap = new HashMap<String, String>();
If you do it like so, you have to split the values at the right place...
String temp="acc=101&name=test";
valuemap.put(temp.split("&")[0].split("=")[0], temp.split("&")[0].split("=")[1]);
valuemap.put(temp.split("&")[1].split("=")[0], temp.split("&")[1].split("=")[1]);
...and put them into your HashMap. Than you have a nice collection of all your values and it is also better if you have more than only that two values. If you want the value back, use:
valuemap.get("acc")
valuemap.get("name")
I would like to parse a string which is basically a URL. I need to check simply that a parameters is passed to it or not.
so http://a.b.c/?param=1 would return true http://a.b.c/?no=1 would return false and http://a.b.c/?a=1&b=2.....¶m=2 would return true since param is set
I am guessing that it would involve some sort of regular expression.
Java has a builtin library for handling urls: Spec for URL here.
You can create a URL object from your string and extract the query part:
URL url = new URL(myString);
String query = url.getQuery();
Then make a map of the keys and values:
Map params<string, string> = new HashMap<string, string>();
String[] strParams = query.split("&");
for (String param : strParams)
{
String name = param.split("=")[0];
String value = param.split("=")[1];
params.put(name, value);
}
Then check the param you want with params.containsKey(key);
There is probably a library out there that does all this for you though, so have a look around first.
String url = "http://a.b.c/?a=1&b=2.....¶m=2";
String key = "param";
if(url.contains("?" + key + "=") || url.contains("&" + key + "="))
return true;
else
return false;