I have faced an error regarding interaction between BackboneJS and spring mvc controller. I am unable to access model properties while adding model to collection list. The error prone part of my JS code is as follows:
var Task = Backbone.Model.extend({
defaults: {
taskName: '',
category:'',
completed: false,
dateCreated:0,
dateCompleted:0
}
});
var TaskList = Backbone.Collection.extend({
model: Task,
url : "/todoCollection"
});
// instance of the Collection
var taskList = new TaskList();
var TaskView = Backbone.View.extend({
tagName: 'div',
render: function(){
var itemHTML = _.template($('script.itemview').html());
this.$el.html(itemHTML(this.model.toJSON()));
return this; // enable chained calls
}
});
var TaskCreateView = Backbone.View.extend({
el : ".taskcreate",
initialize : function(){
this.render();
this.input = this.$('#taskInput');
this.categoryInput = this.$('#taskCategory');
taskList.on('add', this.addAll, this);
taskList.on('reset', this.addAll, this);
taskList.fetch();
},
render : function(){
var createListHTML = _.template($('script.create-task-view').html());
this.$el.append(createListHTML);
var createListHTML = _.template($('script.list-view').html());
this.$el.append(createListHTML);
},
events: {
'click button#createButton':'createTask'
},
createTask : function(e){
if(this.input.val() == ''){
alert("Task name expected");
return;
}
if(this.categoryInput.val() == 'None'){
alert("Enter valid category");
return;
}
var newTask = {
taskName: this.input.val().trim(),
completed: false,
category: this.categoryInput.val().trim()
};
taskList.create(newTask,{ wait: true });
this.input.val(''); // clean input box
this.categoryInput.val('None');
},
addOne: function(task){
var view = new TaskView({model: task});
$('#listDiv').append(view.render().el);
},
addAll: function(){
this.$('#listDiv').html(''); // clean the todo list
taskList.each(this.addOne, this);
}
});
var TodoAppView = Backbone.View.extend({
el: '#todoApp',
initialize : function(){
this.render();
},
render : function(){
var appHTML = _.template($('script.appview').html());
this.$el.append(appHTML);
var taskCreateView = new TaskCreateView();
}
});
var TodoApp1 = new TodoAppView();
The url /todoCollection in TaskList is mapped to a spring mvc controller which is defined as follows:
package com.glider.controller;
import com.glider.model.Todo;
import com.glider.service.TodoService;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Date;
import java.util.List;
#Controller
public class TodoCollectionController {
#Autowired
TodoService service;
#RequestMapping(value = "/todoCollection",method = RequestMethod.POST)
#ResponseBody
public String createTodo(#RequestParam(value = "taskName")String taskName,
#RequestParam(value = "category")String category){
System.out.println("Method working");
ObjectMapper objectMapper = new ObjectMapper();
try {
Todo todo = service.create(taskName,category);
String jsonInString = objectMapper.writeValueAsString(todo);
return jsonInString;
} catch (IOException e) {
e.printStackTrace();
}
return "error";
}
#RequestMapping(value = "/todoCollection",method = RequestMethod.GET)
#ResponseBody
public String getAllTodo(){
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Todo> todoList = service.findAllTasks();
String jsonInString = objectMapper.writeValueAsString(todoList);
return jsonInString;
} catch (IOException e) {
e.printStackTrace();
}
return "error";
}
}
The controller method createTodo is expecting parameters like taskName and category. These properties are also mentioned while adding a new task to taskList. On executing above codes on server I am getting an error from browser console defined as follows:
jquery.min.js:4 POST http://localhost:8080/todoCollection 400 (Bad Request)
On Server side error exists as follows:
HTTP Status 400 - Required String parameter 'taskName' is not present.
I am unable to resolve this issue.
You need a Java class that represents the JSON object spring can map values to. #RequestParam is for mapping query string parameters from the request, which is not the case with REST and backbone.
Your code should look something like:
public String createTodo(#RequestBody Todo todo)){}
and spring will set the values in todo from the JSON request
Related
I have been developing new APIs in Springboot 3 and it has been more a headache than something good, but finally I'm able to do something. Issue is that I was able to add Swagger to it, with OpenAPI from Spring-doc release 2. but the configuration file is not reading my properties. Also I have troubles trying to set up my bearer authentication....
This is my actual swagger: Swagger + spring-doc
And third issue related to this is... I keep can't make the swagger to read the default responses... even I configured like in the old versions, but I couldn't make it work...
For properties, I have tried to add them before the config class, and ad a Bean in methods.
For bearer, I was following Baeldung JWT Swagger guide, but It confuses me a little, tried to run but didnt work.
This is my OpenApiConfig class (commented lines are because they are not compatible with tag declaration):
package info.peluka.csaread.config;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Contact;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.info.License;
import io.swagger.v3.oas.annotations.servers.Server;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
#Configuration
#OpenAPIDefinition(
info =#Info(
title = "${module-name}",
version = "${api-version}",
contact = #Contact(
name = "Joseph", email = "CSA_Read_API#peluka.info", url = "https://www.peluka.info"
),
license = #License(
name = "Apache 2.0", url = "https://www.apache.org/licenses/LICENSE-2.0"
),
description = "${module-description}"
),
servers = #Server(
url = "${api.server.url}",
description = "Production"
)
)
public class OpenApiConfig {
private final String moduleName;
private final String apiVersion;
private final String moduleDescription;
public OpenApiConfig(
#Value("${module-name}") String moduleName,
#Value("${api-version}") String apiVersion,
#Value("${module-description}") String moduleDescription) {
this.moduleName = moduleName;
this.apiVersion = apiVersion;
this.moduleDescription = moduleDescription;
}
/**
* Configure the OpenAPI components.
*
* #return Returns fully configure OpenAPI object
* #see OpenAPI
*/
#Bean
public OpenAPI customizeOpenAPI() {
//#formatter:off
final String securitySchemeName = "bearerAuth";
return new OpenAPI()
.addSecurityItem(new SecurityRequirement()
.addList(securitySchemeName))
.components(new Components()
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.description(
"Provide the JWT token. JWT token can be obtained from the /token endpoint. If need to create an user, contact Griffith.")
.bearerFormat("JWT")));
//#formatter:on
}
// #Bean
// public OpenAPI customOpenAPI(#Value("${application-description}")
// String appDesciption,
// #Value("${application-version}")
// String appVersion) {
// return new OpenAPI()
// .info(new Info()
// .title("CSA Read API - Swagger")
// .version(appVersion)
// .description(appDesciption)
// .termsOfService("http://swagger.io/terms/")
// .license(new License().
// name("Apache 2.0").
// url("http://springdoc.org")));
// }
// #Bean
// public OpenAPI customOpenAPI() {
// final String securitySchemeName = "bearerAuth";
// return new OpenAPI()
// .addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
// .components(
// new Components()
// .addSecuritySchemes(securitySchemeName,
// new SecurityScheme()
// .name(securitySchemeName)
// .type(SecurityScheme.Type.HTTP)
// .scheme("bearer")
// .bearerFormat("JWT")
// )
// )
// .info(new Info().title(moduleName).version(apiVersion).description(moduleDescription));
// }
}
Inside my controller, I have this (It's just a code block of two endpoints) :
(...)
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
(...)
#RestController
#RequestMapping("/csa/api")
#Tag(name = "Users & Clan Controller", description = "This Endpoint manages Users and CSA Members")
public class ClanController extends Helper {
(...)
#PostMapping("/token")
#Operation(summary = "Request a token", description = "Return a new token" )
#ApiResponses(value = {
#ApiResponse(responseCode = "200", description = TOKEN_GENERATED_SUCCESSFULLY, content = #Content),
#ApiResponse(responseCode = "400", description = EMAIL_OR_PASSWORD_WRONG, content = #Content),
#ApiResponse(responseCode = "500", description = INTERNAL_SERVER_ERROR, content = #Content) })
public ResponseEntity<Object> token(#RequestParam("email") String email, #RequestParam("password") String password) {
try {
if(!isValidEmail(email))
return ResponseHandler.generateResponse(EMAIL_OR_PASSWORD_WRONG, HttpStatus.BAD_REQUEST, EMPTY);
var optionalUsers = usersRepository.findByEmailAndPassword(email, password);
if (!optionalUsers.isPresent())
return ResponseHandler.generateResponse(EMAIL_OR_PASSWORD_WRONG, HttpStatus.BAD_REQUEST, EMPTY);
var token = getJWTToken(email);
optionalUsers.get().setToken(token);
optionalUsers.get().setLastLogin(LocalDate.now());
usersRepository.save(optionalUsers.get());
return ResponseHandler.generateResponse(TOKEN_GENERATED_SUCCESSFULLY, HttpStatus.OK, new Token(token));
} catch (Exception e){
return ResponseHandler.generateResponse(INTERNAL_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
#PostMapping("/updatePW")
#Operation(summary = "Update user password", description = "Return successful if all validations were OK." )
#ApiResponses(value = {
#ApiResponse(responseCode = "201", description = PASSWORD_CHANGED_SUCCESSFULLY, content = #Content),
#ApiResponse(responseCode = "400", description = EMAIL_OR_PASSWORD_WRONG, content = #Content),
#ApiResponse(responseCode = "406", description = NEW_PASSWORD_ERROR, content = #Content),
#ApiResponse(responseCode = "500", description = INTERNAL_SERVER_ERROR, content = #Content) })
#SecurityRequirement(name = "Bearer Authentication")
public ResponseEntity<Object> updatePassword(#RequestBody OldUser oldUser){
Users userSaved;
try {
if(!isValidEmail(oldUser.getEmail()))
return ResponseHandler.generateResponse(EMAIL_OR_PASSWORD_WRONG, HttpStatus.BAD_REQUEST, oldUser);
if(!oldUser.getNewPassword().isEmpty() && !isValidPassword(oldUser))
return ResponseHandler.generateResponse(NEW_PASSWORD_ERROR, HttpStatus.NOT_ACCEPTABLE, oldUser);
var init = usersRepository.findAll();
var user = usersRepository.findByEmailAndPassword(oldUser.getEmail(), oldUser.getOldPassword());
if(!user.isPresent())
return ResponseHandler.generateResponse(EMAIL_OR_PASSWORD_WRONG, HttpStatus.BAD_REQUEST, oldUser);
user.get().setPassword(oldUser.getNewPassword());
if(!oldUser.getNewPassword().isEmpty()){
userSaved = usersRepository.save(user.get());
} else {
userSaved = usersRepository.save(new Users(user.get()));
}
emailService.sendMail(userSaved, EMAIL_CHANGE_PASSWORD);
return ResponseHandler.generateResponse(PASSWORD_CHANGED_SUCCESSFULLY, HttpStatus.CREATED, userSaved);
} catch (Exception exception) {
return ResponseHandler.generateResponse(INTERNAL_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR, exception.getMessage());
}
}
As you can see in the first image.... For some reasons my "tags" of spring-doc are not working. I have no descriptions, error responses, any definition at all.
I'm working with SpringBoot 3.0.0 and spring-doc version 2.0.0, I have in my pom the following related imported artifacts to spring-doc: springdoc-openapi-starter-webmvc-ui, springdoc-openapi-starter-common, springdoc-openapi-starter-webflux-ui
I'm using also Java 17, and recently I started to use Dockerfile (This is the only way I have to make Swagger works without asking me credentials)
Please, any help with this will be very useful. I have been trying to figure out what to do for several weeks now, and the final users need Swagger implemented for easier access....
PS1: The response of api has this format:
{
"data": {
"name": "TEST NAME",
"email": "TEST.EMAIL#EMAIL.io",
"password": "TEST_PASSWORD",
"dateCreated": "2022-12-13",
"dateModified": "2022-12-13",
"lastLogin": "2022-12-13",
"token": "Bearer TOKEN",
"active": true
},
"message": "User Created Successfully",
"status": 201
}
Basically is:
{
"data" : Object
"message" : String
"status" : Int
}
Where data is the object created in most of cases. Message, just a typo message. status, HTTP Code with the status of operation...
I tried this code below...can anyone kindly help me how to pass the params to the spring method and is it a correct implementation in angularjs.
#GetMapping("/extended-registered-time")
public ResponseEntity<List<Registered_time>> getSubLeaves(#ApiParam Pageable pageable) {
log.debug("REST request to get registered time : {}", pageable);
LocalDate startDate = LocalDate.of(2018,01,15);
LocalDate endDate = LocalDate.of(2018,01,24);
List<Registered_time> result = ExtendedRegisteredTimeService.
getSelectedRegisteredTime(startDate,endDate);
return new ResponseEntity<>(result, HttpStatus.OK);
}
This is the frontend implementation(AngularJs)
.factory('RegisteredTimeService', RegisteredTimeService);
RegisteredTimeService.$inject = ['$resource'];
function RegisteredTimeService ($resource) {
var userName="HGajanayake";
var resourceUrl = '/api/extended-registered-time/{'+userName+'}';
return $resource(resourceUrl, {}, {
'query': {
method: 'GET',
isArray: true
},
'status':{
method:"POST",
isArray:true,
I couldnt get over with #requestParams so I choosed #pathVariable instead.I got the correct result.
This is my Service
function RegisteredTimeService ($resource) {
var userName="HGajanayake";
// var resourceUrl = '/api/extended-registered-time?employee='+userName;
var resourceUrl = "/api/extended-registered-time/:employee";
return $resource(resourceUrl, {}, {
'query': {
method: 'GET',
isArray: true
},
This is my api endpoint
#GetMapping("/extended-registered-time/{employee}")
#ResponseBody
public ResponseEntity<List<Registered_time>> getSubLeaves(#PathVariable String employee) {
List<Registered_time> result = ExtendedRegisteredTimeService.getSelectedRegisteredTime(employee);
return new ResponseEntity<>(result, HttpStatus.OK);
}
This is the controller where I call the service
function RegisteredTimeController ($rootScope, $scope, $state, Employee, RegisteredTimeService,Profile,$resource) {
var firstName="HGajanayake";
var c=RegisteredTimeService.query({employee:firstName},function(result) {
var v=result;
console.log(v);
});
I have created a simple app with Spring and AngularJS with CRUD functions.
Now, my scope variable that contains the arraylist that I pass is not updating when I create a new one.
This is my code for my AngularJS controller
$scope.agency = {id: null, name: '', contact: '', employees: []};
$scope.agencies = [];
$scope.getAllAgencies = function() {
AgencyService.getAllAgencies()
.then(
function (response) {
$scope.agencies = response;
}
)
};
$scope.getAllAgencies();
$scope.createAgency = function(agency) {
AgencyService.createAgency(agency)
.then(
$scope.getAllAgencies(),
function(errReponse){
console.error('Error while creating Agency.');
}
);
};
$scope.submit = function () {
console.log("Saving new Agency");
$scope.createAgency($scope.agency);
$scope.reset();
};
$scope.reset = function(){
$scope.agency = {id: null, name: '', contact: '', employees: null};
$scope.myForm.$setPristine(); //reset Form
};
Service
App.factory('AgencyService', ['$http', '$q', function($http, $q) {
return {
getAllAgencies: function() {
return $http.get('/agency')
.then(
function(response) {
return response.data;
},
function(errResponse){
console.error('Error while fetching agencies');
return $q.reject(errResponse);
}
)
},
createAgency: function(agency) {
console.log("Creating Agency");
return $http.post('/agency', agency)
.then(
function (response) {
return response.data;
},
function (errResponse) {
console.error('Error while create agency');
return $q.reject(errResponse);
}
)
}
};
}]);
And these are my methods in Spring
Get Agencies
#RequestMapping(value = "/agency", method = RequestMethod.GET)
public ResponseEntity<List<Agency>> getAllAgencies() {
List<Agency> agencies = agencyService.getAllAgencies();
if (agencies.isEmpty()) {
return new ResponseEntity<List<Agency>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Agency>>(agencies, HttpStatus.OK);
}
Creation of Agency
#RequestMapping(value = "/agency", method = RequestMethod.POST)
public ResponseEntity<Void> createAgency(#RequestBody Agency agency, UriComponentsBuilder ucBuilder) {
if(agencyService.isAgencyExists(agency)) {
System.out.println("CONFLICT");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
agencyService.saveAgency(agency);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/agency/{id}").buildAndExpand(agency.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
Note: that when I debug, after the post method it does not continue to my get method.
There is no error in this, when I reload it gets all including the one I just created.
Thanks!
I think the create agency function call should be like below:
$scope.createAgency = function(agency) {
AgencyService.createAgency(agency)
.then(
$scope.getAllAgencies,
function(errReponse){
console.error('Error while creating Agency.');
}
);
};
first parameter in then should be the function "$scope.getAllAgencies" instead you are passing the value the function returned "$scope.getAllAgencies()".
I have created a spring controller and a jsp page. In jsp page I am using jquery ajax call to hit the controller. Now, this controller returns a json response as string. Now on based of json response in success method, I want to call a next controller call which will return a ModelAndView jsp page. How can I do this. Below is my code:
JSP Jquery ajax call:
$(document).ready(function(){
$("#submitButton").click(function(e){
var formData = getFormData();
if(formData!=false){
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {jsonData: JSON.stringify(formData)},
dataType: 'json',
success: function(response){
try{
var strResponse=jQuery.parseJSON(response);
}catch(err){}
if(response.status=='ok')
{
alert ("okokokokokokokokok");
//I am successfully reaching till here.
//But in case of this alert box I want to call a
//controller which will return ModelAndView and
//should open a corresponding ModelAndView jsp page.
//something like:
/*
$.ajax({
type: 'GET',
'url': 'http://localhost:8080/Test_ReportingUI/abcxyz.htm',
)};
*/
}
else
{
alert("ERROR!!");
}
},
timeout: 10000,
error: function(xhr, status, err){
if(response.status=='timeout')
{
alert('Request time has been out','');
}
console.log(status,err);
}
}); }
});
});
Controller class methods:
#RequestMapping (value="fieldMappingNext.htm", method=RequestMethod.POST)
#ResponseBody String addFieldMappingNext(#RequestParam String jsonData)
{
String customerID =null;
String objectID = null;
String syncFieldName = null;
String optMapping = null;
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(jsonData);
customerID = requestedJSONObject.getString("customerID");
objectID = requestedJSONObject.getString("objectID");
syncFieldName = requestedJSONObject.getString("syncFieldName");
optMapping = requestedJSONObject.getString("optMapping");
}catch(Exception exex){
exex.printStackTrace();
}
if(optMapping.equalsIgnoreCase("direct")){
long metadataID=rwCustomerService.getMetaDataID(customerID,objectID);
List<RWFieldDetail> list=rwCustomerService.getFieldDetailNames(metadataID);
request.setAttribute("customerID", customerID);
request.setAttribute("objectID", objectID);
request.setAttribute("optMapping", optMapping);
request.setAttribute("syncFieldName", syncFieldName);
request.setAttribute("fieldNames", list);
try {
jsonResponse.put("status", "ok");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonResponse.toString();
}
Second Controller method that I want to call from jquery success method:
#RequestMapping (value="abcxyz.htm", method=RequestMethod.GET)
ModelAndView fieldMapping(){
ModelAndView modelAndView=new ModelAndView("FieldMappingMainScreenNext");
return modelAndView;
}
How do I do this.
Since the second handler method returns ModelAndView, you should redirect from the success callback:
...
success: function(response) {
window.location.replace(response.url);
}
...
In your Java code you can use something like:
Map<String, String> map = new HashMap<String, String>();
if(condition1){
map.put("url","url1.html");
}
if(condition2){
map.put("url","url2.html");
}
Convert it to a JSON string and revert it back. Afterwards, in the jquery portion you'll get the response:
success:function(jsonStr){
var obj = JSON.parse(jsonStr);
var url = obj.url;
}
That is how you can get the url. If you want to load an other page or create an ajax call then you can do it.
I am currently using the Spring MVC, and I am trying to do some stuff with ajax. Basically what I want to do now is display the result from a controller dynamically on a webpage.
I.E. A user pushes a button it goes to the "whatever.do" controller and gets a list and displays that list without having to reload that page.
Anyway does anyone know any good tutorials or example projects?
It is very simple, I don't even think a special tutorial is needed (apart from a generic spring-mvc one).
Make a #RequestMapping("/foo") method that returns a List<Foo>
Have <mvc:annotation-driven /> in your dispatcher-servlet.xml to activate handler mappings and convertors
Put Jackson (json serializer) on your classpath
Use $.getJSON("/foo", function(data) {..}); (jquery) - you will get a JSON-encoded list of your Foo objects
Spring will detect that the browser requests a json response, and converts your objects using Jackson.
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
http://krams915.blogspot.com/2011/01/spring-mvc-3-and-jquery-integration.html
your controller must have in following format when you are using with spring along with ajax:
#RequestMapping(value = "/show.ajax", method = RequestMethod.POST)
public #ResponseBody List<your object type> your_method_name() {
//code logic
return list_of_your_object;
}
also your java script code on jsp page in following format:
<script>
function your_javascript_fun_name() {
$.ajax({
type : 'POST',
url : 'show.ajax',//this is url mapping for controller
success : function(response) {
alert(response);
//this response is list of object commming from server
},
error : function() {
alert("opps error occured");
}
});
}
</script>
import jquery library in jsp page
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
var id = $("#id").val();
var resourceURL = $("#contextpath").val()+"/customer/retrivebyid/"+id;
$.ajax({
url : resourceURL,
type : 'GET',
dataType : 'json',
async : false,
success: function(data) {
var successflag = data.response.successflag;
var errors = data.response.errors;
var results = data.response.result;
if(successflag == "true"){
$.each(results, function (i, result) {
$("#id").val((result.id == undefined || result.id == null || result.id.length <= 0) ? "-" : result.id);
$("#name").val((result.customername == undefined || result.customername == null || result.customername.length <= 0) ? "-" : result.customername);
});
}else{
$("#errorMsgContent").html(errors);
$.fancybox.open('#errorMsg');
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#errorMsgContent").html(thrownError);
$.fancybox.open('#errorMsg');
}
});
#RequestMapping(value = "/retrivebyid/{id}", method = RequestMethod.GET)
public #ResponseBody String retriveUser(#PathVariable long id, Model model,HttpServletRequest request) {
String jsonresp = null;
try {
List<CustomerDO> customerList = new CustomerService().retriveById(id);
jsonresp = CustomerUtil.getCustomerList(customerList).toString();
} catch (Exception e) {}
if (jsonresp != null) {
return jsonresp.toString();
} else {
return null;
}
}
public static JSONObject getCustomerList(List<CustomerDO> empList)throws AppException {
JSONObject responseJSON = new JSONObject();
JSONObject resultJSON = new JSONObject();
try {
resultJSON.put(CommonConstants.SUCCESS_FLAG, CommonConstants.TRUE);
resultJSON.put(CommonConstants.ERRORS, "");
JSONArray resultJSONArray = new JSONArray();
for (CustomerDO customer : empList) {
resultJSONArray.put(getCustomerDetailObject(customer));
}
resultJSON.put(CommonConstants.RESULTS, resultJSONArray);
responseJSON.put(CommonConstants.RESPONSE, resultJSON);
} catch (JSONException e) {
e.printStackTrace();
}
return responseJSON;
}
private static JSONObject getCustomerDetailObject(CustomerDO customer)throws JSONException, AppException {
JSONObject result = new JSONObject();
result.put(CommonConstants.ID, String.valueOf(customer.getId()));
result.put(CommonConstants.CUSTOMER_NAME, String.valueOf(customer.getName()));
return result;
}