please help me, i want send json data to some API which use basic auth and i want catch respon from that API. this is my code:
#Inject
WSClient ws;
public Result testWS(){
JsonNode task = Json.newObject()
.put("id", 123236)
.put("name", "Task ws")
.put("done", true);
WSRequest request = ws.url("http://localhost:9000/json/task").setAuth("user", "password", WSAuthScheme.BASIC).post(task);
return ok(request.tojson);
the question is how i get return from ws above and process it to json? because that code still error. i'm use playframework 2.5
.post(task) results in a CompletionStage<WSResponse>, so you can't just call toJson on it. You have to get the eventual response from the completion stage (think of it as a promise). Note the change to the method signature too.
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.fasterxml.jackson.databind.JsonNode;
import play.libs.Json;
import play.libs.ws.WSAuthScheme;
import play.libs.ws.WSClient;
import play.libs.ws.WSResponse;
import play.mvc.Controller;
import play.mvc.Result;
import scala.concurrent.ExecutionContextExecutor;
#Singleton
public class FooController extends Controller {
private final WSClient ws;
private final ExecutionContextExecutor exec;
#Inject
public FooController(final ExecutionContextExecutor exec,
final WSClient ws) {
this.exec = exec;
this.ws = ws;
}
public CompletionStage<Result> index() {
final JsonNode task = Json.newObject()
.put("id", 123236)
.put("name", "Task ws")
.put("done", true);
final CompletionStage<WSResponse> eventualResponse = ws.url("http://localhost:9000/json/task")
.setAuth("user",
"password",
WSAuthScheme.BASIC)
.post(task);
return eventualResponse.thenApplyAsync(response -> ok(response.asJson()),
exec);
}
}
Check the documentation for more details of working with asynchronous calls to web services.
Related
Need a help to write junit5 test case in springboot for a post api where it uses apache camel producer template to send message to kafka. Please find the controller class details for which junit test cases are required. Note-I don't have any service/repository layer for this.This is standalone controller which is responsible to publish message to kafka by using camel producer template.Thanks is advance.
Controller Class-->
`
`import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rms.inventory.savr.audit.model.AuditInfo;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MockKafkaProducerController {
#Autowired ProducerTemplate producerTemplate;
#Value("${audit.inbound.endpoint.kafka.uri:audit-json-topic}")
private String auditTopicKafka;
#Value("${camel.component.kafka.consumer.supply}")
private String supplyLineUpdateKafkaTopic;
#Value("${camel.component.kafka.consumer.demand}")
private String demandLineUpdateKafkaTopic;
#Value("${camel.component.kafka.consumer.supply-bucket}")
private String supplybucketTopicKafka;
#Value("${camel.component.kafka.consumer.demand-bucket}")
private String demandbucketTopicKafka;
#Value("${camel.component.kafka.consumer.availability}")
private String availabilityTopicKafka;
private Map<String, String> dataTypeTopicMap;
#PostConstruct
void init() {
dataTypeTopicMap =
Map.of(
"SUPPLY_LINE",
supplyLineUpdateKafkaTopic,
"SUPPLY_BUCKET",
supplybucketTopicKafka,
"DEMAND_LINE",
demandLineUpdateKafkaTopic,
"DEMAND_BUCKET",
demandbucketTopicKafka,
"AVAILABILITY",
availabilityTopicKafka);
}
#PostMapping("/api/mock/producer")
public ResponseEntity<Boolean> saveAuditInfo(#RequestBody AuditInfo auditInfo)
public ResponseEntity<Boolean> saveAuditInfo(
#RequestBody AuditInfo auditInfo, #RequestHeader("AUDIT_TYPE") String auditType)
throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
if (auditType == null || auditType.isEmpty()) {
auditType = "SUPPLY_LINE";
}
String topicName = dataTypeTopicMap.get(auditType);
// producerTemplate.
producerTemplate.sendBodyAndHeader(
auditTopicKafka, objectMapper.writeValueAsString(auditInfo), "messageFormat", "CANONICAL");
topicName, objectMapper.writeValueAsString(auditInfo), "messageFormat", "CANONICAL");
return ResponseEntity.ok(Boolean.TRUE);
}
#PostMapping("/api/inventory/audit/mock/producer")
public ResponseEntity<Boolean> publishInventoryAudit(#RequestBody String auditInfo)
public ResponseEntity<Boolean> publishInventoryAudit(
#RequestBody String auditInfo, #RequestHeader("AUDIT_TYPE") String auditType)
throws JsonProcessingException {
producerTemplate.sendBody(auditTopicKafka, auditInfo);
if (auditType == null || auditType.isEmpty()) {
auditType = "SUPPLY_LINE";
}
String topicName = dataTypeTopicMap.get(auditType);
producerTemplate.sendBody(topicName, auditInfo);
return ResponseEntity.ok(Boolean.TRUE);
}
}`
`
I tried to mock producer template but not able to fix.
I'm trying to get a PACT test running on JUnit5. We use JUnit4 for others, but this one will be JUnit5. The error occurs when running the JUnit5 test using the pact annotation on the RequestResponsePact method.
Error : No method annotated with #Pact was found on test class ConsumerContractTest for provider ''.
I've seen Basic Pact/Junit5 Test Setup fails. No method annotated with #Pact was found for provider error, but this is issue was due to the #PactTestFor(pactMethod = "examplePact") not matching the #Pact method name. But on my code it does match.
I can't seem to figure out why I get the error and especially why the error has an empty provider(provider '') despite defining one("some-provider").
Example code :
import au.com.dius.pact.consumer.MockServer
import au.com.dius.pact.consumer.Pact
import au.com.dius.pact.consumer.dsl.PactDslJsonArray
import au.com.dius.pact.consumer.dsl.PactDslWithProvider
import au.com.dius.pact.consumer.junit5.PactConsumerTestExt
import au.com.dius.pact.consumer.junit5.PactTestFor
import au.com.dius.pact.model.RequestResponsePact
import groovyx.net.http.RESTClient
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.http.HttpStatus
#ExtendWith(PactConsumerTestExt.class)
class ConsumerContractTest {
#Pact(consumer = "some-consumer", provider = "some-provider")
RequestResponsePact examplePact(PactDslWithProvider builder) {
builder
.given("provider state")
.uponReceiving("Contract description")
.method("GET")
.matchPath("/endpoint")
.willRespondWith()
.status(200)
.headers(["Content-Type": "application/vnd.pnf.v1+json"])
.body(new PactDslJsonArray())
.toPact()
}
#Test
#PactTestFor(pactMethod = "examplePact")
void exampleTest(MockServer mockServer) {
def client = new RESTClient(mockServer.getUrl())
}
}
Not sure if that's just the gist you've posted here but I see the return word missing and also the #PactTestFor annotation missing the provider and version. Here is an example I have that works for my project.
import au.com.dius.pact.consumer.dsl.DslPart;
import au.com.dius.pact.consumer.dsl.PactDslJsonBody;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.consumer.junit5.PactConsumerTestExt;
import au.com.dius.pact.consumer.junit5.PactTestFor;
import au.com.dius.pact.core.model.PactSpecVersion;
import au.com.dius.pact.core.model.RequestResponsePact;
import au.com.dius.pact.core.model.annotations.Pact;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.HashMap;
import java.util.Map;
import static com.example.mbbackend.config.Constants.*;
import static com.example.mbbackend.util.Utils.getRequestSpecification;
import static org.junit.jupiter.api.Assertions.assertEquals;
#ExtendWith(PactConsumerTestExt.class)
class GetActorIT {
Map<String, String> headers = new HashMap<>();
String path = "/api/mb/actor/";
#Pact(provider = PACT_PROVIDER, consumer = PACT_CONSUMER)
public RequestResponsePact createPact(PactDslWithProvider builder) {
headers.put("Content-Type", "application/json");
DslPart bodyReturned = new PactDslJsonBody()
.uuid("id", "1bfff94a-b70e-4b39-bd2a-be1c0f898589")
.stringType("name", "A name")
.stringType("family", "A family")
.stringType("imageUrl", "http://anyimage.com")
.close();
return builder
.given("A request to retrieve an actor")
.uponReceiving("A request to retrieve an actor")
.pathFromProviderState(path + "${actorId}", path + "1bfff94a-b70e-4b39-bd2a-be1c0f898589")
.method("GET")
.headers(headers)
.willRespondWith()
.status(200)
.body(bodyReturned)
.toPact();
}
#Test
#PactTestFor(providerName = PACT_PROVIDER, port = PACT_PORT, pactVersion = PactSpecVersion.V3)
void runTest() {
//Mock url
RequestSpecification rq = getRequestSpecification().baseUri(MOCK_PACT_URL).headers(headers);
Response response = rq.get(path + "1bfff94a-b70e-4b39-bd2a-be1c0f898589");
assertEquals(200, response.getStatusCode());
}
}
Hi I'm trying to make a request to external service with the use of httpClient vert.x but I keep getting error: Search domain query failed. Original hostname: 'google.com' failed to resolve 'google.com'
What am i missing in the code below? I'm not sure about those AddressResolverOptions, I have read about them but still I'm not sure what they are responsible for. I'd like to make the request the simplest possible way but the more I investigate the more difficult it seems
package io.vertx.starter;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.dns.AddressResolverOptions;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.URL;
import java.util.Collections;
#RunWith(VertxUnitRunner.class)
public class MainVerticleTest {
private Vertx vertx;
#Before
public void setUp(TestContext tc) {
vertx = Vertx.vertx(new VertxOptions().setAddressResolverOptions(
new AddressResolverOptions().addSearchDomain("google.com").addSearchDomain("bar.com"))
);
// vertx = Vertx.vertx();
vertx.deployVerticle(MainVerticle.class.getName(), tc.asyncAssertSuccess());
}
#After
public void tearDown(TestContext tc) {
vertx.close(tc.asyncAssertSuccess());
}
#Test
public void testThatTheServerIsStarted(TestContext tc) {
final HttpClientOptions httpClientOptions = new HttpClientOptions();
httpClientOptions.setConnectTimeout(300);
httpClientOptions.setIdleTimeout(5);
// httpClientOptions.` `
httpClientOptions.setSsl(true).setTrustAll(true);
// final URL url = new URL("currentUrl");
Async async = tc.async();
vertx.createHttpClient(httpClientOptions).getNow(
443,"google.com", "/", response -> {
System.out.println(response.statusCode());
async.complete();
});
//
// Async async = tc.async();
// vertx.createHttpClient().getNow(8080, "localhost", "/", response -> {
// tc.assertEquals(response.statusCode(), 200);
// response.bodyHandler(body -> {
// tc.assertTrue(body.length() > 0);
// async.complete();
// });
// });
}
}
I have a couple of spring boot rest controllers, and I want a standard JSON response structure to be sent to the client.
The standard response will be composed of responseTime, apiResponseCode, status, apiName, response ( which will vary based on the api). See below:
{
"responseTime": "2020-04-19T08:36:53.001",
"responseStatus": "SUCCESS",
"apiResponseCode": "SUCCESS",
"apiName": "PROPERTY_STORE_GET_PROPERTIES",
"response": [
{
"propertyName": "app.name",
"propertyValue": "property-store"
}
]
}
To achieve this, I have created below model class:
package com.example.response.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import com.example.constants.ApiResponseCode;
import com.example.constants.Status;
public class ApplicationResponse<T> implements Serializable {
private static final long serialVersionUID = -1715864978199998776L;
LocalDateTime responseTime;
Status responseStatus;
ApiResponseCode apiResponseCode;
String apiName;
T response;
public ApplicationResponse(LocalDateTime responseTime, Status status,
ApiResponseCode apiRespCode, String apiName, T response) {
this.responseTime = responseTime;
this.responseStatus = status;
this.apiResponseCode = apiRespCode;
this.apiName = apiName;
this.response = response;
}
// getters and setters
To create a generic response wrapper, I have created below response util class.
import java.time.LocalDateTime;
import com.example.constants.ApiResponseCode;
import com.example.constants.Status;
import com.example.response.model.ApplicationResponse;
public class ResponseUtil {
public static <T> ApplicationResponse<T> createApplicationResponse(String
apiName, T response) {
return new ApplicationResponse<>(LocalDateTime.now(),
Status.SUCCESS, ApiResponseCode.SUCCESS, apiName,
response);
}
private ResponseUtil() {
}
}
Now the ask is that my response from controller should get serialized in the standard way. Shown below is my controller method.
package com.example.propertystore.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RestController;
import com.example.constants.ApiResponseCode;
import com.example.constants.Status;
import com.example.exception.ApplicationException;
import com.example.exception.ApplicationExceptionHelper;
import com.example.propertystore.constants.PropertyStoreApiName;
import com.example.propertystore.dto.PropertyDTO;
import com.example.propertystore.entity.Property;
import com.example.propertystore.service.PropertyStoreService;
import com.example.response.ResponseUtil;
import com.example.response.model.ApplicationResponse;
#RestController
public class PropertyStoreControllerImpl implements PropertyStoreController {
#Autowired
PropertyStoreService propertyStoreService;
#Autowired
ApplicationExceptionHelper exceptionHelper;
#Override
public ApplicationResponse<List<PropertyDTO>> getProperties() throws ApplicationException {
ApplicationResponse<List<PropertyDTO>> response = null;
try {
response = ResponseUtil.createApplicationResponse(
PropertyStoreApiName.PROPERTY_STORE_GET_PROPERTIES.toString(),
propertyStoreService.getProperties());
} catch (Exception e) {
exceptionHelper.raiseApplicationException( HttpStatus.INTERNAL_SERVER_ERROR, Status.FAILURE,
ApiResponseCode.INTERNAL_SERVER_ERROR,
PropertyStoreApiName.PROPERTY_STORE_GET_PROPERTIES.toString(), null);
}
return response;
}}
With the current implementation what I'll have to do is that in my controllers I will have to transform the response by calling ResponseUtil.createApplicationResponse(). This is going to litter the entire controller methods with the createApplicationResponse() method call.
What I wanted to explore is that if there is any cleaner way of achieving this using servlet filters or AOP?
PS: I tried filter option, but couldn't understand how to proceed around it. Got stuck after retrieving the response.getOutputStream() in doFilter().
Hope someone can help?
Just wrap all your responses into a decorator object.
class ResponseDecorator<T> {
//global.fields (time,code, status.....)
T response;
}
Then wrap this response wrapper into the ResponseEntity
The response.getOutputStream that you used and filters are servlet related classes , and i think you can do that without them.Just make your custom response class and add fields however you want your response. Than in the controller , just return new ResponseEntity(HttpStatus.OK,"your message "):
I don't know if this is the behavior you want.
I'm trying to parse the request sent to a java based fulfillment in V2 of the API. I can't find any example documentation in Java for doing this in V2 of the API (com.google.cloud:google-cloud-dialogflow:0.38.0-alpha dependency in my project).
So far I've got as far as writing a very basic Spring MVC controller to accept the request.
How can I parse out the payload in the request, e.g. the parameters that dialog flow sent ?
import com.google.cloud.dialogflow.v2beta1.WebhookRequest;
import com.google.cloud.dialogflow.v2beta1.WebhookResponse;
import com.google.protobuf.Descriptors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
#RestController
#RequestMapping("test")
public class TestRequestRestController {
private static final Logger log = LoggerFactory.getLogger(TestRequestRestController.class);
#PostMapping("test1t")
public WebhookResponse getTest1(WebhookRequest request) {
System.out.println(request.toString());
return WebhookResponse.newBuilder().setFulfillmentText("Example reply 1 ").build();
}
}
Not sure about WebhookRequest and WebhookResponse.
The code below code might help you.
import org.springframework.http.HttpEntity;
#PostMapping("test1t")
public String getTest1(HttpEntity<String> httpEntity) {
String reqObject = httpEntity.getBody();
System.out.println("request json object = "+reqObject);
//Get the action
JSONObject obj = new JSONObject(reqObject);
String action = obj.getJSONObject("result").getString("action");
//Get the parameters
JSONObject params = obj.getJSONObject("result").getJSONObject("parameters");
String response = "Hello from Java.";
return "{'speech': '"+response+"', 'displayText':'"+response+"'}";
}