Error while generating json content using jersy - json

I'm working on jersy project when a lunch tomcat server i get this exception :
MessageBodyWriter not found for media type=application/json
This is my code :
#Path("/activities")
public class ActivityResource {
private ActivityRepository activityRepository = new ActivityRepositoryStub();
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Activity> getAllActivities(){
return activityRepository.findAllActivities();
}

You need to add jersy-media-moxy jar in your Lib folder or add it in your pom.xml that why you have this error message
if you want to return xml content make shur that you have #XmlRootElement on your entity because jersy use JAXB to map java object to xml
#XmlRootElment
public class Activity {
}

Related

How to convert a List to JSON?

I am trying to display a List of items in JSON format. My code structure utilizing SpringBoot and JPA Repository on Server side:
Entity class
Repository class created
Service written (contains repository.findAll() function)
Controller class
Goal is to output the record set extracted from SQL database onto localhost:8080/api/getinspection.
I have added Gson dependency in my pom.xml and in my controller class added code to convert to JSON.
I get an error saying:
java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy.
Forgot to register a type adapter?
I have researched on type adapter on stackoverflow and tried to implement the solution, but in vain. Please help.
Service class
public List<INSPCTN> getInspections() {
return inspctnRepository.findAll(); }
Controller Class
#Service
public class InspectionService {
#Autowired
INSPCTNRepository inspctnRepository;
#GetMapping(path="/getInspection", produces = "application/JSON")
public String getInspections() {
List<INSPCTN> list = inspectionService.getInspections();
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
}
Expected result: List of records from the database in JSON format
Actual:
There was an unexpected error (type=Internal Server Error, status=500).
Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy.
Forgot to register a type adapter?

How to access java abc.properties file values in json formate using Spring framework

i'm trying to access the values of properties file in spring framework. now i have bean file and controller. so how to access properties file value in json formate using bean
For accessing single value can be used Spring annotations "PropertySource" and "Value".
#PropertySource("classpath:application.properties")
public class SomeClass {
#Value("${some.property}")
private String someProperty;
...
}
For accessing/looping all spring properties, check this solution looping-through-all-the-properties-in-a-file-with-spring-and-java
Controller sample code:
#RestController
public class PropertiesController {
#Autowired
Properties props;
#RequestMapping(value = {"/properties"}, method = RequestMethod.GET, produces= MediaType.APPLICATION_JSON_UTF8_VALUE)
public Set<Map.Entry<Object, Object>> getProperties() {
return props.entrySet();
}
}
if you are Using spring-boot then add spring-actuator dependency which by defaults expose /env endpoint and spits out all the properties loaded in the spring container in json format.

Unable to access HTML files from spring MVC

I am writing basic spring mvc application which have no xml configuration its annotation based. I am trying to access html files like
" localhost:9090/help.html " but i get error
No mapping found for HTTP request with URI [/help.html] in DispatcherServlet with name 'dispatcher'
here is my config
#EnableWebMvc
#Configuration
#ComponentScan({ "com.example.test" })
public class WebConfig extends WebMvcConfigurationSupport {
#Bean
public InternalResourceViewResolver internalResourceViewResolver(){
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/jsp/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/*");
registry.addResourceHandler("/**/*").addResourceLocations("/templates/*");
}
}
my html pages are inside
webapp->templates
i have tried many question here but none helped and all of them relates to xml config
any suggestions ??
Ok I figured this out. It was just a silly mistake. In addResourceLocations i removed * at the end and bingo issued resolved
so this is wrong
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/*");
correct form is
registry.addResourceHandler("/resources/**").addResourceLocations("/resources");
Now i can access html pages directly like
localhost:8080/resources/help.html
even this is possible now
localhost:8080/help.html
because i have added another resource-handler as addResourceHandler("/*\*/**")

Filtering entity fields dynamically in Spring Data rest json Response

Hi I have a requirement to dynamically ignore entity fields in spring data rest response [I know they can be done in a static way by using #JsonIgnore annotation] ideally based on a spring security Role .The role part is still manageable but how to dynamically ignore fields in the json response is a challenge.
After some analysis and the docs I think jackson is the way to go as spring data rest does provide jackson customization via jackson modules and mixins http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.custom-jackson-deserialization .
So I think in jackson api it could be done via #jsonFilter and then suppling the same when the ObjectMapper write the object [more details here http://www.cowtowncoder.com/blog/archives/2011/09/entry_461.html] .
But I am not sure how this could be wired up with Spring data rest (basically the part where I acan inject the filterprovider into spring data rest objectmapper).Let me know if anyone has tried this or someone from the Spring data team has insights .
Will post an answer myself If I am able to achieve the same.
UPDATE
So I figured out that the way to implement custom filtering is through the jackson BeanSerializerModifier .Got great help from #cowtowncoder on twitter .Also helpful reference or holy grails for filtering with jackson http://www.cowtowncoder.com/blog/archives/2011/02/entry_443.html
So yes finally I was able to solve this .The trick here is to use a custom BeanSerializerModifier and register it via a Custom Module [which is the custom hook available to customize spring data rest jackson serialization],something like
setSerializerModifier( new CustomSerializerModifier()).build()));
now you can customize our BeanSerializerModifier by overriding the method changeProperties to apply your custom filter ,which basically includes and excludes BeanPropertyWriter based on your logic .sample below
List<BeanPropertyWriter> included = Lists.newArrayList();
for (BeanPropertyWriter property : beanProperties)
if (!filter.contains(property.getName()))
included.add(property);
this way you can include any logic per class or otherwise and filter properties form response in a custom manner.Hope It Helps
Also have updated my code on github do look at https://github.com/gauravbrills/SpringPlayground
This example shows how to implement a dynamic JSON transformation (filtering) in a Spring Boot REST controller. It is using AOP controller advice to change controller method output in runtime. Code on github: https://github.com/andreygrigoriev/jsonfilter
AOP Advice
#ControllerAdvice
#SuppressWarnings("unused")
public class FilterAdvice implements ResponseBodyAdvice<Object> {
#Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
String fields = ((ServletServerHttpRequest) request).getServletRequest().getParameter("fields");
return new FilterMappingJacksonValue<>(body, StringUtils.isEmpty(fields) ? new String[] {} : fields.split(","));
}
#Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
}
FilterMappingJacksonValue
public class FilterMappingJacksonValue<T> extends MappingJacksonValue {
public FilterMappingJacksonValue(final T value, final String... filters) {
super(value);
setFilters(new SimpleFilterProvider().addFilter("dynamicFilter",
filters.length > 0 ? SimpleBeanPropertyFilter.filterOutAllExcept(filters) : SimpleBeanPropertyFilter.serializeAll()));
}
}
Simple DTO
#Data
#AllArgsConstructor
#JsonFilter("dynamicFilter")
public class Book {
String name;
String author;
}
BookController
#RestController
#SuppressWarnings("unused")
public class BookController {
#GetMapping("/books")
public List<Book> books() {
List<Book> books = new ArrayList<>();
books.add(new Book("Don Quixote", "Miguel de Cervantes"));
books.add(new Book("One Hundred Years of Solitude", "Gabriel Garcia Marquez"));
return books;
}
}

Struts 2 json annotation

Ive been wanting to create a struts 2 with json return type using the annotation configuration. Ive successfully created this using the xml-type configuration like this snippet:
<action name="FetchJSON" class="com.stikiflem.Json" method="getJSON">
<result type="json"/>
</action>
I have posted a working demo of using an xml-type config here
http://stikiflem.wordpress.com/2008/08/27/struts-2-json-sample/
But how do I convert this to annotation? Here is my sample class:
public class JsonAction extends ActionSupport{
private List sampleList;
public String execute() {
sampleList = new ArrayList();
sampleList.add("stikiflem sample 1");
sampleList.add("stikiflem sample 2");
sampleList.add("stikiflem sample 3");
sampleList.add("stikiflem sample 4");
System.out.println("----------------------------------------------");
System.out.println("----------------------------------------------");
System.out.println("-sample111List:" + sampleList.toString());
System.out.println("----------------------------------------------");
System.out.println("----------------------------------------------");
return SUCCESS;
}
#Action(value="FetchJSON", results = {
#Result(name="success", type="json")
})
public String getJSON(){
System.out.println("get jason ko");
return execute();
}
public List getSampleList() {
return sampleList;
}
public void setSampleList(List sampleList) {
this.sampleList = sampleList;
}
}
Tried calling it by "json.action", it triggers the execute() method of course but cannot return a json type. Calling it by "FetchJSON" doesnt do anything. This question sounds stupid but there are just a small amount of tutorials and example of a detailed annotation in the net. Ive read a Manning Struts 2 in action book but it just barely scratch the surface, just the typical hello world and sucess,input redirection.
Ive searched the net high and low and so far, i havent seen any. I know there are a lot of programmers searching for this too.Hope someone can enlighten me about this one. Ive been banging my head on this for days already. :(
A similar question was asked here:
Struts2 JSON Plugin With Annotations
I got your action working by annotating it as follows:
#ParentPackage("json-default")
#Result(name="success", type="json")
public class JsonAction extends ActionSupport {
Get the JAR Dependencies
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.3.20</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.3.20</version>
</dependency>
Convention Plugin
The Convention Plugin is bundled with Struts since 2.1 and replaces the Codebehind Plugin and Zero Config plugins. It provides the following features :
Action location by package naming conventions
Result (JSP, FreeMarker, etc) location by naming conventions
Class name to URL naming convention
Package name to namespace convention
Action name overrides using annotations
Namespace overrides using annotations
XWork package overrides using annotations
Set Parent Package
Using annotation set the package as json-default to support the JSON.
#ParentPackage("json-default")
Set Result Type
#Result(name="success", type="json")
Define filter in web.xml
Define the struts 2 filter in web.xml and pass the action class by defining actionPackages.
Action Class
In this class data converted into JSON format.
#Result(name = "success", type = "json")
#ParentPackage("json-default")
public class StrutsJsonAnnotationAction extends ActionSupport {
private static final long serialVersionUID = 3516335522937177571L;
private String name = "Narendra Modi";
private String designation = "Prime Minister of India";
private String dob = "17 September 1950";
private String[] education = {"MA", "BA"};
private List<String> favBooks = new ArrayList<String>();
private Map<String, String> assumedOffice = new HashMap<String, String>();
public StrutsJsonAnnotationAction() {
favBooks.add("Ramayan");
favBooks.add("Geeta");
assumedOffice.put("President", "Pranab Mukherjee");
assumedOffice.put("Preceded by", "Manmohan Singh");
}
#org.apache.struts2.convention.annotation.Action("/india")
#Override
public String execute() {
return SUCCESS;
}
Source:
http://www.websparrow.org/struts/struts2-and-json-integration-using-annotation-example