Can you please advise How to mock the Rest Template - java

Is there any possibility to write the mockito condition on it. if not let me know how to change the actual code.
String url = new StringBuilder(EPARTNER_MICRO_SERVICE_URL).append(service).toString();
RequestEntity<String> requestEntity = new RequestEntity<String>(prePreocess(ePartnerRestRequestDTO), HttpMethod.POST, new URI(url));
Instant before = Instant.now();
ResponseEntity<String> response = new RestTemplate().exchange(requestEntity, String.class);
logger.info("ePartner service " + url + " - duration (milliseconds) :: " + Duration.between(before, Instant.now()).toMillis());
if(isObjectPresent(response) && isObjectPresent(response.getStatusCode()) && HttpStatus.OK == response.getStatusCode()) {
ePartnerRestResponseDTO = postProcess(JWSResponseUtil.verifyJWSSignatureAndExtractPayload(response.getBody()));

Related

Services set with status code different from 200 are failed

My goal is to test my services depending on their service HTTP status.
When I launch my request, just services set by the 200 value succeed but another status like 400, 500, etc. failed that can be seen on the logs.
I am using soaPUI for a testing application located on the Tomcat server. The tracks of my requests are logged on another application before that test, the HTTP status was unique and set for all called services.
Now, for my test I have to dissociate the HTTP status code of my services, that is to each service with its own HTTP status depending on my tests needs.
code:
import com.eviware.soapui.impl.rest.mock.RestMockResult
import java.nio.charset.Charset
import com.eviware.soapui.model.mock.MockRunListener
import groovy.json.JsonSlurper
httpStatus = 200
def writeOut(fileEndPath, mockResult, method) {
def jsonFile = new File(dataDir + fileEndPath)
log.info "jsonFile " + jsonFile
if("GET".equalsIgnoreCase(method)){
mockRequest.httpResponse.status = httpStatus
mockRequest.httpResponse.setContentType("application/json")
mockRequest.httpResponse.writer.print(jsonFile.getText("UTF-8"))
mockRequest.httpResponse.writer.flush()
}
}
def isFileToReturnExist(fileToReturn){
def fileExist = false
if(fileToReturn != null){
def fileToTest = new File(dataDir + fileToReturn)
if( fileToTest.exists() && fileToTest.canRead()){
fileExist = true
}
}
return fileExist
}
dataDir = new File(context.getMockService().getProject().path).parent
def services = ["Service1", "Service2", "Service3", "Service4",
"Service5", "Service6", "Service7","Service8"]
def status = [200, 400, 200, 200, 400, 200, 200, 200]
def temp =
mockRequest.getHttpRequest().getQueryString().split("fields=")
if ( temp.size() == 2){
temp = temp[1].split("&")
if ( temp.size() > 0){
infos = temp[0]
for(int i=0; i< services.size; i++){
el = services[i]
if ( infos.split(",").size() > 1 && (infos.split(",")
[1]== el || infos.split(",")[0]== el)){
infos = el
httpStatus = status[i]
break;
}
}
}
}
inf = infos.split(",")
log.info inf.size()
def docroot = "/pns/"+infos
def method = mockRequest.getHttpRequest().getMethod();
def queryString = mockRequest.getHttpRequest().getPathInfo()
log.info "method " + method
log.info "queryString " + queryString
if(queryString != null){
def list = queryString.trim().split("/")
def credValue = list[list.size()-1].tokenize('|')[0]
def typecredential = ""
def lstcredtemp = list[list.size()-2].tokenize('|')
if ( lstcredtemp.size() > 0){
typecredential = lstcredtemp[0] + "_"
}
if("GET".equalsIgnoreCase(method)){
fileToReturn = docroot + "/Response_" + typecredential +
credValue + ".json"
}
}
if(!isFileToReturnExist(fileToReturn)){
log.info "le fichier " + fileToReturn + " n'existe pas"
fileToReturn = docroot+"/error.json"
}
RestMockResult mockResult = new RestMockResult( mockRequest )
if (fileToReturn != null) {
writeOut(fileToReturn, mockResult, method)
}
log.info typecredential + " fileToReturn : " + fileToReturn
return mockResult
The log application is supposed to trace for services with status 200 a START line and STOP line with OK.
For services with status code 400 (according to the code) are traced with a START line and a STOP line with KORG, the return code and the description of the error.
But my actual results are that for services with the status code 400, I get just the START line, but not the STOP line with error description and so on.
NTL;NTL;FRO;GetMyServices;START;;;IBTIs;IBTIt;.......;
NTL;FRO;SP;getPns[Service1];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service1];STOP;OK;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service3];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service5];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service2];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service4];START;;;IBTIs;IBTIt;
NTL;FRO;ADVISE;getProposal;START;;;IBTIs;IBTIt;
NTL;FRO;SPX;getProposal;STOP;OK;200;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service3];STOP;OK;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service6];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service4];STOP;KORG;Mapping
exception;IBTIs;IBTIt;Mapping exception reponse pnsGatape;
NTL;FRO;SP;getPns[Service6];STOP;OK;;IBTIs;IBTIt;
NTL;NTL;FRO;GetMyServices;STOP;OK;;IBTIs;IBTIt;....

