Request Specification is changing Object to String for query params - java

In the request specification trying to add query params using the Map<String, Object> but after the request spec gets generated any value in th Object is getting converted to String even if the value passed in Int or anything else
public Response postCall(String body, Map<String, Object> queryParams, int id1, int id2) {
RequestSpecification requestSpecification = genericRequestBuilder.getRequestSpecificationObject(); // setting the basepath and portno. and login
// The ids can be send via the queryParams map but in both the cases either in map or individual query, the values are getting converted into String
requestSpecification.queryParams(queryParams);
requestSpecification.queryParam("id1",id1);
requestSpecification.queryParam("id2",id2);
requestSpecification.body(body);
Response response =
requestSpecification.post(uri);
return response;
}
The query parameter changes as noticed in the debug mode:
result = {LinkedHashMap#4245} size = 6
"stringId1" -> "kmpySmUISimoRrJL6NL73w"
"stringId2" -> "YOgB1-WjSKyZWoCkuY7kBA"
"projectIdentifier" -> "1234"
"requestGuid" -> "1594123919225"
"id1" -> "1"
"id2" -> "1"
All the fields are string except the id1 and id2

Related

Get Value and pass as parameter to function in Java

ResponseEntity<String> respEntity = null;
try {
respEntity = getConfiguredRestTemplate().exchange(uri.toString()
, HttpMethod.GET
, entity
, new ParameterizedTypeReference<String>() {
});
log.debug("URL to retrieve a document : {}", respEntity.getBody());
}
The respEntity.getBody() returns {"url":"https://aps-fst"}
I want to send only the value - https://aps-fst as parameter to a function to download the content in the URL. How to extract only the URL value and pass it as parameter of type URL / String ?
You can use ObjectMapper from jackson and have the response body transformed into a map from which you can take the url value. You can find an example here.
String jsonString = respEntity.getBody();
JSONObject obj = new JSONObject(jsonString);
String s3urlvalue = obj.getString("url");
log.debug("S3 URL to retrieve a document : {} ", s3urlvalue);
I am able to get value with above code

Mybatis - without any error it just return [] instead of db data

I'm trying to get return value from DB but it return [] instead of data
JAVA Restful
#RequestMapping("/regLocal")
public List<Map<String, Object>> regist_local(#RequestBody Map<String, Object> params){
Map<String, String> map = new HashMap<String, String>();
String location = (String) params.get("location_name"); // 'country'
String code = (String) params.get("location_code"); // '1'
map.put("location", location);
map.put("code", code);
List<Map<String, Object>> lists = se.selectList(ns+".regLocal", map); // it return []
return lists;
}
Mybatis
<select id="regLocal" resultType="map">
select hll.hll_code hll_code, hll.hll_name hll_name
from hl_local hll, h_location hl
where hll.hl_location = #{code} and hl.hl_name = #{location}
</select>
in Oracle DB SQL select is working fine without a single problem.
but it keep return this []
anyone know the problem??
You are using the selectList api and the XML declaration the return type is map, but you did not specify how the query results must fill the map. If you want that every row from the db is mapped to a Map<String, Object> you must write a ResultHandler.
You can use the selectMap api but the result is a Map<String,AnObject> where AnObject is a class that represents the columns selected in the query.
You can check this respone for more details.

Parsing map JSON value and reinserting back into map

I am trying to parse a map and update the value in it...
Here is the content of the .txt file that I have made the hashmap
The first line is the key and the JSON string is the value.
Not_enough_parameters
{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting: 18, actual:8", "version": "0.97", "coreName": "Patient_Responsibility"}
Here is my parsing code:
parse = params.split("\\|");
String key;
String value;
String value2;
String key2;
String value3;
Map<String, String> predictionFeatureMap = mockconfig.getPredictionFeatureMap();
if(parse.length!=18) {
key = "Not_enough_parameters";
value = predictionFeatureMap.get(key);
Map<?,?> resultJsonObj = new Gson().fromJson(value, Map.class);
key2 = "errorMessage";
value2 = (String) resultJsonObj.get(key2);
value3 = value2.substring(0,61) +parse.length+value2.substring(62);
}
I am sending a payload string named params that is separated by "|" separators. They input must have 18 parameters(18 values in-between the "|" separators). I parse the input and if it does not have enough parameters I get they key containing the string "Not_enough_paramters" and then get its value which is the JSON string.
I then take that JSON string and using Gson create a map out of it.
I did that because I want value to return
{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting: 18, actual:(params.length)", "version": "0.97", "coreName": "Patient_Responsibility"}
So I want "actual:" to be updated. I get the value from the JSON map for "errorMessage" and using substring I get the index and change the value to update the actual amount of parameters the user put in.
I am not sure how to reinsert the new JSON into the entire JSON string in the JSON map and then into the original map.
So I implemented a solution although I am not sure it is the cleanest and most straight forward.
I still got the substring from the value from the "errorMessage" key in the JSON Map.
I then replaced the value of that key with the new edited JSON.
Then I took the Json Map and converted it into a string.
I then added the new JSON string to the value of the original hashmap
String[] parse;
#PostMapping(value = "/")
public String payloader(#RequestBody String params ) throws IOException{
LOGGER.debug("code is hitting");
String key,key2;
String value,value2,value3;
Map<String, String> predictionFeatureMap = mockconfig.getPredictionFeatureMap();
if(parse.length!=18) {
key = "Not_enough_parameters";
value = predictionFeatureMap.get(key);
Map<String,Object> resultJsonObj = new Gson().fromJson(value, Map.class);
key2 = "errorMessage";
value2 = (String) resultJsonObj.get(key2);
value3 = value2.substring(0,61) +parse.length+value2.substring(62);
resultJsonObj.replace(key2, value3);
String updatedResponse = new Gson().toJson(resultJsonObj,Map.class);
value = updatedResponse;
}
else {
key = params;
value = predictionFeatureMap.get(key);
}
return value;

getting a string payload to curl

I am trying to curl a string payload and I need it to throw an error if it contains certain parameters.
Here is my code:
#RequestMapping(value = "/payload3", method = RequestMethod.POST, produces = {"application/json"})
public String payloader3(#RequestParam Map<String, String> params ) throws IOException{
#NotNull
String type = mockendpoint.Payload3();
return type;
}
You need to change your return type so that you return a ResponseEntity.
In the event of a successful request, you return a HTTP 200, with the required response body:
return ResponseEntity.ok(json);
And in the event your parameter map size is not equal to your desired value, you can return a HTTP 400, with an appropriate error message:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(badRequestBody);
You can consume the input as a String instead of Map(that you currently have) and do a split on it with your delimeter |. If the returned array size is not 18 then throw an exception?

Store #PathParam values from REST call in a list or array

My function looks like this:
#PUT
#Path("property/{uuid}/{key}/{value}")
#Produces("application/xml")
public Map<String,ValueEntity> updateProperty(#Context HttpServletRequest request,
#PathParam("key") String key,
#PathParam("value") String value,
#PathParam("uuid") String uuid) throws Exception {
...
}
I have to modify it, so it accepts indefinite(or many) list of key-value pairs from REST call, something like
#Path("property/{uuid}/{key1}/{value1}/{key2}/{value2}/{key3}/{value3}/...")
Is it possible to store them in an array or list, so I do not list dozens of #PathParams and parameters, to avoid this:
#PathParam("key1") String key1,
#PathParam("key2") String key2,
#PathParam("key3") String key3,
Might be a good opportunity to rethink this design. By using /s, we are in a way signifying, with each / that we are trying to locate a different resource. Key/Value pairs (in the context of the URL) are mainly for query parameters or matrix parameters.
If /property/{uuid} is the path to a main resource, and we just want to offer some parameters to the client for accessing this resource, then we could allow matrix parameters or query parameters
Matrix Parameters (in a request url) will look something like
/12345;key1=value1;key2=value2;key3=value3
A resource method to obtain the values might look something like
#GET
#Path("/property/{uuid}")
public Response getMatrix(#PathParam("uuid") PathSegment pathSegment) {
StringBuilder builder = new StringBuilder();
// Get the {uuid} value
System.out.println("Path: " + pathSegment.getPath());
MultivaluedMap matrix = pathSegment.getMatrixParameters();
for (Object key : matrix.keySet()) {
builder.append(key).append(":")
.append(matrix.getFirst(key)).append("\n");
}
return Response.ok(builder.toString()).build();
}
See PathSegment
Query Parameters (in a request url) might look something like
/12345?key1=value1&key2=value2&key3=value3
A resource method to obtain the values might look something like
#GET
#Path("/property/{uuid}")
public Response getQuery(#PathParam("uuid") String uuid,
#Context UriInfo uriInfo) {
MultivaluedMap params = uriInfo.getQueryParameters();
StringBuilder builder = new StringBuilder();
for (Object key : params.keySet()) {
builder.append(key).append(":")
.append(params.getFirst(key)).append("\n");
}
return Response.ok(builder.toString()).build();
}
See UriInfo
The difference is that Matrix parameters can be embedded into path segments, while query parameters must be placed at the end of the URL. You can also notice a little difference in syntax.
Some Resources
Query String (Wikipedia)
When to use query parameters versus matrix parameters?
URL matrix parameters vs. request parameters
UPDATE
Also looking at the PUT in you method signature, it appears you are trying update a resource using the path as the values for which you are trying to update, as I don't see any parameters in your method for an entity body. When PUTting, you should be sending the representation in the the entity body, not as as path segments or parameters.
A workaround:
#Path("/foo/bar/{other: .*}
public Response foo(#PathParam("other") VariableStrings vstrings) {
String[] splitPath = vstrings.getSplitPath();
}
VariableStrings class:
public class VariableStrings {
private String[] splitPath;
public VariableStrings(String unparsedPath) {
splitPath = unparsedPath.split("/");
}
}
Path segment sequence to vararg array in JAX-RS / Jersey?
Another example where you map the optional parameter to a Map:
#GET
# Produces({"application/xml", "application/json", "plain/text"})
# Path("/location/{locationId}{path:.*}")
public Response getLocation(#PathParam("locationId") int locationId, #PathParam("path") String path) {
Map < String, String > params = parsePath(path);
String format = params.get("format");
if ("xml".equals(format)) {
String xml = "<location<</location<<id<</id<" + locationId + "";
return Response.status(200).type("application/xml").entity(xml).build();
} else if ("json".equals(format)) {
String json = "{ 'location' : { 'id' : '" + locationId + "' } }";
return Response.status(200).type("application/json").entity(json).build();
} else {
String text = "Location: id=" + locationId;
return Response.status(200).type("text/plain").entity(text).build();
}
}
private Map < String, String > parsePath(String path) {
if (path.startsWith("/")) {
path = path.substring(1);
}
String[] pathParts = path.split("/");
Map < String, String > pathMap = new HashMap < String, String > ();
for (int i = 0; i < pathParts.length / 2; i++) {
String key = pathParts[2 * i];
String value = pathParts[2 * i + 1];
pathMap.put(key, value);
}
return pathMap;
}

Categories