I am trying to hit restful api through resttemplate but i am getting Request processing failed - resttemplate

error:
package com.concretepage.bean;
import org.springframework.beans.factory.annotation.Value;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
#Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
controller class:
package com.concretepage.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
import com.concretepage.bean.Quote;
#Controller
public class LoginController {
#RequestMapping(value="login", method = RequestMethod.GET)
public String login(){
System.setProperty("proxyHost", "proxy1.wipro.com");
System.setProperty("proxyPort", "8080");
return "redirect:pages/login.jsp";
}
#RequestMapping(value="pages/userCheck", method = RequestMethod.POST)
public String userCheck(ModelMap model, HttpServletRequest request) {
String name=request.getParameter("name");
String pwd=request.getParameter("pwd");
if("concretepage".equalsIgnoreCase(name)&&"concretepage".equalsIgnoreCase(pwd)){
model.addAttribute("message", "Successfully logged in.");
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters =restTemplate.getMessageConverters();
MappingJacksonHttpMessageConverter map =new MappingJacksonHttpMessageConverter();
messageConverters.add(map);
restTemplate.setMessageConverters(messageConverters);
Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
System.out.println(quote.toString());
}else{
model.addAttribute("message", "Username or password is wrong.");
}
return "redirect:success.jsp";
}
}
Qoute class:
package com.concretepage.bean;
import org.springframework.beans.factory.annotation.Value;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
#Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}

Your import org.springframework.beans.factory.annotation.Value might be wrong in Quote.class Json object.
Response from the RequestingURL
you are trying to hit as below.
You have to design your Json object as per the response returned by the server.
{
"type": "success",
"value": {
"id": 4,
"quote": "Previous to Spring Boot, I remember XML hell, confusing set up, and many hours of frustration."
}
}
You may have to create another POJO object Value with the properties id and quote and define this as a property in Quote class.

Related

spring boot override date

I am writing integration testing for the REST API. I am facing an issue while while testing
the logic for validateDate in MyService class. I would like to mock the currentDate() method MyService class in order to write the different test scenarios. How can I achieve this in spring boot?
#RunWith(SpringRunner.class)
#SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyControllerTest {
TestRestTemplate restTemplate = new TestRestTemplate();
#LocalServerPort
private int port;
//#MockBean
//MyService service;
#Test
public void testRetrieveStudentCourse() {
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
ResponseEntity<String> response = restTemplate.exchange(
createURLWithPort("/validatedate"),
HttpMethod.GET, entity, String.class);
String expected = "true";
assertEquals(expected, response.getBody(), false);
}
private String createURLWithPort(String uri) {
return "http://localhost:" + port + uri;
}
import java.util.Date;
import org.springframework.stereotype.Service;
public interface IMyService {
public boolean validateDate(Date date);
}
#Service
public class MyService implements IMyService{
public boolean validateDate(Date date) {
if(currentDate().before(date)) {
return true;
}
return false;
}
private Date currentDate() {
return new Date();
}
}
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MyController {
#Autowired
IMyService service;
#GetMapping(value = "/validatedate", produces = MediaType.APPLICATION_JSON_VALUE)
public boolean validateDate() {
// date object will be retrieved.
Date date = somedate;
service.validateDate(date);
}
}
Mockito.when(myservice.currentDate()).thenReturn(null);
doReturn(null).when(myservice.currentDate());
import static org.mockito.Mockito.when;
........................
public class MyControllerTest {
#Mock
IMyService service
.........................................
#Test
public void myTest(){
when(service.validateDate(date)).thenReturn(false);
......... do test .............................................
}
}

Creating custom unique constraints