Junit5 TestReporter

I was trying understand TestReporter in Junit5
#BeforeEach
void beforeEach(TestInfo testInfo) {
}
#ParameterizedTest
#ValueSource(strings = "foo")
void testWithRegularParameterResolver(String argument, TestReporter testReporter) {
testReporter.publishEntry("argument", argument);
}
#AfterEach
void afterEach(TestInfo testInfo) {
// ...
}
what is the use of publishEntry in TestReporter,
Can someone explain me.. Thanks in Advance..
"TestReporter" in conjunction with "TestInfo" gives an instance of the current test, this way you can get info about your actual test. and then publish it, in this example used as kind of logger.
StringBuffer is used for his mutable, fast, and synchonized characteristics, required for a test.
public class TestReporterTest {
StringBuffer sbtags = new StringBuffer();
StringBuffer displayName = new StringBuffer();
StringBuffer className = new StringBuffer();
StringBuffer methodName = new StringBuffer();
#BeforeEach
void init(TestInfo testInfo) {
className.delete( 0, className.length());
className.append( testInfo.getTestClass().get().getName());
displayName.delete( 0, displayName.length());
displayName.append( testInfo.getDisplayName());
methodName.delete( 0, methodName.length());
methodName.append( testInfo.getTestMethod().get().getName());
}
#Test
#DisplayName("testing on reportSingleValue")
void reportSingleValue(TestReporter testReporter) {
testReporter.publishEntry( "className : " + className);
testReporter.publishEntry( "displayName: " + displayName);
testReporter.publishEntry("methodName : " + methodName);
testReporter.publishEntry("algun mensaje de estatus");
}
#Test
void reportKeyValuePair(TestReporter testReporter) {
testReporter.publishEntry( "className : " + className);
testReporter.publishEntry( "displayName: " + displayName);
testReporter.publishEntry("methodName : " + methodName);
testReporter.publishEntry("una Key", "un Value");
}
#Test
void reportMultiKeyValuePairs(TestReporter testReporter) {
Map<String, String> map = new HashMap<>();
map.put("Fast and Furious 8","2018");
map.put("Matrix","1999");
testReporter.publishEntry( "className : " + className);
testReporter.publishEntry( "displayName: " + displayName);
testReporter.publishEntry("methodName : " + methodName);
testReporter.publishEntry(map);
}
}
Running the Test
timestamp = 2019-11-22T12:02:45.898, value = className : TestReporterTest
timestamp = 2019-11-22T12:02:45.904, value = displayName: testing on reportSingleValue
timestamp = 2019-11-22T12:02:45.904, value = methodName : reportSingleValue
timestamp = 2019-11-22T12:02:45.904, value = algun mensaje de estatus
timestamp = 2019-11-22T12:02:45.919, value = className : TestReporterTest
timestamp = 2019-11-22T12:02:45.920, value = displayName: reportMultiKeyValuePairs(TestReporter)
timestamp = 2019-11-22T12:02:45.920, value = methodName : reportMultiKeyValuePairs
timestamp = 2019-11-22T12:02:45.921, Fast and Furious 8 = 2018, Matrix = 1999
timestamp = 2019-11-22T12:02:45.924, value = className : TestReporterTest
timestamp = 2019-11-22T12:02:45.925, value = displayName: reportKeyValuePair(TestReporter)
timestamp = 2019-11-22T12:02:45.925, value = methodName : reportKeyValuePair
timestamp = 2019-11-22T12:02:45.925, una Key = un Value
Apart from the previous answers, When we are writing junit test scripts if we want to get some information out of the process we normally do System.out.println which is not recommended in corporate/enterprise world. Specially in code reviews, peer reviews we are advised to remove all the System.out.println from the code base. So in the junit world if we want to push or publish out of the scripts we are advised to use TestReporter publishEntry() method. With the combination of TestInfo we could read several information out of the original junit scripts.
Hope this facts also support your question.
The method name suggests you are publishing a new entry to the report, which is supported by the Java Doc for 5.3.0
https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/TestReporter.html
This would allow you to add additional, useful information to the test report; perhaps you would like to add what the tests initial conditions are to the report or some environmental information.

