parsing data sent from a spring controller - javascript

I'm trying to send some datas from the controller to the jsp view then parse them using javascript to fill a table in html
this is the controller's method
final String SERVER_URI = "http://localhost:8081/BackEndFinalVersion";
#RequestMapping(value = "/CourriersArrivées", method = RequestMethod.GET)
public String showHome(Principal principal,Model model) {
RestTemplate restTemplate = new RestTemplate();
#SuppressWarnings("unchecked")
Map<String, Object> roles = restTemplate
.getForObject(SERVER_URI + "/getUserRole" + "?uid=" + principal.getName(), HashMap.class);
List<String>r=(List<String>) roles.get("roles");
for (int i = 0; i < r.size(); i++) {
if(r.get(i).equals("Secrétaire Générale")){
#SuppressWarnings("rawtypes")
List<Map<String, Object>> allCourrier= restTemplate.getForObject(SERVER_URI + "/listCourriersArrivés", ArrayList.class);
System.out.println(allCourrier);
model.addAttribute("allCourrier", allCourrier);
return "CourriersArrivées";
}
}
return "CreationCourrier";
}
this controller will redirect me to "CreationCourrier.jsp page with the "allCourrier" attribute which is a List<Map> which gives me a result like this
[{date=19-5-5, expéditeur=Steg, listePiécesJointes=[C:\Users\Wassim\Downloads\eclipse\compte.txt, C:\Users\Wassim\Downloads\eclipse\udemy mdp.txt], isValidated=true, idCourrierArrivéFolder=workspace://SpacesStore/6cd81e2e-512f-47a1-a372-014369368584, départmentId=ROLE_ADMIN}, {date=19-5-5, expéditeur=Steg, listePiécesJointes=[C:\Users\Wassim\Downloads\eclipse\mdp enis account.txt, C:\Users\Wassim\Downloads\eclipse\udemy mdp.txt], isValidated=true, idCourrierArrivéFolder=workspace://SpacesStore/68afae4e-195f-4d58-8d0d-3b3525b0edeb, départmentId=ROLE_ADMIN}
which is very hard to parse because it is not json so I can't parse him easily with javascript
My question is that is there any easy way to parse this result and if not can you show me how to send json format for exemple which is easier to parse

Related

Calling script from Blazor with parameters

I've been given a script function and would like to partially translate it to C# in a Blazor app
<script>
function pay() {
var token = document.getElementById('token').value;
var card = document.getElementById('card').value;
var exp = document.getElementById('exp').value;
var cvv = document.getElementById('cvv').value;
var paymentData = {
ssl_txn_auth_token: token,
ssl_card_number: card,
ssl_exp_date: exp ,
ssl_cvv2cvc2: cvv
};
ConvergeEmbeddedPayment.pay(paymentData);
return false;
}
</script>
I want to call the script (that is inside the script above)
ConvergeEmbeddedPayment.pay(paymentData);
Directly from c# . Like so
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", paymentData);
There is some good information here:
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1
But it stops short of helping me.
What kind of variable should I pass in the paymentData parameter? And how should I pass it?
I've tried var , object and string and also tried JsonSerializer.Serialize( ); but no luck
Based on suggestion from #BurningKarl I tried Dictionary and object[] but
I get an error saying the content is missing or "Expected BEGIN_OBJECT but was STRING "
Looks like you have to create your own c# class that mimics the payment data object in your Javascript.
Something like this
public class PaymentData
{
public string ssl_txn_auth_token {get; set;}
public string ssl_card_number{get; set;}
public string ssl_exp_date{get; set;}
public string ssl_cvv2cvc2{get; set;}
}
Then you have to create an instance of this class and pass it to InvokeVoidAsync as an argument.
var data = new PaymentData ()
{
ssl_txn_auth_token = "authtokenvalue",// you have to get it from control
ssl_card_number = "card number",
ssl_exp_date: "date", // probably it should be daytime or similar
ssl_cvv2cvc2 = "111"
}
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", data);

Why my GET call gets an array with empty objects?

I have a c# web project that has some REST request to do to get data from the db. My problem is: I have a GET call which return an array of the size of the number of rows returned by the query but every object is empty. While I'm debugging, every object has all the data I need but when the data reach the javascript the array is full of empty object. Where am I wrong?
This is the request on the .js file:
$.get("api/giacenzemobile/getGiacenze", function (data) {
console.log(data)
});
This is the function on the model file (.cs)
public static List<GiacenzeMobile> EstraiGiacenzeMobile()
{
List<GiacenzeMobile> giacenzeMobile = new List<GiacenzeMobile>();
SqlCommand cmd = null;
SqlConnection sqlconn = null;
using (sqlconn = new SqlConnection(Configurazione.ConnessioneDB))
{
sqlconn.Open();
string query = "...";
cmd = new SqlCommand(query, sqlconn);
SqlDataReader res = cmd.ExecuteReader();
while (res.Read())
{
GiacenzeMobile giac = new GiacenzeMobile();
giac.IdGiacenza = res.GetInt32(0);
//..... set all data ...
giacenzeMobile.Add(giac);
}
return giacenzeMobile;
}
}
And this is the controller (.cs):
public class GiacenzeMobileController : ApiController
{
[Route("api/giacenzemobile/getGiacenze")]
public IEnumerable<GiacenzeMobile> GetGiacenze()
{
return GiacenzeMobile.EstraiGiacenzeMobile();
}
//...other code...
}
And this is the result write on the console log:
Array(6)0: {}1: {}2: {}3: {}4: {}5: {}
SOLVED
I didn't set as public the fields of the GiacenzeMobile object.
If your attributes are private kotlin will not add it to the JsonString when it is deserialized. So make them public or remove the private identifier

How to use JSON result in selenium webdriver

Im a beginner for automation testing.Here I want to get the data's from json to be used by selenium webdriver.I wrote one java class and hard coded something to get a result as a try.and getting an answer in console panel like
{
"name": "john",
"location": "jihu",
"job": [
{
"manager": [
{
"collegues": [
"ram",
"ranma",
],
}
}
}
(not exactly this).
Now i want to use this for one specific application using selenium webdriver. How can i move on with this.help me in detail.Thanks in advance.
From Selenium and Backend Comparison testing point of view i am answering the same .you need to parse json response using some Libraries like GSON , jackson etc into Java Pojo objects and then apply asserts on the fields you want to compare with json and UI. I guess you need to go through below topics first
1) Serialization -Deserialization API response
2) GSON or Jackson parsers
3) RestAssured ( Provides framework for API testing )
4) JAVA pojo classed and usage of them . you might need them to save your response in form of some Response class and compare objects .
You can use these online converters for converting a json object into Java Pojo Classes :
http://json2java.azurewebsites.net/ (I usually use this)
https://codebeautify.org/json-to-java-converter
and then place them in a package or in the same class as you wish :
You can better understand it by below example :
package com.demo.core;
import com.google.gson.Gson;
import io.restassured.RestAssured;
import io.restassured.response.Response;
public class Demo {
public static void main(String r[]) {
Response response1 = RestAssured.given().get("http://dummy.restapiexample.com/api/v1/employee/1"); // use your method to get the API response (I have used RestAssured here)
String json = response1.asString(); // you can use your json response here and convert it into a String
Gson gson = new Gson();
Employee emp = gson.fromJson(json, Employee.class); // The response is now captured in this Employee class
System.out.println(emp.getEmployeeAge());
System.out.println(emp.getEmployeeName());
System.out.println(emp.getEmployeeSalary());
}
}
class Employee {
private String id;
private String employee_name;
private String employee_salary;
private String employee_age;
private String profile_image;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getEmployeeName() {
return this.employee_name;
}
public void setEmployeeName(String employee_name) {
this.employee_name = employee_name;
}
public String getEmployeeSalary() {
return this.employee_salary;
}
public void setEmployeeSalary(String employee_salary) {
this.employee_salary = employee_salary;
}
public String getEmployeeAge() {
return this.employee_age;
}
public void setEmployeeAge(String employee_age) {
this.employee_age = employee_age;
}
public String getProfileImage() {
return this.profile_image;
}
public void setProfileImage(String profile_image) {
this.profile_image = profile_image;
}
}
You can easily assert the values after the response is captured in Java classes using their getter methods like I have used in the code to get field values present in Employee class.
Please do let me know if you still got an issue.
If your result contains many fields than better to shift all converted java classes into a separate package for a clear code.

