I am trying to call a service in another Spring Boot application using RestTemplate,like below:
#RestController
public class Controller {
#Autowired
RestTemplate restTemplate;
#RequestMapping("/hello")
public String getHi() {
return restTemplate.getForObject("http://localhost:8082/hello", String.class);
}
}
This is the Main class for application A:
#SpringBootApplication
public class ServiceApplication {
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
Below the other Spring Boot application B:
#RestController
public class Controller {
#RequestMapping ("/hello")
public String getHi() {
return "Hi";
}
}
Application A (RestTemplate): In this I am trying to achieve the API call to go through like, Postman -> Application A -> Application B. I tried this API with Postman, but the request is not sent. Just showing "Sending request...". Also didn't get failure response.
Application B: Called GET endpoint from Postman which invokes getHi() in
Controller(RestController) class in Postman and browser, both work fine.
Port used:
Application A: 8083
Application B: 8082
Both applications are running. I have gone through lots of websites and git codes, but couldn't find a solution.
Related
This works, I am able to make a request in postman for this Service.
#RestController
#Path("sample")
public class SampleClass {
#GET
#Path(value = "/s1")
public Object get() {
//Something
}
}
The problem is when I try to use #RequestMapping instead of #Path, I get a
404 Not Found
Error.
#RestController
#RequestMapping("sample")
public class CommonService {
#GetMapping(value = "/s1", produces = MediaType.APPLICATION_JSON)
public Object get() {
//Something
}
}
What I am doing wrong here?
After a while, I found out that for the JAX-RS (#Path) I had configured in web.xml file a different route "something".
JAX-RS: localhost:8080**/something**/sample/s1
Spring Rest Services: localhost:8080/sample/s1
I was also missing a "/" in the Spring Rest Service.
#RequestMapping("**/**sample")
Full code bellow:
#RestController
#RequestMapping("/sample")
public class CommonService {
#GetMapping(value = "/s1", produces = MediaType.APPLICATION_JSON)
public Object get() {
//Something
}
}
I have a Spring Boot application which needs to occasionally publish messages to GCP PubSub. I implemented it following the instructions on the spring boot page (https://spring.io/guides/gs/messaging-gcp-pubsub/) so I have implemented the following configuration file:
#Configuration
public class PubSubConfiguration {
#Value("${myprog.pubsub.sms-topic}")
private String topic;
#Bean
#ServiceActivator(inputChannel = "pubsubOutputChannel")
public MessageHandler messageSender(PubSubTemplate pubsubTemplate) {
return new PubSubMessageHandler(pubsubTemplate, this.topic);
}
#MessagingGateway(defaultRequestChannel = "pubsubOutputChannel")
public interface PubsubOutboundGateway {
void sendToPubsub(String text);
}
}
From my rest controller, I autowire the message gateway and call sendToPubsub:
#RequestMapping("/api/stuff")
#RestController
public class StuffController {
PubSubConfiguration.PubsubOutboundGateway messagingGateway;
#Autowired
public StuffController(#SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") PubSubConfiguration.PubsubOutboundGateway messagingGateway) {
this.messagingGateway = messagingGateway;
}
#RequestMapping(method = RequestMethod.POST, path = "/go")
public ResponseEntity<String> send() {
messagingGateway.sendToPubsub("TEST");
return new ResponseEntity<>("Ok!", HttpStatus.OK);
}
}
This works, however due to our particular use case I would like to respond with an error if publishing fails. If, for example, I configure a non-existent topic I would like to return a 500 error whereas it currently returns 200 and throws an exception asynchronously later. Is there any way I can access a future at the point of publishing?
Spring Cloud GCP PubSub implementation uses Spring Integration framework and rely on it. For this, your send to PubSub method have to throw an exception as described in the Spring integration documentation
#MessagingGateway(defaultRequestChannel = "pubsubOutputChannel")
public interface PubsubOutboundGateway {
void sendToPubsub(String text) throws MessagingException;
}
I have a Spring application with Apache Wicket (Its my first Spring-Application) and its autogenerated. If I run my application and I call it on localhost there is only shown a site with "TestDataManager is running" on it instead of the Site I call in the Main. I figured out that I have in the tests- package a class named ExampleController and its not from me. In this class is witten what is shown on localhost. But in my Main I dont call this Class.
Can Somone say how to fix this.
#SpringBootApplication
#RestController
public class Application extends WebApplication {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public Class<? extends Page> getHomePage() {
return WhatToDoPage.class;
}
}
ExampleController:
#RestController
public class ExampleController {
#Value("TestDataManager is running")
private String message;
#GetMapping("/")
public String indexGet() {
return message;
}
}
Spring Boot scans the classpath, finds ExampleController and registers it as a REST controller bean.
Later when you make a call to / it uses it to return the response. Since you return a String without #GetMapping(produces = ...) it uses text/plain as response content type.
Apache Wicket is not involved in your application. I am not sure why you use/tag it.
Was trying out RSocket Request/Response as specified in section 4 of https://www.baeldung.com/spring-boot-rsocket. So there is a RSocketServer autoconfigured and listening at port 7000. Unable to connect to the method annotated with #GetMapping when hitting the same from browser
#RestController
public class MarketDataRestController {
private final RSocketRequester rSocketRequester;
public MarketDataRestController(RSocketRequester rSocketRequester) {
this.rSocketRequester = rSocketRequester;
}
#GetMapping(value = "/current/{stock}")
public Publisher<MarketData> current(#PathVariable("stock") String stock) {
return rSocketRequester
.route("currentMarketData")
.data(new MarketDataRequest(stock))
.retrieveMono(MarketData.class);
}
}
Expecting to be able to connect to the current() of the class MarketDataRestController annotated with #GetMapping when requesting the same from browser, say e.g.: http://localhost:7000/current/APPLE.
Not sure how to connect to the same.
You can't use #RequestMapping with sockets, use #MessageMapping instead:
instead of #RequestMapping or #GetMapping annotations like in Spring MVC, we will use the #MessageMapping annotation:
#Controller
public class MarketDataRSocketController {
private final MarketDataRepository marketDataRepository;
public MarketDataRSocketController(MarketDataRepository marketDataRepository) {
this.marketDataRepository = marketDataRepository;
}
#MessageMapping("currentMarketData")
public Mono<MarketData> currentMarketData(MarketDataRequest marketDataRequest) {
return marketDataRepository.getOne(marketDataRequest.getStock());
}
How does one invoke methods in a rest service that is not written in spring or java (its wcf rest service) using JUnit & Spring?
Note: I want to do HTTP-GET so mocking is not the case here.
Does Spring let me use restTemplate.getForObject(..) from JUnit? Cucumber?
So far I have a client written using Spring:
#SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
private static final String SERVICE_URL="http://localhost:12345/PrivilegesService/IsAlive";
public static void main(String args[]) {
SpringApplication.run(Application.class);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
#Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
boolean response = restTemplate.getForObject(SERVICE_URL, boolean.class);
log.info("response: "+ response); // print : true
};
}
}
I want my tests look :
public class StepDefinitions {
#When("^application is up$")
public void the_client_issues_GET_version(){
}
#Then("^the server should be running$")
public void the_client_receives_status_code_of() {
boolean response = restTemplate.getForObject(SERVICE_URL, boolean.class);
AssertTrue(true,response);
}
}
RestTemplate works in Junit as well. It doesn't matter if its a source code or test code.
REST is based on HTTP, so it doesn't matter what framework is used to write a REST service. As long as it is a REST service, you should be able to call it