HTTP 400 response Servlet

The below code is part of a servlet which is taking the cookie value and sending request to another service with the same cookie value with additional headers.
I am getting HTTP 400 response on the responseCode = serviceUrlConnection.getResponseCode(); and on is = serviceUrlConnection.getInputStream();.
With the same input values (cookie and additional headers), I able to get correct output from the service using SOAP UI. Could somebody point out the mistake.
URL serviceURL = new URL(serviceUrlInput);
logger.info(" Validate Test token service Url" + serviceUrlInput);
URLConnection serviceConnection = serviceURL.openConnection();
HttpURLConnection serviceUrlConnection = (HttpURLConnection)serviceConnection;
serviceUrlConnection.setRequestProperty("Content-Type", "application/json");
serviceUrlConnection.setRequestProperty("charset", "UTF-8");
String TestCookieValue = null;
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("Test")) {
//TestToken = cookies[i].getValue();
TestCookieValue = cookies[i].getValue();
logger.info("Test cookie : " + "Test=" +TestCookieValue);
//serviceUrlConnection.setRequestProperty("Cookie", TestCookie.substring(0, TestCookie.indexOf(';')));
serviceUrlConnection.setRequestProperty("Cookie", "Test=" +TestCookieValue);
break;
}
}
}
//Set the timestamp in the header
Date javaUtilDate = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String formattedDateTime = formatter.format(javaUtilDate);
serviceUrlConnection.setRequestProperty("timestamp", formattedDateTime);
logger.info(adapterDescription + " :: timestamp added with value :: " + formattedDateTime);
//Set the transactionId header
UUID uuid = java.util.UUID.randomUUID();
serviceUrlConnection.setRequestProperty("transactionId", uuid.toString());
logger.info(adapterDescription + " :: transactionID added with value :: " + uuid.toString());
//Set the sourceSystem header
String sourceSystem = + InetAddress.getLocalHost().getHostName();
serviceUrlConnection.setRequestProperty("sourceSystem", sourceSystem);
logger.info(adapterDescription + " :: sourceSystem added with value :: " + sourceSystem);
int responseCode;
serviceUrlConnection.setDoOutput(true);
wr = new DataOutputStream(serviceUrlConnection.getOutputStream());
wr.writeBytes("");
logger.info(adapterDescription +" :: " + wr);
responseCode = serviceUrlConnection.getResponseCode();
logger.info(adapterDescription +":: responseCode :: " + responseCode);
is = serviceUrlConnection.getInputStream();
Error 400 means that there's something wrong with your request. A few things to check:
Is the server really expecting a GET request, not a POST? To do a post you can call serviceUrlConnection.setRequestMethod("POST")
You are settings setDoOutput(true) but are not writing anything in the request. Maybe you need to write some content.
By default the request method is GET. So, If no data need to be sent over, we dont need to set the DataOutputStream and also no need to call setDoOutput(true)
/*
Commented out the below lines:-
wr = new DataOutputStream(serviceUrlConnection.getOutputStream());
serviceUrlConnection.setDoOutput(true);
*/
See an exiting SO question :-
HttpURLConnection sends a POST request even though httpCon.setRequestMethod("GET"); is set