I Defined my #FuSsA_UniqueKey constraint annotation:
package com.fussa.employee.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
#Constraint(validatedBy = { UniqueIDValidator.class })
#Target({ ElementType.TYPE })
#Retention(RetentionPolicy.RUNTIME)
public #interface FuSsA_UniqueKey {
String columnNames();
String message() default "{Value is not unique}";
Class<?>[]groups() default {};
Class<? extends Payload>[]payload() default {};
}
Having defined my annotation, i created a constraint validator UniqueIDValidator, which is able to validate elements with a #FuSsA_UniqueKey annotation:
package com.fussa.employee.util;
import java.io.Serializable;
import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintValidatorContext.ConstraintViolationBuilder;
import javax.validation.ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderDefinedContext;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
public class UniqueIDValidator implements ConstraintValidator<FuSsA_UniqueKey, Serializable> {
#Autowired
private SessionFactory sessionFactory;
private Session s;
private String uniqueField;
private FuSsA_UniqueKey unique;
public void initialize(FuSsA_UniqueKey unique) {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
uniqueField = unique.columnNames();
}
#Override
public boolean isValid(Serializable arg0, ConstraintValidatorContext arg1) {
String a = arg0.getClass().getSimpleName();
String query = String.format("from %s where %s = :%s ", a, uniqueField, uniqueField);
List<?> list = null;
try {
s = sessionFactory.getCurrentSession();
s.setFlushMode(FlushMode.COMMIT);
list = s.createQuery(query).setParameter(uniqueField, "FuSsA").list();
} catch (HibernateException e) {
s = sessionFactory.openSession();
s.setFlushMode(FlushMode.COMMIT);
list = s.createQuery(query).setParameter(uniqueField, "FuSsA").list();
} finally {
// this is to reset the hibernate config I think
s.setFlushMode(FlushMode.AUTO);
}
if (list != null && !(list.size() > 1)) {
return true;
} else {
ConstraintViolationBuilder cvb = arg1.buildConstraintViolationWithTemplate(unique.message());
NodeBuilderDefinedContext nbdc = cvb.addNode(unique.columnNames());
ConstraintValidatorContext cvc = nbdc.addConstraintViolation();
cvc.disableDefaultConstraintViolation();
return false;
}
}
}
methode saveEmployee on my Controller:
#Autowired
EmployeeService service;
#Autowired
MessageSource messageSource;
#Autowired
private Validator validator;
#RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveEmployee(#Valid Employee employee, BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
Set<ConstraintViolation<Employee>> violations = validator.validate(employee);
if (!violations.isEmpty()) {
FieldError ssnError = new FieldError("employee", "ssn", messageSource.getMessage("non.unique.ssn",
new String[] { employee.getSsn() }, Locale.getDefault()));
result.addError(ssnError);
return "registration";
} else {
service.saveEmployee(employee);
model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
return "success";
}
}
Edit
i also add to my #Configuration class AppConfig this methode, so i can autowired it on my controller "not sure if its correct":
#Bean
public Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
when i try to save my object .. i got this errors:
Caused by: javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:451)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:127)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:592)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:555)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:490)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:454)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:406)
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:204)
at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:108)
at org.springframework.validation.DataBinder.validate(DataBinder.java:866)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.validateIfApplicable(ModelAttributeMethodProcessor.java:164)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:111)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:99)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
... 31 more
Caused by: java.lang.NullPointerException
at com.fussa.employee.util.UniqueIDValidator.isValid(UniqueIDValidator.java:54)
at com.fussa.employee.util.UniqueIDValidator.isValid(UniqueIDValidator.java:1)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:448)
... 54 more
so the error is catched on that line :
ConstraintViolationBuilder cvb = arg1.buildConstraintViolationWithTemplate(unique.message());
thanks for any advices..
I fixed this issue by Initializing the variable unique :
public void initialize(FuSsA_UniqueKey unique) {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
this.unique = unique;
uniqueField = unique.columnNames();
}

Trying to post username and password to restful API using resttemplate but getting error.

I am getting error when i try to run the code as Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 407 Proxy Authentication Required.
Controller class:
package com.concretepage.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
import com.concretepage.bean.Quote;
#Controller
public class LoginController {
#RequestMapping(value="login", method = RequestMethod.GET)
public String login(){
System.setProperty("proxyHost", "proxy1.wipro.com");
System.setProperty("proxyPort", "8080");
return "redirect:pages/login.jsp";
}
#RequestMapping(value="pages/userCheck", method = RequestMethod.POST)
public String userCheck(ModelMap model, HttpServletRequest request) {
String name=request.getParameter("name");
String pwd=request.getParameter("pwd");
if("concretepage".equalsIgnoreCase(name)&&"concretepage".equalsIgnoreCase(pwd)){
model.addAttribute("message", "Successfully logged in.");
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters =restTemplate.getMessageConverters();
MappingJacksonHttpMessageConverter map =new MappingJacksonHttpMessageConverter();
messageConverters.add(map);
restTemplate.setMessageConverters(messageConverters);
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("userName", name);
params.add("passWord", pwd);
Quote result = restTemplate.postForObject( "http://gturnquist-quoters.cfapps.io/api/random", params, Quote.class) ;
System.out.println("username="+result.getValue().getUserName());
/*Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
System.out.println(quote.getType());*/
}else{
model.addAttribute("message", "Username or password is wrong.");
}
return "redirect:success.jsp";
}
}
qoute bean class:
package com.concretepage.bean;
import com.concretepage.bean.Value;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
#Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}