How to return object from rest service in java?

What is the best way to return a value of a method of rest service ? A java object, json string or with Response?
For example, these examples are implemented with api jersey (maven):
1) Return java object (mapped to json):
#GET
#Path("/getUser")
#Produces({MediaType.APPLICATION_JSON})
public UserVO getUser() {
UserVO user = new UserVO();
user.setValid(true);
user.setName("Peter");
return user;
}
2) Return a json string:
#GET
#Path("/getUser")
public String getUser() {
UserVO user = new UserVO();
user.setValid(true);
user.setName("Peter");
Gson gson = new Gson();
String jsonResp = gson.toJson(user);
return jsonResp;
}
3) Return with response json:
#GET
#Path("/getUser")
public Response getUser() {
UserVO user = new UserVO();
user.setValid(true);
user.setName("Peter");
Gson gson = new Gson();
String jsonResp = gson.toJson(user);
return Response.ok(jsonResp, MediaType.APPLICATION_JSON).build();
}
What is the difference between these 3? Which is better to use ?
(Considering it will be consumed from javascript)
All three options seem valid, but the first one is in my opinion more consistent because you're using an API (jersey) and this #produces annotation is the common way to use that API.
Moreover it won't make you dependant of another lib, GSON, which you could ultimately remove from your classpath if it isn't used elsewhere.

