Restful Response Showing \n Instead of New Line - spring

I am trying to generate a TEXT/PLAIN response for my Spring application.
When I am debugging the code, I see the string nicely formatted:
LINE1
LINE2
...
But when I see the response in Postman I see that the output is all messed up like
LINE1\nLIINE2\n....
I am not sure if the set up the controller properly or not!
Here is my Controller class:
import java.io.StringReader;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#Configuration
#EnableAutoConfiguration
public class ConfigGeneratorController {
private final AtomicLong counter = new AtomicLong();
Logger logger = null;
#RequestMapping(value = "/configGenerator", method = {RequestMethod.POST})
#Consumes({MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
#Produces({MediaType.TEXT_PLAIN_VALUE})
public ConfigGenerator configGenerator(#RequestBody String xml) {
logger = Logger.getLogger(ConfigGeneratorController.class.getName());
.
.
.
bunch of code
.
.
.
return new ConfigGenerator(counter.incrementAndGet(), String.format(actionMonitor.getGeneratedConfig().replaceAll("^\t+", "")));
}
}
actionMonitor.getGeneratedConfig() is the method that returns the string.

Related

Spring not picking up RestController endpoint

I have my spring project setup as shown below, but I am getting a 404 on the /custom endpoint. All answers I've found similar to this problem highlighted that the controller layer needs to be in a package below the project layer however I have it set out like this so I'm unsure why Spring isn't recognising the endpoint.
package com.myproject.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("custom")
public class CustomPathController {
#GetMapping
public ResponseEntity<Void> test() {
return new ResponseEntity<>(HttpStatus.OK);
}
}
package com.myproject;
import com.ryantenney.metrics.spring.config.annotation.EnableMetrics;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#EnableMetrics
#EnableJpaRepositories
#SpringBootApplication
public class MyProject {
public static void main(String[] args) {
SpringApplication.run(MyProject.class, args);
}
}
There must have been a port clash as a PC restart has fixed the issue

how to request data from our spring boot micro-service to external server for a given id's?

Currently I have created 2 microservices and and getting the data from one service to another using RestTemplate.
Microservice -1:
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
#RestController
public class StringDataController {
List<String> stringList = new ArrayList<>();
#RequestMapping(value = "/securities/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<String> sendStringData(){
stringList.add("12345");
stringList.add("23435");
stringList.add("23436");
return stringList;
}
}
Microservice-2:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
#RestController
#EnableAutoConfiguration
public class ExternalRequestController {
#Value ("${sampleMS1.uri}")
String sampleMS1URI;
#RequestMapping(value="/listdata", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public void receiveStringFromAnotherMS(){
List<String> list = null;
list = new RestTemplate().getForObject(sampleMS1URI,List.class);
System.out.println(list.toString());
System.out.println("-->"+list);
}
}
Now, I have to send the List(String)(list of ID's) data to some external server and response should get Map(K,V) ==> key as a String and Value as a Double.
Note: The external server is not handling by us, so we can only request the data with List of id's and then they should sending the response with price data of specific id's.
Can anyone suggest me a way to do it ?
I am new to Spring & Spring boot.
Thank you!

Error while instantiating selenium chrome driver in Spring MVC Java Controller

When I'm running the selenium chrome driver instantiation code in separate java file i'm not getting any error but when trying to run it in controller method of spring mvc then I'm getting following error:
Warning: StandardWrapperValve[dispatcher]: Servlet.service() for servlet dispatcher threw exception
java.lang.NoSuchMethodError:com.google.common.base.Preconditions.checkState(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
at org.openqa.selenium.remote.service.DriverService.findExecutable
(DriverService.java:124)
at org.openqa.selenium.chrome.ChromeDriverService.access$000
(ChromeDriverService.java:32)
at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable
(ChromeDriverService.java:137)
...etc
My spring mvc controller code is as follows:
package com.webcrawler;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import static javax.servlet.SessionTrackingMode.URL;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.Alert;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.interactions.Actions;
public class WebCrawlerController {
#RequestMapping("/index.htm")
public ModelAndView login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String errorMsg = "";
System.setProperty("webdriver.chrome.driver","C:\\Users\\<username>\\Desktop\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://netforum.acg.org/eweb/DynamicPage.aspx?WebCode=LoginRequired&expires=yes&Site=ACG");
System.out.println("inside webcrawlerController");
return new ModelAndView("index");
}
Am I missing anything ? I'm getting error on the line:
WebDriver driver=new ChromeDriver();
I fixed it just deleting a guava library from the pom file

Spring Boot Integration Tests, #Autowired works, #Inject does not, Why?

I work on a Spring Boot application, I have written a Service and I want to test this Service in an Integration Test. Therefor I want to Inject the Service Into my test. If I use the #Inject annotation, The Service is null. If I use #Autowired, the Service gets Injected and the test works. I thought the annotation should do more or less the same, with the only differrence that #Autowired fails if no bean is available, because it is default set to required=true.The Service has an Interface and I choose the implementation based on Field Name.
Interface:
import org.springframework.core.io.ByteArrayResource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
public interface FileService {
boolean storeDicomZip(InputStream stream, long caseId);
.
.
.
}
Implementation:
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import java.io.*;
import java.nio.file.Files;
import java.util.Optional;
#Service
public class FileSystemFileService implements FileService {
.
.
.
}
And The Test:
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#WebAppConfiguration
#IntegrationTest
public class FileSystemFileServiceTest {
#Autowired
private FileService fileSystemFileService;
#Test
public void storeDicomZip() throws Exception {
InputStream stream = new ByteArrayInputStream("TEST".getBytes());
fileSystemFileService.storeDicomZip(stream, 3);
Assert.assertTrue(fileSystemFileService.getDicomZipVersions(3) == 1);
}
.
.
.
}
As described, If I use #Autowired, like here it works, if I use #Inject it does not because fileSystemFileService is null.
Does somebody know why this is the case, and what I have to change to use #Inject?

Post url seems not been called with spring security

My issue is that, when I call the url http://localhost:8080/site/data/gouv/ with postman with corresponding form data parameters, nothing happens. It seems even the call is not catched by the controller because there is no log.
Postman page
Here is the controller :
package com.mintad.spring.controllers;
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.site.common.beans.Gouv;
import com.site.common.service.GouvService;
import au.com.bytecode.opencsv.CSVReader;
#RestController
#RequestMapping("/data")
public class DataController {
#Autowired
private GouvService gouvService;
#RequestMapping(value = "/gouvernorate", method = RequestMethod.POST)
public ResponseEntity<Gouv> addGouvernorate(#RequestBody Gouv gouv) throws IOException {
gouvService.addGouv(gouv);
return new ResponseEntity<Gouv>(gouv, HttpStatus.OK);
}
}
I've tried to call the url with Jsoup as follows :
String base64login = new String(Base64.encode("sof:1".getBytes()));
Document docs = Jsoup.connect("http://localhost:8080/site/data/gouv/").header("Authorization", "Basic " + base64login).
data("name", "name").
data("delegation", "delegation").
data("district", "district").
data("postalCode", "postalCode").post();
But in vain.
Any help please ? I'm using spring security 4.0.4.RELEASE and Spring 4.2.5.RELEASE

Resources