spring MVC use #JsonView on spring-data Page

I'm using Spring-MVC, Spring-data-jpa, jackson on a Jhipster project.
I managed to use the #JsonView annotation on an object and it works well when the method in the rest controller return a type ResponseEntity<List<MyObject>> but I can't make it work when the method return type is ResponseEntity<Page<MyObject>>.
I've tried to set MapperFeature.DEFAULT_VIEW_INCLUSION to true (which default is false). When I do it, all attributes are serialized. But filtering through #JsonView does not work anymore.
I can't modify the Page object because it's a Spring-data object.
I'm looking for a way to tell jackson to include all attributes of the Page object.
Here is my code:
My entity:
#Entity
#Table(name = "T_REGION")
public class Region implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "code", nullable = false)
private Integer code;
#Column(name = "name", length = 60, nullable = false)
#JsonView(View.Summary.class)
private String name;
// Getters and setters
}
My rest controller:
#RestController
#RequestMapping("/api")
public class RegionResource {
#RequestMapping(value = "/regionsearch1",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#JsonView(View.Summary.class)
public ResponseEntity<Page<Region>> findAll1(
#RequestParam(value = "page" , required = false) Integer offset,
#RequestParam(value = "per_page", required = false) Integer limit,
Sort sort)
throws URISyntaxException {
Pageable pageRequest = PaginationUtil.generatePageRequest(offset, limit, sort);
Page<Region> page = regionRepository.findAll(pageRequest);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/regionsearch1", pageRequest);
return new ResponseEntity<>(page, headers, HttpStatus.OK);
}
#RequestMapping(value = "/regionsearch2",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#JsonView(View.Summary.class)
public ResponseEntity<List<Region>> findAll2(
#RequestParam(value = "page" , required = false) Integer offset,
#RequestParam(value = "per_page", required = false) Integer limit,
Sort sort)
throws URISyntaxException {
Pageable pageRequest = PaginationUtil.generatePageRequest(offset, limit, sort);
Page<Region> page = regionRepository.findAll(pageRequest);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/regionsearch2", pageRequest);
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
}
findAll1 returns:
[
{
"name": "Ile-de-France"
},
{
"name": "Champagne-Ardenne"
},
....
]
findAll2 returns:
{}
The object Page has no #JsonView on its attributes therefore no attributes are serialized.
I can't find a way to tell Jackson to include all Page attributes even when #JsonView is used.
Any ideas ?
Another way to return all page elements is to create your own implementation for the Page interface (including the JsonView you want):
JsonPage
public class JsonPage<T> extends org.springframework.data.domain.PageImpl<T> {
public JsonPage(final List<T> content, final Pageable pageable, final long total) {
super(content, pageable, total);
}
public JsonPage(final List<T> content) {
super(content);
}
public JsonPage(final Page<T> page, final Pageable pageable) {
super(page.getContent(), pageable, page.getTotalElements());
}
#JsonView(JsonViews.UiView.class)
public int getTotalPages() {
return super.getTotalPages();
}
#JsonView(JsonViews.UiView.class)
public long getTotalElements() {
return super.getTotalElements();
}
#JsonView(JsonViews.UiView.class)
public boolean hasNext() {
return super.hasNext();
}
#JsonView(JsonViews.UiView.class)
public boolean isLast() {
return super.isLast();
}
#JsonView(JsonViews.UiView.class)
public boolean hasContent() {
return super.hasContent();
}
#JsonView(JsonViews.UiView.class)
public List<T> getContent() {
return super.getContent();
}
}
Next return this class to the controller layer:
Service
#Override
public Page<User> findAll(final int page) {
PageRequest pr = new PageRequest(page, pageSize, new Sort(Sort.Direction.DESC, "dateCreated"));
return new JsonPage<User>(userRepository.findAll(pr), pr);
}
Controller
#JsonView(JsonViews.UiView.class)
#RequestMapping(method = RequestMethod.GET, value = "{page}")
public Page<User> getUsers(#PathVariable final int page) {
return userService.findAll(page);
}
I have done like this , it's working well
package com.natixis.spring.ws.configuration;
import java.io.IOException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
#Configuration
public class JacksonAdapter extends WebMvcConfigurerAdapter {
#Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
return new Jackson2ObjectMapperBuilder()
.failOnUnknownProperties(false)
.serializationInclusion(Include.NON_EMPTY)
.serializerByType(Page.class, new JsonPageSerializer());
}
public class JsonPageSerializer extends JsonSerializer<Page<?>>{
#Override
public void serialize(Page<?> page, JsonGenerator jsonGen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
ObjectMapper om = new ObjectMapper()
.disable(MapperFeature.DEFAULT_VIEW_INCLUSION)
.setSerializationInclusion(Include.NON_EMPTY);
jsonGen.writeStartObject();
jsonGen.writeFieldName("size");
jsonGen.writeNumber(page.getSize());
jsonGen.writeFieldName("number");
jsonGen.writeNumber(page.getNumber());
jsonGen.writeFieldName("totalElements");
jsonGen.writeNumber(page.getTotalElements());
jsonGen.writeFieldName("last");
jsonGen.writeBoolean(page.isLast());
jsonGen.writeFieldName("totalPages");
jsonGen.writeNumber(page.getTotalPages());
jsonGen.writeObjectField("sort", page.getSort());
jsonGen.writeFieldName("first");
jsonGen.writeBoolean(page.isFirst());
jsonGen.writeFieldName("numberOfElements");
jsonGen.writeNumber(page.getNumberOfElements());
jsonGen.writeFieldName("content");
jsonGen.writeRawValue(om.writerWithView(serializerProvider.getActiveView())
.writeValueAsString(page.getContent()));
jsonGen.writeEndObject();
}
}
}
Regards,
RĂ©gis LIMARE
I know this is an old question, but you can use something like this for a Page of objects
#Configuration
public class JacksonAdapter implements WebMvcConfigurer {
#Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
return new Jackson2ObjectMapperBuilder().failOnUnknownProperties(false).serializerByType(Page.class,
new JsonPageSerializer());
}
public class JsonPageSerializer extends JsonSerializer<Page> {
#Override
public void serialize(Page page, JsonGenerator jsonGen, SerializerProvider serializerProvider)
throws IOException {
ObjectMapper om = new ObjectMapper().disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
jsonGen.writeStartObject();
jsonGen.writeFieldName("size");
jsonGen.writeNumber(page.getSize());
jsonGen.writeFieldName("number");
jsonGen.writeNumber(page.getNumber());
jsonGen.writeFieldName("totalElements");
jsonGen.writeNumber(page.getTotalElements());
jsonGen.writeFieldName("last");
jsonGen.writeBoolean(page.isLast());
jsonGen.writeFieldName("totalPages");
jsonGen.writeNumber(page.getTotalPages());
jsonGen.writeObjectField("sort", page.getSort());
jsonGen.writeFieldName("first");
jsonGen.writeBoolean(page.isFirst());
jsonGen.writeFieldName("numberOfElements");
jsonGen.writeNumber(page.getNumberOfElements());
jsonGen.writeFieldName("content");
jsonGen.writeRawValue(
om.writerWithView(serializerProvider.getActiveView()).writeValueAsString(page.getContent()));
jsonGen.writeEndObject();
}
}
}
I've encountered the same problem and I solved it by setting MapperFeature.DEFAULT_VIEW_INCLUSION to true, but you should annotate all fields in classes where you want to apply your view with JsonView or JsonIgnore annotation so they wouldn't be included by default in json.

