No endpoint mapping found for [SaajSoapMessage {http://com.springbootsoap.allapis}addProductRequest] - spring-boot

I have been having issues trying to get endpoint mapping to work for my web service. I am using Tomcat to host my web service and I am using soapUI to send test messages to it.
Endpoint
#Endpoint
public class ProductEndpoint {
private static final String NAMESPACE_URL="http://com.springbootsoap.allapis";
#Autowired
ProductService productService;
#PayloadRoot(namespace = NAMESPACE_URL, localPart = "addProductRequest")
#ResponsePayload
public AddProductResponse addProduct(#RequestPayload AddProductRequest request) {
AddProductResponse response= new AddProductResponse();
ServiceStatus servicestatus=new ServiceStatus();
Product product=new Product();
BeanUtils.copyProperties(request.getProductInfo(),product);
productService.addProduct(product);
servicestatus.setStatus("Success");
servicestatus.setMessage("Content Added Successfully");
response.setServiceStatus(servicestatus);
return response;
}
#PayloadRoot(namespace = NAMESPACE_URL, localPart = "getProductByIdRequest")
#ResponsePayload
public GetProductResponse GetProduct(#RequestPayload GetProductByIdRequest request) {
GetProductResponse response=new GetProductResponse();
ProductInfo productInfo=new ProductInfo();
BeanUtils.copyProperties(productService.getProductById(request.getProductId()),productInfo);
response.setProductInfo(productInfo);
return response;
}
}
SoapUI
enter image description here
here is what I got in soapUi.
I do not have any idea what should I do to make it correct, I saw many questions regarding this problem but did not find any solution.

I also had the same issue. At that time I change the version of java to 1.8 in pom.xml file

Related

Redirect to URL in Spring MVC (REST API) with params

I have an endpoint in RestController. When request would be processed , there must performed redirecting to another URL and There need to pass one parameters in redirect URL.
#RestController
#RequiredArgsConstructor
#Slf4j
public class RestControllerImpl {
#Value("${uri-root}")
private String uriRoot;
private final Service service;
#PostMapping("/api")
public RedirectView performRequest(#RequestBody Transaction dto) {
service.perform(dto);
String referenceToken = "sldflh#2lhf*shdjkla"
String urlRedirect = uriRoot + "?token=" + referenceToken;
return new RedirectView(urlRedirect);
}
}
The code above doesn't work for me.
I was looking for information on stackoverflow, but it suggests either using ModelAndView or RedirectAttributes attributes. But I need endpoint to accept a Post request that would bring data that will be processed in the service layer.
It is not possible to complete this task. Could someone explain how this can work and how such a task can be accomplished ?
It worked.
#RestController
#RequiredArgsConstructor
#Slf4j
public class RestControllerImpl {
#Value("${uri-root}")
private String uriRoot;
private final Service service;
#PostMapping("/api")
public ResponseEntity createClient(#RequestBody Transaction dto) throws URISyntaxException {
service.perform(dto);
String referenceToken = "sldflh#2lhf*shdjkla"
String urlRedirect = uriRoot + "?token=" + referenceToken;
return ResponseEntity.created(new URI(urlRedirect)).build();
}
}

Consume SOAP with Spring Boot and Feign client

I am struggling to properly make a SOAP request with open feign client and get the response. For testing purposes i took this public SOAP service http://www.learnwebservices.com/ and this is WSDL -> http://www.learnwebservices.com/services/hello?WSDL
I generated classes from this WSDL that looks like this:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "SayHello", propOrder = {
"helloRequest"
})
public class SayHello {
#XmlElement(name = "HelloRequest", required = true)
protected HelloRequest helloRequest;
//getters and setters
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "helloRequest", propOrder = {
"name"
})
public class HelloRequest {
#XmlElement(name = "Name", required = true)
protected String name;
//getters and setters
}
And i tried to follow this example:
How to send a SOAP object with FEIGN client?
basically i created this feign config:
private static final JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder()
.withMarshallerJAXBEncoding("UTF-8")
.withMarshallerSchemaLocation("http://www.learnwebservices.com/services/hello?WSDL")
.build();
#Bean
public Decoder feignDecoder() {
return new SOAPDecoder(jaxbContextFactory);
}
#Bean
public Encoder feignEncoder() {
return new SOAPEncoder(jaxbContextFactory);
}
And then here i try to invoke end point like this:
#FeignClient(name = "feign-example",
url = "http://www.learnwebservices.com/services/hello",
configuration = FeignConfig.class)
public interface WogSeb20FeignClient {
#PostMapping(value = "", consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.TEXT_XML_VALUE)
HelloResponse get(#RequestBody HelloRequest addRequest);
}
First when i tried to do the call i got error that says HelloRequest is missing XmlRootElement, so i added that annotation to the class (even i am not sure what to put as root element, i just added #XmlRootElement on top of the class. Afterwards when i create a request i get this error:
Error during parsing response data. Status: 500, Cause: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:Client</faultcode><faultstring>Message part helloRequest was not recognized. (Does it exist in service WSDL?)</faultstring></soap:Fault></soap:Body></soap:Envelope>
Obviously i am doing something wrong, can someone give me some guidance since i was not able to find too much material regarding this topic.

SpringBoot: LoadBalancer [server]: Error choosing server for key default

I'm creating a load balance feature on my project in which I have three server that will simultaneously ping for 15 seconds. However, when I already run my client-side, it always goes to the fallback page and received an error of "LoadBalancer [server]: Error choosing server for key default" even if the servers are already running.
Here are the codes in my project:
app.properties
server.port=8788
server.ribbon.eureka.enabled=false
server.ribbon.listOfServers=localhost:8787,localhost:8789,localhost:8790
#every 15 seconds
server.ribbon.ServerListRefreshInterval=15000
client service (wherein it is my fallback method)
private LoadBalancerClient loadBalancer;
private RestTemplate restTemplate;
public ClientService(RestTemplate rest) {
this.restTemplate = rest;
}
#HystrixCommand(fallbackMethod = "reliable")
public String login() {
ServiceInstance instance = loadBalancer.choose("server");
URI uri = URI.create(String.format("http://%s:%s/admin/ping", instance.getHost(), instance.getPort()));
//URI uri = URI.create("http://localhost:8787/admin/ping");
return this.restTemplate.getForObject(uri, String.class);
}
MainController
public class MainController{
private final static Logger LOGGER = LoggerFactory.getLogger(MainController.class);
#Autowired
private ClientService clientService;
#LoadBalanced
#Bean
public RestTemplate rest(RestTemplateBuilder builder) {
return builder.build();
}
#Autowired
RestTemplate restTemplate;
...
Client client = new Client();
WebResource resource = client.resource("http://%s:%s/auth/loginvalidate");
ClientResponse response = resource.type(MediaType.APPLICATION_JSON)
.header("Authorization", "Basic " + encodePw)
.get(ClientResponse.class);
I got rid of that error by doing two things:
1) Add the following properties to the remote service:
management.endpoints.web.exposure.include: "*"
management.endpoint.health.enabled: "true"
management.endpoint.restart.enabled: "true"
management.endpoint.info.enabled: "true"
2) Make sure that there is a ping endpoint in the remote service:
public class MainController{
#RequestMapping("/")
public String ribbonPing() {
return this.hostName;
}
}
I added a few amendments to the example provided by Kubernetes Circuit Breaker & Load Balancer Example to test this scenario and put in here.
I suggest that you follow those links as a kind of "best practises" guide in order to build your Hystrix/Ribbon solution. Pay special attention to:
the starters/dependencies added to the pom files
the structure of the Java classes (how and where each bean is declared and injected)
how you configure your (micro-)services (in this case with K8s ConfigMaps)

Testing a Post multipart/form-data request on REST Controller

I've written a typical spring boot application, now I want to add integration tests to that application.
I've got the following controller and test:
Controller:
#RestController
public class PictureController {
#RequestMapping(value = "/uploadpicture", method = RequestMethod.POST)
public ResponseEntity<VehicleRegistrationData> uploadPicturePost(#RequestPart("userId") String userId, #RequestPart("file") MultipartFile file) {
try {
return ResponseEntity.ok(sPicture.saveAndParsePicture(userId, file));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
}
Test:
#Test
public void authorizedGetRequest() throws Exception {
File data = ResourceUtils.getFile(testImageResource);
byte[] bytes = FileUtils.readFileToByteArray(data);
ObjectMapper objectMapper = new ObjectMapper();
MockMultipartFile file = new MockMultipartFile("file", "test.jpg", MediaType.IMAGE_JPEG_VALUE, bytes);
MockMultipartFile userId =
new MockMultipartFile("userId",
"userId",
MediaType.MULTIPART_FORM_DATA_VALUE,
objectMapper.writeValueAsString("123456").getBytes()
);
this.mockMvc.perform(multipart("/uploadPicture")
.file(userId)
.file(file)
.header(API_KEY_HEADER, API_KEY)).andExpect(status().isOk());
}
Testing the controller with the OkHttp3 client on android works seamlessly, but I can't figure out how to make that request work on the MockMvc
I expect 200 as a status code, but get 404 since, I guess, the format is not the correct one for that controller
What am I doing wrong?
It must be a typo.
In your controller, you claim the request URL to be /uploadpicture, but you visit /uploadPicture for unit test.

Springboot 405 Method Not Allowed in Pivotal Web Services/Cloud Foundry but working in local docker

I have created REST API application in SpringBoot which has GET and POST method pointing to the same URL. I have created springboot application and deployed in docker container in my local machine. When I try to access this application, I am able to get response for both GET and POST methods. I have deployed the same application into Pivotal Web Services (Pivotal Cloud Foundry). When I try to access GET method in PWS, it works fine but when I try to access POST method, I am getting error.
`"error": "Method Not Allowed",
"message": "Request method 'POST' not supported",`
If I look at the error in PWS log, I could see the following.
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
I have tried to change the springboot code to include different options in the method but none of them seem to work in PWS.
I would like to see 200 OK for POST method.
#RestController
#RequestMapping("/skus")
public class SKUController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
//==============================================================
#Autowired
SKUService skuService; //Service which will do all data retrieval/manipulation work
// -------------------Retrieve All SKUS---------------------------------------------
#RequestMapping(value = "/", method = RequestMethod.GET)
public ResponseEntity<List<SKU>> listAllSKUS() {
List<SKU> skus = skuService.listAllSKUS();
if (skus.isEmpty()) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
// You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<SKU>>(skus, HttpStatus.OK);
}
#RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity<?> addSKU(#RequestBody SKU sku) {
try {
skuService.addSKU(sku);
return new ResponseEntity<SKU>(sku, HttpStatus.OK);
}catch(Exception e) {
return new ResponseEntity("SKU cannot be created", HttpStatus.BAD_REQUEST);
}
}
}
````

Resources