Neo4j Executing cypher query via rest

Good Morning,
I set up a local Neo4j database and want to model a graph of maven dependencies.
When I execute the following statement via the webconsole, everything works fine:
start root = node(1)
create unique root -[:ROOT]-> (n{groupId:'fancyStuff',artifactId:'somewhat', version:'1.4'})
return n
(note: rootnode is there for debugging purposes, will be replaced by actual structure later)
So, here everything works fine, no matter of how much whitespaces I take or replacing ' with "
In my java application i have the following function:
private static URI getOrCreate(Artifact artifact){
String cypherUri = SERVER_ROOT_URI + "cypher";
String cypherStatement="{\"query\" : \"start x = node(1) " +
"create unique x -[:ROOT]-> (artifact{groupId:\"" + artifact.getGroupID() +
"\", artifactId:\"" + artifact.getArtifactID() +
"\", version: \"" + artifact.getVersion() +
"\"}) return artifact ,\"params\" : {}}";
WebResource resource = Client.create()
.resource( cypherUri );
ClientResponse response = resource.accept( MediaType.APPLICATION_JSON_TYPE )
.type( MediaType.APPLICATION_JSON_TYPE )
.entity( cypherStatement )
.post( ClientResponse.class );
System.out.println( String.format( "POST to [%s], status code [%d]",
cypherUri, response.getStatus() ) );
response.close();
return response.getLocation();
}
so basically I post a json file looking like
{"query" : "start root = node(1) create unique root-[:ROOT]->(artifact{groupId:'{"query" : "start root = node(1) create unique root-[:ROOT]->(artifact{groupId:'lol',artifactId:'somewhat',version:'1.4'}) return artifact","params" : {}}
also no matter what whitespacing or "/' I use I get an http 500 error, saying the first - of the relationship -[:ROOT]-> is invalid.
Posting new nodes directly via
final String nodeEntryPointUri = SERVER_ROOT_URI + "node";
WebResource resource = Client.create().resource( nodeEntryPointUri );
ClientResponse response = resource.accept( MediaType.APPLICATION_JSON_TYPE )
.type( MediaType.APPLICATION_JSON_TYPE )
.entity( /*some json*/)
.post(ClientResponse.class);
(Disclaimer: I will move the params to the right place asap this version works ;) )
I could bet it's some totally trivial error, but I'm staring at this for over half a workday right now and none of my variations want to work.
Would be awesome if somebody knows an answer.
Greetings,
Florian Rohm
The problem is you have invalid JSON. You repeat query twice. If you delete the part between stars, does it work?
**{"query" :
"start root = node(1)
create unique root-[:ROOT]->(artifact{groupId:'**
{"query" : "start root = node(1)
create unique root-[:ROOT]->(artifact{groupId:'lol',artifactId:'somewhat',version:'1.4'})
return artifact",
"params" : {}
}
Ok, i don't know what's different with this statement but this works (I tried the param split in the above code, too):
String cypherUri = SERVER_ROOT_URI + "cypher";
JSONObject jObject = new JSONObject();
try {
Map<String, String> params = new HashMap<String, String>();
params.put("groupId", artifact.getGroupID());
params.put("artifactId", artifact.getArtifactID());
params.put("version", artifact.getVersion());
String query = "start x = node(1) create unique x-[:ROOT]->(n{groupId:{groupId},artifactId:{artifactId},version:{version} }) return n";
jObject.put("query", query);
jObject.put("params", params);
} catch (Exception e) {
e.printStackTrace();
}
WebResource resource = Client.create()
.resource( cypherUri );
ClientResponse response = resource.accept( MediaType.APPLICATION_JSON_TYPE )
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(jObject.toString())
.post(ClientResponse.class);
But anyways, the second attempt is nicer and I won't complain :D
It just bugs me not to know what's going on there...

Returning JSON response from Servlet to Javascript/JSP page

I think (actually I KNOW!) I'm doing something wrong here I am trying to populate some values into HashMap and add each hasmap to a list which will be added to a JSON object:
JSONObject json = new JSONObject();
try
{
Map address;
List addresses = new ArrayList();
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new HashMap();
address.put("CustomerName" , "Decepticons" + i);
address.put("AccountId" , "1999" + i);
address.put("SiteId" , "1888" + i);
address.put("Number" , "7" + i);
address.put("Building" , "StarScream Skyscraper" + i);
address.put("Street" , "Devestator Avenue" + i);
address.put("City" , "Megatron City" + i);
address.put("ZipCode" , "ZZ00 XX1" + i);
address.put("Country" , "CyberTron" + i);
addresses.add(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.setContentType("application/json");
response.getWriter().write(json.toString());
My problem is I know this is returning a string, which I cannot seem to parse (which is the problem). My question is how do I return the actual JSON encoded string (or even should I be doing this?) or what is the best method of attack for this type of problem. The JavaScript I am using for this is below:
function getReadyStateHandler(req)
{
// Return an anonymous function that listens to the
// XMLHttpRequest instance
return function ()
{
// If the request's status is "complete"
if (req.readyState == 4)
{
// Check that a successful server response was received
if (req.status == 200)
{
msgBox("JSON Response recieved...");
populateDatagrid(req.responseText.toJSON());
}
else
{
// An HTTP problem has occurred
alert("HTTP error: " + req.status);
}
}
}
}
Note the JSON Response comes back fine, but its a string. Any advice is greatly appreciated. I am also opening to using googles Gson, but don't have too much knowledge on that.
Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe the following:
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new JSONObject();
address.put("CustomerName" , "Decepticons" + i);
address.put("AccountId" , "1999" + i);
address.put("SiteId" , "1888" + i);
address.put("Number" , "7" + i);
address.put("Building" , "StarScream Skyscraper" + i);
address.put("Street" , "Devestator Avenue" + i);
address.put("City" , "Megatron City" + i);
address.put("ZipCode" , "ZZ00 XX1" + i);
address.put("Country" , "CyberTron" + i);
addresses.add(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.setContentType("application/json");
response.getWriter().write(json.toString());
This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel
I used JSONObject as shown below in Servlet.
JSONObject jsonReturn = new JSONObject();
NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);
map = new HashMap<String, String>();
map.put("Status", "Success");
map.put("FailureReason", "None");
map.put("DataElements", "2");
jsonReturn = new JSONObject();
jsonReturn.accumulate("Header", map);
List<String> list = new ArrayList<String>();
list.add(NhAdminTree);
list.add(userName);
jsonReturn.accumulate("Elements", list);
The Servlet returns this JSON object as shown below:
response.setContentType("application/json");
response.getWriter().write(jsonReturn.toString());
This Servlet is called from Browser using AngularJs as below
$scope.GetNeighborhoodTreeUsingPost = function(){
alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );
$http({
method: 'POST',
url : 'http://localhost:8080/EPortal/xlEPortalService',
headers: {
'Content-Type': 'application/json'
},
data : {
'action': 64,
'userName' : $scope.userName
}
}).success(function(data, status, headers, config){
alert("DATA.header.status : " + data.Header.Status);
alert("DATA.header.FailureReason : " + data.Header.FailureReason);
alert("DATA.header.DataElements : " + data.Header.DataElements);
alert("DATA.elements : " + data.Elements);
}).error(function(data, status, headers, config) {
alert(data + " : " + status + " : " + headers + " : " + config);
});
};
This code worked and it is showing correct data in alert dialog box:
Data.header.status : Success
Data.header.FailureReason : None
Data.header.DetailElements : 2
Data.Elements : Coma seperated string values i.e. NhAdminTree, userName
I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?
If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON

Categories

Resources