I am new In spring & Hibernate How To add profile image path in database using Springs 3 MVC

Value Object Class
package com.admin.modelVO;
import java.sql.Timestamp;
public class UserProfileVO{
private String userName;
private String password;
private String fName;
private String lName;
private String dob;
private String emailId;
private String contactNo;
private String gender;
private String photo;
private Timestamp createdDate;
private Boolean status;
private Integer rollId;
public Integer getRollId() {
return rollId;
}
public void setRollId(Integer rollId) {
this.rollId = rollId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
}
Second Controller
package com.admin.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.admin.modelVO.UserProfileVO;
import com.admin.service.UserProfileService;
#Controller
public class UserProfileController{
#Autowired
UserProfileService userProfileService;
#RequestMapping(value="/userprofile1",method = RequestMethod.GET)
public String userprofile1(#ModelAttribute("UserProfileVO") UserProfileVO userProfileVO,ModelMap modelMap, HttpServletRequest request, HttpServletResponse response){
return "userprofile1";
}
#RequestMapping(value="/userprofile",method = RequestMethod.POST)
public String userprofile(#ModelAttribute("UserProfileVO") UserProfileVO userProfileVO,ModelMap modelMap, HttpServletRequest request, HttpServletResponse response,RedirectAttributes redirect){
String result=userProfileService.listUserProfile(userProfileVO);
request.setAttribute("userlist", result);
System.out.println("dfghdfg"+result);
return "success";
}
}
3.DaoImplement
package com.admin.daoImpl;
import java.sql.Timestamp;
import java.util.Date;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.admin.dao.UserProfileDao;
import com.admin.entity.Usermaster;
import com.admin.modelVO.UserProfileVO;
#Repository
public class UserProfileDaoImpl implements UserProfileDao{
#Autowired
SessionFactory sessionFactory;
Date date=new Date();
public String listUserProfile(UserProfileVO userProfileVO) {
String userId=null;
Usermaster userMaster=new Usermaster();
sessionFactory.getCurrentSession().beginTransaction();
userMaster.setUsername(userProfileVO.getUserName());
userMaster.setPassword(userProfileVO.getPassword());
userMaster.setFname(userProfileVO.getfName());
userMaster.setLname(userProfileVO.getfName());
userMaster.setDob(userProfileVO.getDob());
userMaster.setEmail(userProfileVO.getEmailId());
userMaster.setGender(userProfileVO.getGender());
userMaster.setContactNo(userProfileVO.getContactNo());
userMaster.setPhoto(userProfileVO.getPhoto());
userMaster.setStatus(true);
userMaster.setCreatedDate(date);
userMaster.setRoleId(2);
sessionFactory.getCurrentSession().save(userMaster);
System.out.println("dsfsf"+userMaster);
sessionFactory.getCurrentSession().getTransaction().commit();
return userId;
}
}
I want to upload profile picture with registration page and i want to set contxt path on database and image is perticulor folder. i will post you DaoImpl VO and Controller where we put the code and my object is "PHOTO" so i want to stored it
You can refer following method to handle image uploading i.e. multipart request. You can not this method directly in your code. This is for understanding only.
For this you will need :
commons-fileupload.jar
and
commons-io.jar
public String handleFileUpload(HttpServletRequest request,
#RequestParam CommonsMultipartFile[] fileUpload) throws Exception {
System.out.println("description: " + request.getParameter("description"));
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload) {
System.out.println("Saving file: " + aFile.getOriginalFilename());
if (!aFile.getOriginalFilename().equals("")) {
aFile.transferTo(new File(saveDirectory + aFile.getOriginalFilename()));
}
}
}
// returns to the view "Result"
return "Result";
}
Here: "saveDirectory" string variable can be any path on your server, where you want to store files.
in configuration you will need to add:
#Bean(name = "multipartResolver")
public CommonsMultipartResolver getMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxInMemorySize(1048576);
multipartResolver.setMaxUploadSize(20971520);
return multipartResolver;
}
EDIT :
// get absolute path of the application
ServletContext context = request.getServletContext();
String saveDirectory = context.getRealPath("");
System.out.println("saveDirectory = " + saveDirectory);
You dont have to store whole path to the file. Just store file name (that you can give any unique name every time). So in DAOImpl write code for storing filename.

Resources