How to persist session between scenarios on Gatling simulation in Java

I’m trying to extract the cookie from a request and pass it into another. The login request is to be executed only once whereas the other apis may be executed multiple times. Hence the need for different scenarios. However, as gatling does not persist sessions between scenarios, I’m struggling to get the cookie from the login request into the api that uses it as header.

As per the below print, it shows that cookie is being set as ${authCookie} instead of the proper value for the cookie.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>18:15:10.738 [DEBUG]
Request:
GetNotifications: KO jsonPath($[0].id).find.exists preparation crashed: Jackson failed to parse into a valid AST: c.f.j.c.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 2]
Session:
HTTP request:
GET https://dtl.mycompanyconnect.com/aml-account-risk/api/notifications/
headers:
accept: application/json
X-AmlArReporting-ICAs: 11286
X-AmlArReporting-CID: 125283
Cookie: ${authCookie}
host: dtl.mycompanyconnect.com
</code>
<code>18:15:10.738 [DEBUG] Request: GetNotifications: KO jsonPath($[0].id).find.exists preparation crashed: Jackson failed to parse into a valid AST: c.f.j.c.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false') at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 2] Session: HTTP request: GET https://dtl.mycompanyconnect.com/aml-account-risk/api/notifications/ headers: accept: application/json X-AmlArReporting-ICAs: 11286 X-AmlArReporting-CID: 125283 Cookie: ${authCookie} host: dtl.mycompanyconnect.com </code>
18:15:10.738 [DEBUG]
Request:
GetNotifications: KO jsonPath($[0].id).find.exists preparation crashed: Jackson failed to parse into a valid AST: c.f.j.c.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 2]
Session:
HTTP request:
GET https://dtl.mycompanyconnect.com/aml-account-risk/api/notifications/
headers:
    accept: application/json
    X-AmlArReporting-ICAs: 11286
    X-AmlArReporting-CID: 125283
    Cookie: ${authCookie}
    host: dtl.mycompanyconnect.com

