Unable to consume JSON array using Spring RestTemplate - java

Am trying to populate a DTO from a published RESTful URL (simple HTTP GET) by using Spring's RestTemplate HTTP Client.
This is the content of the published JSON that I am trying to consume:
[{"startDate":"2017-01-29","cost":"$50000.00","id":1112,"name":"Porsche"},{"startDate":"2017-03-06","cost":"$27000.00","id":38626,"name":"BMW"}]
My DTO:
class DTO {
private String startDate;
private String cost;
private String name;
// Getters and Setters
}
My Response Object:
public class Response {
private static final STRING = "http://www.sample.com/product";
public static List<Object> getCampaigns() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object[]> responseEntity = (ResponseEntity) restTemplate.getForEntity(URL, Object[].class);
Object[] objects = responseEntity.getBody();
MediaType contentType = responseEntity.getHeaders().getContentType();
HttpStatus statusCode = responseEntity.getStatusCode();
return Arrays.asList(objects);
}
public void static main (String args []) {
List<Object> dtos = getCampaigns();
for (Object dto : dtos) {
System.out.println(dto.toString());
}
}
}
Here's my pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
</dependency>
</dependencies>
When I run the main() method inside Response, I get the following exception:
00:24:14.191 [main] DEBUG org.springframework.web.client.RestTemplate - GET request for "http://www.sample.com/product" resulted in 200 (OK)
Exception in thread "main" org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class [Ljava.lang.Object;] and content type [application/json;charset=utf-8]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:109)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:917)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:901)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:655)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:312)
What am I possibly doing wrong?

Try this
public class Response {
private static final String URL = "http://www.sample.com/product";
public static List<DTO> getCampaigns() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<DTO[]> responseEntity = restTemplate.getForEntity(URL, DTO[].class);
DTO[] objects = responseEntity.getBody();
MediaType contentType = responseEntity.getHeaders().getContentType();
HttpStatus statusCode = responseEntity.getStatusCode();
return Arrays.asList(objects);
}
public void static main (String args []) {
List<DTO> dtos = getCampaigns();
for (DTO dto : dtos) {
System.out.println(dto.toString());
}
}
}

use this jackson library instead
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>

Related

Jbehave Test configuration and test reporting not working as expected

I am using Jbehave to test some API's. I configured my stories but when i run the configuartion file, i get the following output:
Reports view generated with 0 stories (of which 0 pending) containing 0 scenarios (of which 0 pending)
I assumed that my configuration worked fine, and tried to run my whole test package, but it returned an output saying
No tests found in the package "com.example.prederiq.PrederaAiq"
However, when i ran my PrederaAiqApplicationTests.java file containing the test cases, all the tests passed but no console report or html report was returned to me. I have attached all the concerned files in my test package below and also the project structure below, please help me sort this out
Project Structure:
My Configuration file:
public class StoryConfiguration extends JUnitStories {
#Override
public Configuration configuration() {
return new MostUsefulConfiguration().useStoryLoader(new LoadFromClasspath(this.getClass())).useStoryReporterBuilder(new StoryReporterBuilder().withCodeLocation(CodeLocations.codeLocationFromClass(this.getClass())).withDefaultFormats().withFormats(StoryReporterBuilder.Format.CONSOLE, StoryReporterBuilder.Format.HTML));
}
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(),new PrederaAiqApplicationTests());
}
#Override
public List<String> storyPaths() {
String codeLoc = codeLocationFromClass(this.getClass()).getFile();
return new StoryFinder().findPaths(codeLoc, asList("**/test*.story"),asList(""),"file"+codeLoc);
}
}
test.story file:
Given: An authorised URL
When: A GET req is made
Then: 200 status code is returned
Given:Unauthorised link
When:GET req is made
Then: 401 status code is returned
Given: An authorised URL.
When: A GET req is made to it
Then: application type is json
Given: An authorised URL.
When: A GET req is made to it
Then: output same as that in documentation
PrederaAiqApplicationsTest file:
class PrederaAiqApplicationTests {
String contentType;
String uri = "https://sandbox.predera.com/aiq/api/projects";
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort().dynamicHttpsPort());
CloseableHttpClient httpClient = HttpClients.createDefault();
String auth = "Bearer " + "eyJraWQiOiJndE1YKzh2bVBaNnk0NElmdllGNDZqVDlvRG5RZWxoeUg4d1JjMVwvWkdBND0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhMGNhZjMyYy0zY2Q0LTQyNzAtYmQ4NC1kOWI4N2Q1NGIyZjAiLCJjdXN0b206dGllciI6IlN0YW5kYXJkIFRpZXIiLCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtd2VzdC0yLmFtYXpvbmF3cy5jb21cL3VzLXdlc3QtMl8zTVkyM3BMM0YiLCJjb2duaXRvOnVzZXJuYW1lIjoicHBhbGxhdmFsbGlAdW1hc3MuZWR1IiwiY3VzdG9tOnRlbmFudF9pZCI6IlRFTkFOVDU4ZWFjMTM4YzIyMjQ5ZjA5MTA1MDA1Mzk2MGNmMzZhIiwiZ2l2ZW5fbmFtZSI6IlByYW5hdiIsImF1ZCI6IjZibjZrNTk0cmxubXRyamZpYXMxdjQwMGhmIiwiZXZlbnRfaWQiOiJkNDQ2ZTdlNy02MjM5LTRiYWMtYWE0Zi00Y2JjNWQzNDk0YWUiLCJ0b2tlbl91c2UiOiJpZCIsImF1dGhfdGltZSI6MTYyMzg2NTQzOSwiZXhwIjoxNjIzODY5MDM5LCJjdXN0b206cm9sZSI6IlRlbmFudFVzZXIiLCJpYXQiOjE2MjM4NjU0MzksImZhbWlseV9uYW1lIjoiUGFsbGF2YWxsaSIsImVtYWlsIjoicHBhbGxhdmFsbGlAdW1hc3MuZWR1In0.pcp4KY0HzcAtWIgFfoX5sRwJccQ4GizlbBqoh5GuaoRMkvPrzBtLRf1AwC2tsL8cFDni6whxhClSgW_w1cDQZUUUHQ82svDxiSBLLft1ZAg9VVOlJ1AkKbaZDcoA-4wVAZBdzmmuCiwhNerP9Ask2DiP0slAADwzNMfhlhvlqcqdWbZyEreHMuUkVkGVdSUDK933TRKkKP-x62PTsize6oi-mApmeZY3Qr5AcGHHW3frZE-XuYlLaJzDZH5yJv7qA7pkQ5c05LPlZdWrwTelEdx8GLRKRs-fFnwIquOLkWceqSyYuz3gFalXOG3xfZtVIozNfVfocZzXN54ul7_B-g";
int status = 0;
JSONArray array;
HttpUriRequest httpUriRequest;
#Test
#Given("An authorised URL")
void test(){
httpUriRequest = RequestBuilder.get().setUri(uri).setHeader(HttpHeaders.AUTHORIZATION,auth).build();
}
#When("A GET req is made")
void testGet() throws IOException {
HttpResponse response =httpClient.execute(httpUriRequest);
status = response.getStatusLine().getStatusCode();
}
#Then("200 status code is returned")
void test200() {
assertEquals(200,status);
}
#Test
#Given("Unauthorised link")
void test2() {
httpUriRequest = RequestBuilder.get().setUri(uri).build();
}
#When("GET req is made")
void get2() throws IOException {
HttpResponse response = httpClient.execute(httpUriRequest);
status = response.getStatusLine().getStatusCode();
}
#Then("401 status code is returned")
void statusTest2(){
assertEquals(401,status);
}
#Test
#Given("An authorised URL.")
void test3(){
httpUriRequest = RequestBuilder.get().setUri(uri).setHeader(HttpHeaders.AUTHORIZATION,auth).build();
}
#When("A GET req is made to it")
void getTest3() throws IOException {
HttpResponse response = httpClient.execute(httpUriRequest);
contentType = String.valueOf(response.getEntity().getContentType());
}
#Then("application type is json")
void content(){
assertEquals("application/json",contentType);
}
#Test
#Given("An authorised URL.")
void test4(){
httpUriRequest = RequestBuilder.get().setUri(uri).setHeader(HttpHeaders.AUTHORIZATION,auth).build();
}
#When("A GET req is made to it")
void testGet4() throws IOException, ParseException {
HttpResponse response = httpClient.execute(httpUriRequest);
HttpEntity entity = response.getEntity();
Scanner scanner = new Scanner(entity.getContent());
String content = "";
while(scanner.hasNext()){
content += scanner.nextLine();
}
scanner.close();
JSONParser parser = new JSONParser();
array = (JSONArray) parser.parse(content);
}
#Then("output same as that in documentation")
void content2(){
assertEquals("[{\"owner\":\"ppallavalli#umass.edu\",\"name\":\"churn-juyma\",\"description\":\"Customer Churn Example\",\"last_modified_date\":\"2021-06-09T17:38:06.048Z\",\"id\":\"a-443018111\",\"created_date\":\"2021-06-09T17:38:06.048Z\",\"last_modified_by\":\"ppallavalli#umass.edu\",\"created_by\":\"ppallavalli#umass.edu\",\"users\":[\"ppallavalli#umass.edu\"]}]",array.toString());
}
}
Pom.xml:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.prederiq</groupId>
<artifactId>PrederaAiq</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>PrederaAiq</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-core</artifactId>
<version>4.8.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.28.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<argLine>
--illegal-access=permit
</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>

Jersey 2.x post call MessageBodyWriter not found for media type=application/xml

I am using Jersey version 2.29 /java 1.8 on tomcat version 8.5 and trying to retrurn the hasmap<String,String> from jersey rest post service call.
I am getting below exception on server when it is trying to write the hasmap in response.
Aug 23, 2019 10:20:47 PM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
SEVERE: MessageBodyWriter not found for media type=application/xml, type=class java.util.LinkedHashMap, genericType=java.util.Map.
Below are the details of pom.xml,server and jersey client side code.
pom.xml
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.1</version> </dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>${jersey.version}</version>
</dependency>
Client Code
ClientConfig configuration=new ClientConfig();
Client restClientConfig = ClientBuilder.newClient(configuration);
WebTarget webTarget=restClientConfig.target("http://localhost:8080/messenger/webapi/messages/testMap");
HashMap<String,String> mapStr=new HashMap<String,String>();
mapStr.put("a","1");
mapStr.put("b","2");
webTarget.request()
.accept(MediaType.APPLICATION_XML)
.post(Entity.json(mapStr));
Map<String,String> responseMap = new HashMap<String,String>();
GenericType<Map<String,String>> entity = new GenericType<Map<String,String>>() {};
Response xmlResponse = Response.ok(entity).build();
System.out.println("XMLResponse Is :" + xmlResponse + ":"+ responseMap.size());
Jersey Post Service code
#POST
#Path("/testMap")
#Produces(value = { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
#Consumes(value = { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Map<String,String> postMapMessage(Map<String,String> mapMessage) {
System.out.println("It is been invoked....and this time we will add the new MapMessage");
if(mapMessage!=null)
{
System.out.println("Size of the Map Message:" + mapMessage.size());
mapMessage.put("c","3");
}
return mapMessage;
}
I have tried several solutions found on internet but nothing seems to be working for this.
Can anybody please tell me what wrong I am doing in above code snippet?
I am able to partially fix the issue by creating the below wrapper class.
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class JaxrsMapWrapper<T,K> {
private Map<T,K> map;
public JaxrsMapWrapper(){
}
#Override
public String toString() {
return map .toString();
}
public void setMap(Map<T,K> map) {
this.map = map;
}
public Map<T,K> getMap() {
return map;
}
}
By using the above class below getservice returning the typeof Map is working absolutly fine.
#GET
#Path("/mapWarpperReceive")
#Produces({MediaType.APPLICATION_XML})
public JaxrsMapWrapper<String,String> getWarpperMapMsgStr()
{
System.out.println("Returning the MapMessage as String ");
Map<String,String> originalMap=new HashMap<String,String>(){{put("a","a");put("b","b");}};
JaxrsMapWrapper<String,String> jaxRsMapWrapper=new JaxrsMapWrapper<>();
jaxRsMapWrapper.setMap(originalMap);
return jaxRsMapWrapper;
}
But when I am trying to use the same class JaxrsMapWrapper with type of Map it is throwing Error 500 Internal server error while invoking through postman.
#GET
#Path("/customMap")
#Produces({MediaType.APPLICATION_XML})
public JaxrsMapWrapper<String,BookBo> getWarpperMapMsgWithCustomObject()
{
System.out.println("Returning the MapMessage as String and Custom Message ");
Map<String,BookBo> originalMap=new HashMap<>();
originalMap.put("a",new BookBo(1,"Jinesh"));
JaxrsMapWrapper<String,BookBo> jaxRsMapWrapper=new JaxrsMapWrapper();
jaxRsMapWrapper.setMap(originalMap);
return jaxRsMapWrapper;
}
Below is the code for the User defined Java Object BookBo.
#XmlRootElement
public class BookBo implements Serializable{
private Integer id;
private String name;
public BookBo() {
}
public BookBo(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
//getters and setters of the field
}
What am I missing in the above code due to which while writing the Map in response is not working?

RestTemplate response type issue for comsuming web service

I have written following REST web service.
Now i want to consume this web service using RestTemplate.But I am not sure what should be return type for restTemplate.exchange(?).can you please help what should be return type?
#RequestMapping(value = "/customercontact/transid/{brokerid}", method = RequestMethod.GET)
public ResponseEntity<HashMap<String, String>> getTransactionIdWithPublicKey(#PathVariable("brokerid") String brokerid){
HashMap<String, String> transactionid = customerService.getTransactionid(brokerid);
if(transactionid != null)
return new ResponseEntity<HashMap<String, String>>(transactionid,HttpStatus.OK);
else
return new ResponseEntity<HashMap<String, String>>(HttpStatus.NOT_FOUND);
}
public void doGet( HttpServletRequest request,
HttpServletResponse response ) throws IOException
{
RestTemplate restTemplate = new RestTemplate();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("SM_USER", "wbrokere");
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);
ResponseEntity<String> responseobj = restTemplate.exchange("http://127.0.0.1:24000/webbroker/getusername", HttpMethod.GET, httpEntity,?);
}
the same type used in your Rest Service HashMap.class
ResponseEntity<HashMap> responseobj = `restTemplate.exchange("http://127.0.0.1:24000/webbroker/getusername", HttpMethod.GET, httpEntity,HashMap.class);`
responseobj.getBody(); //To get the body of the response entity
Add Jakson dependencies in The POM.xml
<!-- Jackson for Rest Controller -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.8.8</version>
</dependency>

JAX RS, test ETags with JAX RS Client API, Jersey, Glassfish

I always get java.text.ParseException: End of header. exception.
#GET
public Response getTemplate4CustomSkin(#Context final Request request)
{
EntityTag eTag = new EntityTag("123456789");
Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(eTag);
if (responseBuilder == null)
{
System.out.printf("is null");
}
else
{
System.out.printf("is not null");
}
return Response.ok(data.inputStream, data.mimeType).tag(eTag).build();
}
}
#Test
public void testGetFileEtagIsNotChanged() throws UnsupportedEncodingException
{
Client client = ClientBuilder.newClient();
WebTarget target = client.target("someUrl");
EntityTag eTag = new EntityTag("123456789");
Response response = target.request().get();
//send request 2nd time with
response = target.request().header("If-None-Match", response.getEntityTag()).get();
//same result
//response = target.request().header("If-None-Match", response.getEntityTag().getValue()).get();
Assert.assertEquals(eTag, response.getEntityTag());
}
// the following code always throws an exception inside of org.glassfish.jersey.message.internal.HttpHeaderReaderImpl.java class:
private char getNextCharacter(boolean skipWhiteSpace) throws ParseException {
....
// this line of code always throws it:
if(this.index >= this.length) {
throw new ParseException(LocalizationMessages.HTTP_HEADER_END_OF_HEADER(), this.index);
} else {
return this.header.charAt(this.index);
}
}
I run tests via arquillian, dependency versions:
<!--Arquillian JUnit integration: -->
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<version>1.1.8.Final</version>
<scope>test</scope>
</dependency>
<!--glassfish-embedded:-->
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>4.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-embedded-3.1</artifactId>
<version>1.0.0.CR4</version>
<scope>test</scope>
</dependency>
How can I resolve it? How can I send a request with "If-None-Match" header inlcuded and don't get an exception?
EDIT:
In order to avoid the error, I had to use wildfly embedded application server instead of glassfish.

Can't get json from Swagger + Jersey

I have RESTful service based on Jersey 1.18.1 and I want to show my API via Swagger.
Firstly I have to get JSON. I read this instruction: Swagger Core Jersey 1.X Project Setup 1.5. Swagger allows to set up a configuration different methods and I decided to use custom Application subclass. I did everything step by step but I can't get JSON which I have to use for swagger-ui.
What I did:
My custom Application
#ApplicationPath("api/v1")
public class DiscountsApp extends Application{
public DiscountsApp() {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.2");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setHost("localhost:8002");
beanConfig.setBasePath("swaggerapi");
beanConfig.setResourcePackage("alexiuscrow.diploma.endpoints");
beanConfig.setScan(true);
}
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new HashSet();
resources.add(ShopsResources.class);
//...
resources.add(com.wordnik.swagger.jaxrs.listing.ApiListingResource.class);
resources.add(com.wordnik.swagger.jaxrs.listing.SwaggerSerializers.class);
return resources;
}
}
ShopsResources
#Path("/shops")
#Api(value="/shops", description="Shops")
public class ShopsResources {
#GET
#Produces(MediaType.APPLICATION_JSON)
#ApiOperation(value = "List shops", httpMethod = "GET",
notes = "List nearest or locality shops",
response = Shops.class, responseContainer = "List")
public String getShops(
#ApiParam( value = "Radius", required = false)
#QueryParam("radius") String radiusParam,
#ApiParam( value = "Latitude", required = true)
#QueryParam("lat") String latParam,
#ApiParam( value = "Longitude", required = true)
#QueryParam("lng") String lngParam) throws SQLException{
//The list of Shops objects is serialized to string
//using the custom GSON serializer and I know
//that there is the better method of the solution of this task.
}
}
}
Some dependencies from pom.xml
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-jersey-jaxrs</artifactId>
<version>1.5.1-M2</version>
</dependency>
After deploy application to Tomcat I tried to get http://localhost:8002/swaggerapi but I've got no result.
I didn't find the swagger.json in root of my application (/tomcat8/webapps/app).
What's wrong?
How can I get JSON with my API?
I did not correctly build the url.
Correct:
http://{host}:{port}/{context root of application}/{path from #ApplicationPath}/swagger.json
In my case: http://localhost:8080/app/api/v1/swagger.json
Thx to Ron.
adding a relative path worked for me (this is using .netcore 1.1)
app.UseSwaggerUI(s => {
s.RoutePrefix = "help";
s.SwaggerEndpoint("../swagger/v1/swagger.json", "MySite");
s.InjectStylesheet("../css/swagger.min.css");
});

Categories

Resources