I have configured swagger-ui in my SpringBoot application.
Following is my code
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
openAppUrl("8080/swagger-ui.html");
}
public static void openAppUrl(String port) {
String url = "http://localhost:" + port;
String os = System.getProperty("os.name").toLowerCase();
Runtime rt = Runtime.getRuntime();
try {
if (os.indexOf("win") >= 0) {
rt.exec("rundll32 url.dll,FileProtocolHandler " + url);
} else if (os.indexOf("mac") >= 0) {
try {
rt.exec("open " + url);
} catch (IOException e) {
System.out.println(e);
}
} else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) {
String[] browsers = { "epiphany", "firefox", "mozilla", "konqueror", "netscape", "opera", "links",
"lynx" };
StringBuffer cmd = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
cmd.append((i == 0 ? "" : " || ") + browsers[i] + " \"" + url + "\" ");
rt.exec(new String[] { "sh", "-c", cmd.toString() });
} else {
return;
}
} catch (Exception e) {
return;
}
return;
}
}
My Controller
package com. server.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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;
import com. server.spring.domain.User;
import com. server.spring.service.UserService;
#RestController
#RequestMapping(UsersController.ROOT_RESOURCE_PATH)
public class UsersController {
public static final String ROOT_RESOURCE_PATH = "/rest/secure/v1/users";
#Autowired
private UserService userService;
#RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<User> getUsers() {
return userService.getAllUsers();
}
#RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public User createUser(#RequestBody User user) {
return userService.saveUser(user);
}
}
Here it shows the Rest API URL, HTTP Method POST, Response JSON Object. But I don't see the POST Data Obj which is expected in the API call. So without this the Front End developers cann't work on the corresponding API.
So i expect to show POST Data JSON object what this REST Api required from Front end application
Is this the correct way or Do i need to modify it to get the expected one?
You are using an old version of Swagger-ui, that looks like 2.x
The latest is a lot easier to understand, Check it out here:
http://petstore.swagger.io/#/pet/addPet
It sounds like you are giving this to other developers (the Front End developers), In that case I strongly suggest you to look for a way to upgrade, the new version has a much better user experience, also the 2.x UI version is no longer supported.
So to answer your question:
How can I get POST data in swagger-ui?
The actual response you can get it with the [try-it-out] button of the swagger-ui.
And the POST Data Obj expected by the API is what you see on the example.
I got model properties to correctly attach to the body by using examples (Techincally, API Model Properties) on the models. However, my experience with this didn't include Spring, I'm sure that the documentation is similar. You'd add #ApiModelProperty annotation to your User class.
public class User {
private String firstName;
private String lastName;
#ApiModelProperty(value = "User's first name.", example = "John")
public String getFirstName(){}
//...setters
#ApiModelProperty(value = "User's last name.", example = "Smith")
public String getLastName(){}
//...setters
// etc
}
This fills the swagger documentation POST/PUT/etc body with your example strings.
Related
I dont seem to know why Spring is returning me an empty list enough I have passed in a JSON.stringify() string from reactJS
This is my code for reactJS
postData(item){
console.log(item)
fetch("http://localhost:8080/addSuspect", {
"method": "POST",
"headers": {
"content-type": "application/json"
},
"body": item
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
}
uploadFile(event) {
let file
let file2
//Check if the movements andsuspected case profiles are uploaded
if(event.target.files.length !== 2){
this.setState({error:true, errorMsg:"You need to upload at least 2 files!"})
return
}
//Check if the file is the correct file
console.log("Files:")
for (var i=0, l=event.target.files.length; i<l; i++) {
console.log(event.target.files[i].name);
if (event.target.files[i].name.includes("_suspected")){
file = event.target.files[i]
}
else if (event.target.files[i].name.includes("_movements")){
file2 = event.target.files[i]
}
else{
this.setState({error:true, errorMsg:"You have uploaded invalid files! Please rename the files to <filename>_suspected (For suspected cases) or <filename>_movement (For suspected case movement)"})
return
}
}
//Reads the first file (Suspected profile)
if (file) {
const reader = new FileReader();
reader.onload = () => {
// Use reader.result
const lols = Papa.parse(reader.result, {header: true, skipEmptyLines: true}, )
console.log(lols.data)
// Posting csv data into db
// this.postData('"' + JSON.stringify(lols.data) + '"')
this.postData(JSON.stringify(lols.data))
// Adds names into dropdown
this.setState({dataList: ["None", ...lols.data.map(names => names.firstName + " " + names.lastName)]})
const data = lols.data
this.setState({suspectCases: data})
}
reader.readAsText(file)
}
}
Here is what I get from console.log():
[{"id":"5","firstName":"Bernadene","lastName":"Earey","email":"bearey4#huffingtonpost.com","gender":"Female","homeLongtitude":"","homeLatitude":"","homeShortaddress":"","homePostalcode":"552209","maritalStatus":"M","phoneNumber":"92568768","company":"Yadel","companyLongtitude":"","companyLatitude":""},{"id":"14","firstName":"Mada","lastName":"Lafaye","email":"mlafayed#gravatar.com","gender":"Female","homeLongtitude":"","homeLatitude":"","homeShortaddress":"","homePostalcode":"447136","maritalStatus":"M","phoneNumber":"85769345","company":"Eare","companyLongtitude":"","companyLatitude":""}]
Below shows the Code in my Spring Controller
#RestController
public class HomeController {
private final profileMapper profileMapper;
private final suspectedMapper suspectedMapper;
public HomeController(#Autowired profileMapper profileMapper, #Autowired suspectedMapper suspectedMapper) {
this.profileMapper = profileMapper;
this.suspectedMapper = suspectedMapper;
}
#GetMapping("/listAllPeopleProfiles")
//Removes the CORS error
#CrossOrigin(origins = "http://localhost:3000")
private Iterable<Peopleprofile> getAllPeopleProfiles (){
return profileMapper.findAllPeopleProfile();
}
#GetMapping("/listAllSuspectedCases")
#CrossOrigin(origins = "http://localhost:3000")
private Iterable<Suspected> getAllSuspected(){
return suspectedMapper.findallSuspected();
}
#PostMapping("/addSuspect")
#CrossOrigin(origins = "http://localhost:3000")
private void newSuspectedcases(ArrayList<Suspected> unformattedcases){
// try {
// final JSONObject obj = new JSONObject(unformattedcases);
//
// System.out.println(obj);
//// ObjectMapper mapper = new ObjectMapper();
//// List<Suspected> value = mapper.writeValue(obj, Suspected.class);
// } catch (JSONException e) {
// e.printStackTrace();
// }
//
// Gson gson = new Gson();
// List<Suspected> suspectedCases = gson.fromJson(unformattedcases, new TypeToken<List<Suspected>>(){}.getType());
System.out.println(unformattedcases);
// for (Suspected suspected : suspectedCases){
// suspectedMapper.addSuspectedCase(suspected);
// }
}
}
I am not sure I understand your issue. This is my best guess about what you meant and what you want to happen :
You want your controller to receive ArrayList < Suspected > as the POST request body
You want your controller to return ArrayList < Suspected > as the POST response body
If that's the case, try this :
[...]
#PostMapping("/addSuspect")
#CrossOrigin(origins = "http://localhost:3000")
#ResponseBody
private ArrayList<Suspected> newSuspectedcases(#RequestBody ArrayList<Suspected> unformattedcases){
[...]
System.out.println(unformattedcases);
[...]
return unformattedcases;
}
If it's not what you meant, please provide more information.
Firstly, your controller method is returning void and not, if I undestand correctly, the payload that you're trying to send. You have to make your controller method return List<Suspected> to receive a body in the response.
Another issue is that you're missing a #RequestBody annotation on the param, which tells Spring to get the body from the request and try to deserialize it to a ArrayList of Suspects.
Another thing to note, it is a good practice to use interfaces instead of implementation classes as parameters and return value in your methods. Consider using List<Suspected> instead of ArrayList<Suspected>
So the final method should look like this:
#PostMapping("/addSuspect")
#CrossOrigin(origins = "http://localhost:3000")
private List<Suspected> newSuspectedcases(#RequestBody List<Suspected> unformattedcases){
[...]
System.out.println(unformattedcases);
[...]
return unformattedcases;
}
PS For CORS issues you may want to using a local proxy setup as described in React docs: https://create-react-app.dev/docs/proxying-api-requests-in-development/ And configure CORS for remote environments, without adding localhost:3000.
looking for a sample java code to read parameter store values like RDS connection string from aws parameter store. appreicate code or any reference links. thanks.
Here is the V2 (not V1) example to read a specific parameter value from the AWS parameter store:
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.GetParameterRequest;
import software.amazon.awssdk.services.ssm.model.GetParameterResponse;
import software.amazon.awssdk.services.ssm.model.SsmException;
public class GetParameter {
public static void main(String[] args) {
final String USAGE = "\n" +
"Usage:\n" +
" GetParameter <paraName>\n\n" +
"Where:\n" +
" paraName - the name of the parameter\n";
if (args.length < 1) {
System.out.println(USAGE);
System.exit(1);
}
// Get args
String paraName = args[0];
Region region = Region.US_EAST_1;
SsmClient ssmClient = SsmClient.builder()
.region(region)
.build();
try {
GetParameterRequest parameterRequest = GetParameterRequest.builder()
.name(paraName)
.build();
GetParameterResponse parameterResponse = ssmClient.getParameter(parameterRequest);
System.out.println("The parameter value is "+parameterResponse.parameter().value());
} catch (SsmException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement;
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagementClientBuilder;
import com.amazonaws.services.simplesystemsmanagement.model.GetParametersRequest;
import com.amazonaws.services.simplesystemsmanagement.model.GetParametersResult;
...
private static AWSSimpleSystemsManagement ssmclient = AWSSimpleSystemsManagementClientBuilder
.standard().withRegion(System.getProperty("SystemsManagerRegion")).build();
...
GetParametersRequest paramRequest = new GetParametersRequest()
.withNames(parameterName).withWithDecryption(encrypted);
GetParametersResult paramResult = new GetParametersResult();
paramResult = ssmclient.getParameters(paramRequest);
I think GitHub may be of help. I searched for SsmClient getParameter language:java and some of the results seem promising.
This one for example:
public static String getDiscordToken(SsmClient ssmClient) {
GetParameterRequest request = GetParameterRequest.builder().
name("/discord/token").
withDecryption(Boolean.TRUE).
build();
GetParameterResponse response = ssmClient.getParameter(request);
return response.parameter().value();
}
I'm trying to use nvd3d candlestick chart with Angular, but I'm not getting to render it when using a rest service built in Java.
How to consume a java rest to render nv3d candlestick chart with Angular?
My rest is returning this:
[{"id":450,"vwap":3821.62,"faixa":69.48,"open":3858.7,"high":3863.29,"low":3793.81,"close":3795.54,"date":19338}]
The component expected this:
[{values:[{"id":450,"vwap":3821.62,"faixa":69.48,"open":3858.7,"high":3863.29,"low":3793.81,"close":3795.54,"date":19338}]}]
My Angular code:
import { Injectable } from '#angular/core';
import { Provider, SkipSelf, Optional, InjectionToken } from '#angular/core';
import { Response, Http } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { HttpInterceptorService, RESTService } from '#covalent/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
export interface IDolFutDiario {
id: number;
date: number;
open: number;
high: number;
low: number;
close: number;
vwap: number;
faixa: number;
}
#Injectable()
export class DolfudiarioService extends RESTService<IDolFutDiario>{
constructor(private _http: HttpInterceptorService) {
super(_http, {
baseUrl: 'http://localhost:8080',
path: '',
});
}
staticQuery(): Observable<IDolFutDiario[]> {
return this.http.get('http://localhost:8080/dolfutdiarios')
.map(this.extractData)
.catch(this.handleErrorObservable);
}
extractData(res: Response) {
let body = res.json();
return body;
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
}
My Java code:
#RestController
public class DolFutRestController {
#Autowired
DolFutDiarioService dolFutDiarioService;
#RequestMapping(value = "dolfutdiarios", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<DolFutDiario>> list() {
List<DolFutDiario> dolfutdiarios = dolFutDiarioService.listDolFutDiarios();
return ResponseEntity.ok().body(dolfutdiarios);
}
}
PS: When I put the second block of data [[values: ..... , it works.
However when I get from Java Service it does not.
No errors returned as well.
Well, you need to convert the block of data you get to the one you want. It's not going to work if you use the wrong format. The crux of the matter is in this method:
extractData(res: Response) {
let body = res.json();
return body;
}
There you can map your data to what you need; for example, if you want to wrap it in a values object, do it like so:
extractData(res: Response) {
const body = res.json();
return [{ values: body }];
}
Also, try console.log'ing your code in different steps to see what you have and compare to what you need!
My days of Java web development now lie about 6 years behind me and despite my hectic new life as a non-technical consultant I want to get back in to the tech world and equip myself with some essential web dev skills.
To get me started, I installed a vagrant box using this tutorial:
https://dzone.com/articles/vagrant
... which worked like a treat and got me my Ubuntu box on my Windows host machine up and running in no time. Also it comes with Java 7 and the Tomcat app server that I'm still quite familiar with from past days. Notwithstanding the fact that there are probably better servers out there to practice on, this one works and I'll use it for my tinkering for now. The example web app that came with the tutorial also works, so I'm confident that my Tomcat is running on the guest machine on port 8080.
The next step was to find a good AngularJS and Spring MVC tutorial. Again, while I know that AngularJS is the latest craze in web dev, Spring MVC may be somewhat outdated (?) but since I'm a Java-boy since I hatched from the Uni-egg I wouldn't mind going with it for now.
The tutorial I found is this one:
http://websystique.com/springmvc/spring-mvc-4-angularjs-example/
I downloaded the project from git and deployed it into my tomcat webapps folder. In the user_service.js file I left the REST_SERVICE_URI as http://localhost:8080/Spring4MVCAngularJSExample/user/ given that Tomcat runs on port 8080 on the host Ubuntu box and I can access the application on my guest machine in the browser at http://192.168.33.10:8080/Spring4MVCAngularJSExample
The problem is that the application (while it's showing up in the browser), does not load the mock-users that are populated in the UserServiceImpl class and that should show up when loading the app. When I check my Firefox console under the JavaScript tab, I get the 'Error while fetching Users' error message from the fetchAllUsers function in the user_controller.js script.
I suspect that the problem here is that the front-end (AngularJS $http service) cannot contact the back-end (Spring service). If there were no users in the back-end and returned 0, I wouldn't get the error but an empty set instead, hence my suspicion of some other problem.
My question is how to debug this web app from here? I have tried to look through the front-end console logs using the FF Developer tool (Debugger) and I must admit I haven't written any JUnit test to actually run a test against the Spring service implementation class.
Thanks for your advice, and let me know if I should provide any more details.
Cheers
AHL
Spring controller:
package com.websystique.springmvc.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
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 org.springframework.web.util.UriComponentsBuilder;
import com.websystique.springmvc.model.User;
import com.websystique.springmvc.service.UserService;
#RestController
public class HelloWorldRestController {
#Autowired
UserService userService; //Service which will do all data retrieval/manipulation work
//-------------------Retrieve All Users--------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if(users.isEmpty()){
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
//-------------------Retrieve Single User--------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(#PathVariable("id") long id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
//-------------------Create a User--------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(#RequestBody User user, UriComponentsBuilder ucBuilder) {
System.out.println("Creating User " + user.getUsername());
if (userService.isUserExist(user)) {
System.out.println("A User with name " + user.getUsername() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
userService.saveUser(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
//------------------- Update a User --------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public ResponseEntity<User> updateUser(#PathVariable("id") long id, #RequestBody User user) {
System.out.println("Updating User " + id);
User currentUser = userService.findById(id);
if (currentUser==null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
currentUser.setUsername(user.getUsername());
currentUser.setAddress(user.getAddress());
currentUser.setEmail(user.getEmail());
userService.updateUser(currentUser);
return new ResponseEntity<User>(currentUser, HttpStatus.OK);
}
//------------------- Delete a User --------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteUser(#PathVariable("id") long id) {
System.out.println("Fetching & Deleting User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("Unable to delete. User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
userService.deleteUserById(id);
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}
//------------------- Delete All Users --------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteAllUsers() {
System.out.println("Deleting All Users");
userService.deleteAllUsers();
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}
}
IndexController.java:
package com.websystique.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
public class IndexController {
#RequestMapping(method = RequestMethod.GET)
public String getIndexPage() {
return "UserManagement";
}
}
Javascript user_controller.js:
'use strict';
angular.module('myApp').controller('UserController', ['$scope', 'UserService', function($scope, UserService) {
var self = this;
self.user={id:null,username:'',address:'',email:''};
self.users=[];
self.submit = submit;
self.edit = edit;
self.remove = remove;
self.reset = reset;
fetchAllUsers();
function fetchAllUsers(){
UserService.fetchAllUsers()
.then(
function(d) {
self.users = d;
},
function(errResponse){
console.error('Error while fetching Users');
}
);
}
function createUser(user){
UserService.createUser(user)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while creating User');
}
);
}
function updateUser(user, id){
UserService.updateUser(user, id)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while updating User');
}
);
}
function deleteUser(id){
UserService.deleteUser(id)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while deleting User');
}
);
}
function submit() {
if(self.user.id===null){
console.log('Saving New User', self.user);
createUser(self.user);
}else{
updateUser(self.user, self.user.id);
console.log('User updated with id ', self.user.id);
}
reset();
}
function edit(id){
console.log('id to be edited', id);
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id === id) {
self.user = angular.copy(self.users[i]);
break;
}
}
}
function remove(id){
console.log('id to be deleted', id);
if(self.user.id === id) {//clean form if the user to be deleted is shown there.
reset();
}
deleteUser(id);
}
function reset(){
self.user={id:null,username:'',address:'',email:''};
$scope.myForm.$setPristine(); //reset Form
}
}]);
Javascript user_service.js:
'use strict';
angular.module('myApp').factory('UserService', ['$http', '$q', function($http, $q){
var REST_SERVICE_URI = 'http://localhost:8080/Spring4MVCAngularJSExample/user/';
var factory = {
fetchAllUsers: fetchAllUsers,
createUser: createUser,
updateUser:updateUser,
deleteUser:deleteUser
};
return factory;
function fetchAllUsers() {
var deferred = $q.defer();
$http.get(REST_SERVICE_URI)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching Users');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
function createUser(user) {
var deferred = $q.defer();
$http.post(REST_SERVICE_URI, user)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while creating User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
function updateUser(user, id) {
var deferred = $q.defer();
$http.put(REST_SERVICE_URI+id, user)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while updating User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
function deleteUser(id) {
var deferred = $q.defer();
$http.delete(REST_SERVICE_URI+id)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while deleting User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
}]);
On the server (the vagrant host machine), I can wget the URL and get my data back from the Spring server:
vagrant#precise32:~$ wget http://localhost:8080/Spring4MVCAngularJSExample/user/--2016-08-26 11:08:24-- http://localhost:8080/Spring4MVCAngularJSExample/user/
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:8080... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [application/json]
Saving to: `index.html'
[ <=> ] 206 --.-K/s in 0s
2016-08-26 11:08:24 (9.77 MB/s) - `index.html' saved [206]
vagrant#precise32:~$ less index.html
this gives me the expected result set:
[{"id":1,"username":"Sam","address":"NY","email":"sam#abc.com"},{"id":2,"username":"Tomy","address":"ALBAMA","email":"tomy#abc.com"},{"id":3,"username":"Kelly","address":"NEBRASKA","email":"kelly#abc.com"}]
From your spring controller code all your request mappings are expecting user in the url so if you don't have this the spring controllers will not be called. Is you dispatcher servlet set up to except all http requests E.g /
The problem was a simple mistake:
In the user_service.js file, the REST_SERVICE_URI must be set to the address of the host machine:
http://192.168.33.10:8080/Spring4MVCAngularJSExample/user/
So, when deploying this to a (remote) server, I suppose the 192.168.33.10:8080 portion would need to be changed to that server's IP and the respective Tomcat port.
My problem existed (probably) because I was using a virtual box and had (mistakenly) used the host machine's IP instead of the guest machine's IP. Please correct me if I'm wrong, I'm still somewhat confused ....
this is my annotations:
#RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
now i would like to get request method it is POST in this case and the value it is /trade/createrequisition in this case.
How to do this using reflection in java.
Please help me to resolve this.
EDIT:
this is what is my actual method :
#PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_REQUISITION')")
#RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
public #ResponseBody
void createRequisition(#RequestBody CreateRequisitionRO[] request,
#RequestHeader("validateOnly") boolean validateOnly) {
....
}
this is how i tried to get the #RequestiMapping:
package com.hexgen.reflection;
import java.lang.reflect.Method;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.hexgen.api.facade.HexgenWebAPI;
public class WebAPITest {
public static void main(String[] args) {
try {
Class<HexgenWebAPI> clazz = HexgenWebAPI.class;
Method methodAnnotaion = clazz.getMethod("createRequisition");
RequestMapping methodRequestMappingAnnotation = methodAnnotaion.getAnnotation(RequestMapping.class);
RequestMethod[] methods = methodRequestMappingAnnotation.method();
String[] mappingValues = methodRequestMappingAnnotation.value();
for(RequestMethod req : methods){
System.out.println("RequestMethod : " + req);
}
for (String string : mappingValues) {
System.out.println("mappingValues : " + string);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
but i get this exception :
java.lang.NoSuchMethodException: com.hexgen.api.facade.HexgenWebAPI.createRequisition()
at java.lang.Class.getMethod(Class.java:1605)
at com.hexgen.reflection.WebAPITest.main(WebAPITest.java:12)
As you are trying to get the RequestMapping annotation, and it can be placed at a class or a method, see both uses below:
For a class YourClass:
Class<YourClass> clazz = YourClass.class;
RequestMapping clazzRequestMappingAnnotation = clazz.getAnnotation(RequestMapping.class);
RequestMethod[] methods = clazzRequestMappingAnnotation.method();
String[] mappingValues = clazzRequestMappingAnnotation.value();
For a method methodName at a class YourClass:
Class<YourClass> clazz = YourClass.class;
Method method = clazz.getMethod("methodName");
RequestMapping methodRequestMappingAnnotation = method.getAnnotation(RequestMapping.class);
RequestMethod[] methods = methodRequestMappingAnnotation.method();
String[] mappingValues = methodRequestMappingAnnotation.value();
If this annotation is on a class (eg: Test) then
RequestMapping a = Test.class.getAnnotation(RequestMapping.class);
RequestMethod m = a.getMethod();