This is the full simulation class:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>package com.mycompany.amlar.performancetests;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mycompany.amlar.openapi.Notification;
import io.gatling.javaapi.core.ScenarioBuilder;
import io.gatling.javaapi.core.Simulation;
import io.gatling.javaapi.http.HttpProtocolBuilder;
import java.util.concurrent.ConcurrentHashMap;
import static io.gatling.javaapi.core.CoreDsl.*;
import static io.gatling.javaapi.http.HttpDsl.*;
public class AmlarSimulation extends Simulation {
private static final String BASE_URL = "https://dtl.mycompanyconnect.com/";
private static final ConcurrentHashMap<String, String> authCookies = new ConcurrentHashMap<>();
private final HttpProtocolBuilder httpProtocol = http
.disableFollowRedirect()
.baseUrl(BASE_URL)
.acceptHeader("application/json")
.header("X-AmlArReporting-ICAs", "11286")
.header("X-AmlArReporting-CID", "125283");
Notification notification;
private final ScenarioBuilder loginScenario = scenario("LoginScenario")
.exec(http("Login")
.post("/heracles/login")
.header("Content-Type", "application/x-www-form-urlencoded")
.formParam("username", "aml_ar_stg")
.formParam("password", "1234")
.formParam("login-form-type", "token")
.check(status().is(302), header("Set-Cookie").saveAs("authCookie")))
.exec(session -> {
String authCookie = "auth_token=" + session.get("authCookie");
authCookies.put("authCookie", authCookie); // Save the authCookie to the ConcurrentHashMap
return session;
});
private final ScenarioBuilder scn = scenario("MyScenario")
.exec(session -> {
// Add the authCookie to the session
String authCookie = authCookies.get("authCookie");
session.set("authCookie", authCookie);
return session;
})
.exec(http("GetNotifications")
.get("aml-account-risk/api/notifications/")
.header("Cookie", "${authCookie}")
.check(bodyString().saveAs("body")) // Save the response body
.check(jsonPath("$[0].id").saveAs("notificationId"))
.check(jsonPath("$[0]").saveAs("notificationJson"))) // Save the whole notification as JSON
.exec(session -> {
// Parse the JSON and create the Notification object
String notificationJson = session.get("notificationJson");
ObjectMapper objectMapper = new ObjectMapper();
try {
notification = objectMapper.readValue(notificationJson, Notification.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
// Save the Notification object in the session
session.set("notification", notification);
return session;
});
{
setUp(
loginScenario.injectOpen(atOnceUsers(1)).protocols(httpProtocol)
.andThen(scn.injectOpen(rampUsers(1).during(10)).protocols(httpProtocol))
);
}
}
</code>
<code>package com.mycompany.amlar.performancetests; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mycompany.amlar.openapi.Notification; import io.gatling.javaapi.core.ScenarioBuilder; import io.gatling.javaapi.core.Simulation; import io.gatling.javaapi.http.HttpProtocolBuilder; import java.util.concurrent.ConcurrentHashMap; import static io.gatling.javaapi.core.CoreDsl.*; import static io.gatling.javaapi.http.HttpDsl.*; public class AmlarSimulation extends Simulation { private static final String BASE_URL = "https://dtl.mycompanyconnect.com/"; private static final ConcurrentHashMap<String, String> authCookies = new ConcurrentHashMap<>(); private final HttpProtocolBuilder httpProtocol = http .disableFollowRedirect() .baseUrl(BASE_URL) .acceptHeader("application/json") .header("X-AmlArReporting-ICAs", "11286") .header("X-AmlArReporting-CID", "125283"); Notification notification; private final ScenarioBuilder loginScenario = scenario("LoginScenario") .exec(http("Login") .post("/heracles/login") .header("Content-Type", "application/x-www-form-urlencoded") .formParam("username", "aml_ar_stg") .formParam("password", "1234") .formParam("login-form-type", "token") .check(status().is(302), header("Set-Cookie").saveAs("authCookie"))) .exec(session -> { String authCookie = "auth_token=" + session.get("authCookie"); authCookies.put("authCookie", authCookie); // Save the authCookie to the ConcurrentHashMap return session; }); private final ScenarioBuilder scn = scenario("MyScenario") .exec(session -> { // Add the authCookie to the session String authCookie = authCookies.get("authCookie"); session.set("authCookie", authCookie); return session; }) .exec(http("GetNotifications") .get("aml-account-risk/api/notifications/") .header("Cookie", "${authCookie}") .check(bodyString().saveAs("body")) // Save the response body .check(jsonPath("$[0].id").saveAs("notificationId")) .check(jsonPath("$[0]").saveAs("notificationJson"))) // Save the whole notification as JSON .exec(session -> { // Parse the JSON and create the Notification object String notificationJson = session.get("notificationJson"); ObjectMapper objectMapper = new ObjectMapper(); try { notification = objectMapper.readValue(notificationJson, Notification.class); } catch (JsonProcessingException e) { throw new RuntimeException(e); } // Save the Notification object in the session session.set("notification", notification); return session; }); { setUp( loginScenario.injectOpen(atOnceUsers(1)).protocols(httpProtocol) .andThen(scn.injectOpen(rampUsers(1).during(10)).protocols(httpProtocol)) ); } } </code>
package com.mycompany.amlar.performancetests;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mycompany.amlar.openapi.Notification;
import io.gatling.javaapi.core.ScenarioBuilder;
import io.gatling.javaapi.core.Simulation;
import io.gatling.javaapi.http.HttpProtocolBuilder;

import java.util.concurrent.ConcurrentHashMap;

import static io.gatling.javaapi.core.CoreDsl.*;
import static io.gatling.javaapi.http.HttpDsl.*;

public class AmlarSimulation extends Simulation {

    private static final String BASE_URL = "https://dtl.mycompanyconnect.com/";

    private static final ConcurrentHashMap<String, String> authCookies = new ConcurrentHashMap<>();

    private final HttpProtocolBuilder httpProtocol = http
            .disableFollowRedirect()
            .baseUrl(BASE_URL)
            .acceptHeader("application/json")
            .header("X-AmlArReporting-ICAs", "11286")
            .header("X-AmlArReporting-CID", "125283");

    Notification notification;

    private final ScenarioBuilder loginScenario = scenario("LoginScenario")
            .exec(http("Login")
                    .post("/heracles/login")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .formParam("username", "aml_ar_stg")
                    .formParam("password", "1234")
                    .formParam("login-form-type", "token")
                    .check(status().is(302), header("Set-Cookie").saveAs("authCookie")))
            .exec(session -> {
                String authCookie = "auth_token=" + session.get("authCookie");
                authCookies.put("authCookie", authCookie); // Save the authCookie to the ConcurrentHashMap
                return session;
            });

    private final ScenarioBuilder scn = scenario("MyScenario")
            .exec(session -> {
                // Add the authCookie to the session
                String authCookie = authCookies.get("authCookie");
                session.set("authCookie", authCookie);
                return session;
            })
            .exec(http("GetNotifications")
                    .get("aml-account-risk/api/notifications/")
                    .header("Cookie", "${authCookie}")
                    .check(bodyString().saveAs("body")) // Save the response body
                    .check(jsonPath("$[0].id").saveAs("notificationId"))
                    .check(jsonPath("$[0]").saveAs("notificationJson"))) // Save the whole notification as JSON

            .exec(session -> {
                // Parse the JSON and create the Notification object
                String notificationJson = session.get("notificationJson");
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    notification = objectMapper.readValue(notificationJson, Notification.class);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }

                // Save the Notification object in the session
                session.set("notification", notification);
                return session;
            });

    {
        setUp(
                loginScenario.injectOpen(atOnceUsers(1)).protocols(httpProtocol)
                        .andThen(scn.injectOpen(rampUsers(1).during(10)).protocols(httpProtocol))
        );
    }
}

Thank you.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật