Thursday, February 23, 2023

Create A Service to Run Jar File In Background As System Service on AWS EC2

 

Prerequisite:

  1. Java should already have
  2. Open and connect AWS ec2 instance using terminal
  3. Reach out root folder where the domain is pointing out for me it’s /var/www/HTML/
  4. Take pull the latest Spring Boot code from git https://bitbucket.org/***
  5. MVN clean install – this will convert java code with all its dependencies in a jar file
    (SUDO) java -jar target/YOUR_FILE_NAME.jar (target is a folder on root)

Problem: We found a challenge while running java -jar *.jar on AWS ec2 instance in the background

Solution:  Create a system service to run the Jar file in the background Linux

Ubuntu/Linux has an in-built mechanism to create custom services and enable them to start on system boot time and start/stop them as a service.

Create a bash script to run jar file Linux:

Replace the customservicename with your own service name

  1. Create a vi or nano file under /usr/local/bin/ by running the following commandeg: sudo vi /usr/local/bin/customservicename.shThis will open a file with the name customservicename.sh.
  1. Paste the following Code in opened sh.
    In the below code replace the customservicename with your own service name,
    JAR_FILE_PATH(Absolute Path to your jar File), and choose a PID_NAME_PATH(just replace CUSTOM_SERVICE_NAME to your customservicename keeping -PID at the end ) for the file you are going to use to store your service ID.

The only changes needed are to the first 3 variables.

#!/bin/sh
CUSTOM_SERVICE_NAME=customservicename
JAR_FILE_PATH=/var/www/html/target/YourJavaApplication.jar
PID_NAME_PATH=/tmp/customservicename-pid
case $1 in
start)
echo "Starting $CUSTOM_SERVICE_NAME ..."
if [ ! -f $PID_NAME_PATH ]; then
nohup java -jar $JAR_FILE_PATH /tmp 2>> /dev/null >>/dev/null & echo $! > $PID_NAME_PATH
echo "$CUSTOM_SERVICE_NAME started ..."
else
echo "$CUSTOM_SERVICE_NAME is already running ..."
fi
;;
stop)
if [ -f $PID_NAME_PATH ]; then
PID=$(cat $PID_NAME_PATH);
echo "$CUSTOM_SERVICE_NAME stopping ..."
kill $PID;
echo "$CUSTOM_SERVICE_NAME stopped ..."
rm $PID_NAME_PATH
else
echo "$CUSTOM_SERVICE_NAME is not running ..."
fi
;;
restart)
if [ -f $PID_NAME_PATH ]; then
PID=$(cat $PID_NAME_PATH);
echo "$CUSTOM_SERVICE_NAME stopping ...";
kill $PID;
echo "$CUSTOM_SERVICE_NAME stopped ...";
rm $PID_NAME_PATH
echo "$CUSTOM_SERVICE_NAME starting ..."
nohup java -jar $JAR_FILE_PATH /tmp 2>> /dev/null >> /dev/null & echo $! > $PID_NAME_PATH
echo "$CUSTOM_SERVICE_NAME started ..."
else
echo "$CUSTOM_SERVICE_NAME is not running ..."
fi
;;
esac
    1. Write and quit the above file by pressing the ESC button then:wq! and give execution permissions :eg: sudo chmod +x /usr/local/bin/customservicename.sh

Read Also:- Setting Up Jenkins on Amazon EC2 Ubuntu Instance


Use The Following Commands to Test Whether Java Application Is Working:

/usr/local/bin/./customservicename.sh start
/usr/local/bin/./customservicename.sh stop
/usr/local/bin/./customservicename.sh start
/usr/local/bin/./customservicename.sh restart

 

If all the above commands do not give an error then we move forward to create a service

  1. Create a file under /etc/system/system/ with nano or vi and paste the example script below.
         Eg. sudo vi /etc/systemd/system/customservicename.service
  2. Insert the following code in customservicename:
    [Unit]
    Description = My Java Service
    After network.target = customservicename.service
    [Service]
    Type = forking
    Restart=always
    RestartSec=1
    SuccessExitStatus=143
    ExecStart = /usr/local/bin/customservicename.sh start
    ExecStop = /usr/local/bin/customservicename.sh stop
    ExecReload = /usr/local/bin/customservicename.sh reload
    [Install]
    WantedBy=multi-user.target

     

  3. Write and quit this file by pressing the ESC button then:wq!
    Now Service is all set up.

You can enable/start/stop your Java Application as a Service using the following commands:

sudo systemctl daemon-reload
sudo systemctl enable customservicename
sudo systemctl start customservicename
sudo systemctl stop customservicename

 

This should get Java Application up and running in the background as a System Service.


Original Source:- https://www.devstringx.com/run-jar-file-in-background-on-aws-ec2

Wednesday, February 22, 2023

Retrieve Test Data from Json file in C# Selenium Framework

 When we write an automation framework one of the many challenges is to use test data in our test scripts. One way is to hardcode the test data in our test scripts but this approach is not extensible, what if the test data change after some time?

Then we have to change the hardcoded data in the test scripts themselves and if the same test data is used in various test scripts changing the hardcoded data from each test script will be time-consuming and will result in test script failure if some of the test data is not updated correctly.

Another approach is to separate the test data from the test script and put the test data in an external file like Excel or JSON.

In this blog, I will show you how we can retrieve the data from JSON files and use that data in our test script.

I will be extending the CalculatorFramework.

Retrieve the Data from JSON files

Create a new folder TestData and create a Data.json file

Data.json

{
"Addition": 16,
"Subtraction": 2,
"Multiplication": 63,
"Division": 1,
"Array": [
"one",
"two",
"three"
]
}

In our JSON file Addition, Subtraction, Multiplication, Division, and Array are Keys and each key has a corresponding value. The value can be of any data type e.g., integer, float, Boolean, string, array, etc. Using the key, we can fetch the corresponding data. In the Data.json file, we have four integer values and one string array.

Create a new JsonHelper.cs file which we will use to get the data from JSON

JsonHelper.cs

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
namespace CalculatorFramework.Utils
{
class JsonHelper
{
public static string GetProjectRootDirectory()
{
string currentDirectory = Directory.GetCurrentDirectory();
return currentDirectory.Split("bin")[0];
}
private static JObject GetTestDataJsonObject()
{
string path = Path.Combine(GetProjectRootDirectory(), "Testdata", "Data.json");
JObject jObject = JObject.Parse(File.ReadAllText(path));
return jObject;
}
public static int GetTestDataInt(string label)
{
var jObject = GetTestDataJsonObject();
return Int32.Parse(jObject[label].ToString());
}
public static List<string> GetTestDataArray(string label)
{
var jObject = GetTestDataJsonObject();
return jObject[label].ToObject<List<string>>(); ;
}
}
}

GetProjectRootDirectory() – Returns the project root directory path

GetTestDataJsonObject() – Reads the json file and returns a Json Object

GetTestDataInt() – Use the JSON object to get the value for the corresponding Key from the JSON file

GetTestDataArray() – Use the JSON object to get the array value for the corresponding Key from the JSON file

Read Also:- How To Get The Execution Time of Multiple Methods In Selenium Java

AddSubtractTest.cs

using CalculatorFramework.Tests;
using CalculatorFramework.Utils;
using JCMSFramework.Utils;
using NUnit.Framework;
using System.Collections.Generic;
namespace CalculatorFramework
{
[Parallelizable]
public class AddSubtractTest : BaseTest
{
readonly List<string> list = JsonHelper.GetTestDataArray("Array");

[TestCase(9, 7)]

public void Addition(double a double b)
{
string str1 = a.ToString();
string str2 = b.ToString();
string result = homePageStep.Add(str1, str2);
int expectedResult = JsonHelper.GetTestDataInt("Addition");
Assert.AreEqual(expectedResult, double.Parse(result), "Result is incorrect");
ReportLog.Pass("Addition of " + a + " and " + b + " is: " + result);
ReportLog.Info(string.Join(", ", list));
}

[TestCase(9, 7)]

public void Subtraction(double a double b)
{
string str1 = a.ToString();
string str2 = b.ToString();
string result = homePageStep.Subtract(str1, str2);
int expectedResult = JsonHelper.GetTestDataInt("Subtraction");
Assert.AreEqual(expectedResult, double.Parse(result), "Result is incorrect");
ReportLog.Pass("Subtraction of " + a + " and " + b + " is: " + result);
ReportLog.Info(string.Join(", ", list));
}
}
}

Read Also:- Fetch Text from Image & PDF Using Selenium Java

MultiplyDivideTest.cs
using CalculatorFramework.Tests;
using CalculatorFramework.Utils;
using JCMSFramework.Utils;
using NUnit.Framework;
using System.Collections.Generic;
namespace CalculatorFramework
{
[Parallelizable]
public class MultiplyDivideTest : BaseTest
{
readonly List<string> list = JsonHelper.GetTestDataArray("Array");

[TestCase(9, 7)]

public void Multiplication(double a, double b)

{
string str1 = a.ToString();
string str2 = b.ToString();
string result = homePageStep.Multiply(str1, str2);
int expectedResult = JsonHelper.GetTestDataInt("Multiplication");
Assert.AreEqual(expectedResult, double.Parse(result), "Result is incorrect");
ReportLog.Pass("Multiplication of " + a + " and " + b + " is: " + result);
ReportLog.Info(string.Join(", ", list));
}

[TestCase(9, 7)]

public void Division(double a, double b)

{
string str1 = a.ToString();
string str2 = b.ToString();
string result = homePageStep.Divide(str1, str2);
int expectedResult = JsonHelper.GetTestDataInt("Division");
Assert.AreEqual(expectedResult, float.Parse(result), "Result is incorrect");
ReportLog.Pass("Division of " + a + " and " + b + " is: " + result);
ReportLog.Info(string.Join(", ", list));
}
}
}

Read Also:- Integrate Extent Report with in NUnit Selenium Framework Screenshots

Project Structure

Project Structure

Reports

Reports

 

 

 

 

 

 

 

 

 

 

Json file

FAQs

  • How to read data from JSON files in selenium using java?

An open standard format called JSON uses text that can be read by humans to transport data objects made up of attribute-value pairs. Features: – Small, easily readable output. Null object fields are handled by default; they are not included in the output by default. The establishment of page locators hierarchies is quite

  • How to extract data from JSON file in c#?

The JSON extract function can be used, like in the example below, to extract the name and project properties from the JSON text. The JSON extract function uses a JSONPath-like expression in the dot. the notation to search the column containing the JSON string. JSONPath conducts a straightforward tree traversal.

  • How to read JSON files in selenium Webdriver?

Data Reading From a JSON File

JSONParser: new JSONParser(); Employee. JSON in the FileReader file reader = new FileReader; /Read a file of JSON FileReader = Object obj = jsonParser.parse;

  • How to read JSON file c#?

Import JSON module to read a JSON file in C#.

  • Using the open() function, open the specified file using the name of the JSON file.
  • Using the open() function, open the specified file using the name of the JSON file.
  • Use load() to read the JSON file and save the data in a variable.

Is Chrome Developer Tool a Future For Test Automation?

  Devtools (Chrome Developer Tool)  is a powerful set of tools that helps web developers to build better applications. In this blog, we will...