How to use page session value and function in Jquery webmethod

I have a session value and a function in a apsx.cs page and I am using jquery webmethod to insert data into database.
Now i want to access session value and function in webmethod but it gives some error.
Below is my Page load code:
int nUserId = Convert.ToInt16(Session["UId"]);
And a Function :
public int CalcUser()
{
return Convert.ToInt16(Session["UId"]) * 2;
}
Now below is my Webmethod:
[WebMethod]
public static void Save()
{
UserInfo objUser = new UserInfo();
objUser.Useid = Convert.ToInt16(Session["UId"]);
objUser.CalcUser = CalcUser();
... Save into Database
}
So how can I use session value and function in webmwthod.
Thanks
You need to explicitly state that you want to use Session with your ASP.NET AJAX Page Method by using the EnableSession= true value in the WebMethod attribute, like this:
[WebMethod(EnableSession = true)]
public static void Save()
{
UserInfo objUser = new UserInfo();
objUser.Useid = Convert.ToInt16(HttpContext.Current.Session["UId"]);
objUser.CalcUser = CalcUser();
... Save into Database
}
Note: You must fully qualify the namespace of the session (HttpContext.Current.Session).
To use the CalcUser() function you need to make it static and fully qualify the Session object, like this:
public static int CalcUser()
{
return Convert.ToInt16(HttpContext.Current.Session["UId"]) * 2;
}
Note: ASP.NET AJAX Page Methods only have access to static methods, as there is no instance of the page (or any class for that matter).
You need to use [WebMethod(EnableSession = true)] on webmethod
Then you can use like Context.Session["key"]
[WebMethod]
[WebMethod(EnableSession = true)]
public static void Save()
{
UserInfo objUser = new UserInfo();
objUser.Useid = Convert.ToInt16(Context.Session["UId"]);
objUser.CalcUser = CalcUser();
... Save into Database
}

Categories