Configuring POJOMappingFeature without web.xml - jersey

I am using Jersey to marshall a Java object to JSON, as follows:
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
#POST
#Consumes({MediaType.APPLICATION_JSON})
#Path("/test")
public Response replay(String input) throws IOException {
return Response.ok().entity(new MyClass()).build();
}
Am receiving the following exception:
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.company.MyClass, and Java type class com.company.MyClass, and MIME media type application/octet-stream was not found.
I understand that the solution here is to :
Add the jackson-jaxrs-json-provider dependency
Use com.sun.jersey.api.json.POJOMappingFeature
POJOMappingFeature is normally configured in web.xml.
Is there an alternative for applications which are annotation driven and do not use web.xml?
Thanks

You should just be able to add this to your pom file.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
This dependency is normally commented out if you have created your project from the Jersey maven archetype.
com.sun.jersey.api.json.POJOMappingFeature is only for version 1.* of Jersey. The package name changed from com.sun.* to org.glassfish.* from version 1 to 2 of Jersey.

Related

spring boot application deployed but i am getting 404 error even after all setups done [duplicate]

TL;DR: I have a Spring MVC Hello, World! application that works on Tomcat 9. The same application on Tomcat 10 gives a 404 error for web request mappings.
The Problem
When deploying a Spring MVC 5 Hello, World! application to Tomcat 10, the application gives a 404 error for web request mappings. The same Hello, World! application works on Tomcat 9. It displays the Hello, World! message on Tomcat 9.
What I Expected
I expected the application to display the Hello, World! message on Tomcat 10.
Environment
MS Windows 10
Tomcat 10.0.2
Spring MVC 5.3.3
Research I Performed
I researched in the Spring Reference Manual, Section on Web Servlet. I also tested Spring MVC Tutorials online. These tutorials worked on Tomcat 9. However, the same tutorials failed on Tomcat 10. I also performed Google search on Tomcat 10. I saw references to Jakarta EE, but I am not sure if this is the source of the issue. Java EE 8 and Jakarta EE 8 are backwards compatible.
How to Reproduce
I created a very basic Hello, World! project to test this out. Here is the code that I'm using for the project.
File pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.spring</groupId>
<artifactId>example-spring</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<properties>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>
File ProjectInitializer.java
package com.example;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ProjectInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { PureJavaConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
}
File PureJavaConfig.java
package com.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.example")
public class PureJavaConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setSuffix(".jsp");
resolver.setPrefix("/WEB-INF/jsp/");
return resolver;
}
}
File TutorialController.java
package com.example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class TutorialController {
#GetMapping("/")
public String home() {
return "home";
}
}
File home.jsp
<html>
<body>Hello, World! of Spring! <%= java.time.LocalDateTime.now() %></body>
</html>
This project runs okay on Tomcat 9. It displays the Hello, World! message. However, when I run on Tomcat 10, I get a 404 error message.
TL;DR: Spring MVC 5 does not run on Tomcat 10 because of the package renaming from javax.* to jakarta.*.
After further research, I was able to find the answer to my question. Spring MVC 5 does not work on Tomcat 10. This is because Tomcat 10 is based on Jakarta EE 9 where package names for APIs have changed from javax.* to jakarta.*.
Tomcat 10 mentioned this on the download webpage:
Users of Tomcat 10 onwards should be aware that, as a result of the
move from Java EE to Jakarta EE as part of the transfer of Java EE to
the Eclipse Foundation, the primary package for all implemented APIs
has changed from javax.* to jakarta.*. This will almost certainly
require code changes to enable applications to migrate from Tomcat 9
and earlier to Tomcat 10 and later.
For Spring MVC 5, the Spring MVC DispatcherServlet has a dependency on the javax.servlet.* package namespace. This is using the Java EE 8 javax package naming. Since Tomcat 10 is based on Jakarta EE 9, the packages for javax naming are not supported. This explains why Spring MVC 5 does not work on Tomcat 10.
There are GitHub issues filed against the Spring Framework regarding this:
Spring core 5 is not starting on Tomcat 10
Support for Jakarta EE 9 (annotations and interfaces in jakarta.* namespace)
In my case, instead of migrating to Tomcat 10, I will stay on Tomcat 9 until the Spring framework is upgraded to Jakarta EE 9.

Caused by: java.lang.ClassNotFoundException: org.h2.Driver

Caused by: java.lang.ClassNotFoundException: org.h2.Driver cannot be found by {my Component}.
What is the possible mistake that I would have made?
Have added the following dependency :
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency>
And the class loader will be like this:
Class.forName("org.h2.Driver");
And I try to import the package for building an OSGi bundle as below:
com.h2database.*; version ="[1.0.0,3.0.0]"
I was struggling for so long and your help would be appreciated!
I think you're importing the wrong package: You are importing package com.h2database, but you're using the driver in package "org.h2"
Also, I think you have to import a package without the ".*" at the end
Never use Class.forName(String) in OSGi.
Always provide a classloader if you want to load classes dynamically. E.g.:
this.getClass().getClassLoader().loadClass(xxx) uses the same class loader that loaded the type of the current object.
MyType.class.getClassLoader.loadClass(xxx) uses the same class loader that loaded MyType
Class.forName(String, true, classLoader)
Also note, that you import the wrong package.

Spring Boot-Unable to connect to JSP in spring boot maven project error (type=Not Found, status=404) is thrown

I created simple spring boot project to show a jsp output,but error is displayed inspite of following below steps how do i overcome this issue
ERROR is:
There was an unexpected error (type=Not Found, status=404).
/WEB-INF/jsp/products.jsp
Dependencies added are:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
I have all my controllers under same folder
Controller Code
package CRUDRdsapp.CRUDRdsapp;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class ProductController {
#RequestMapping("/welcome")
public String welcome(){
return "products";
}
}
properties added to application properties file are:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
I placed jsp in webapp/WEB-INF/jsp folder:
prpject folder structure

Import Spring-Boot Configuration class (Project A) in ext-spring.xml (Project B)

I have a project A that use SPRING BOOT and it have this ConfigurationClass for this
package it.blabla.common.couponing.configuration;
#Configuration
#ComponentScan(basePackages = { "it.***", "it.**" })
#EnableAutoConfiguration
#PropertySource("classpath:couponing-${application.environment}.properties")
public class CouponingConfiguration {
#Autowired
private Environment env;
..
I have Spring Project B without Spring-Boot that IMPORT and USE Project A.
How can i import Spring-Boot configuration in project B?
For example, for others project that using spring xml file I use this instruction in ext-spring.xml project B
<import resource="classpath:META-INF/projectA-spring.xml"/>
I try import spring Boot Configuration using
<bean class="it.blabla.common.couponing.configuration.CouponingConfiguration "></bean>
but receive this error
LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: Root WebApplicationContext
What is the best way for do that? Is possible? Can I use springBoot Project in a non-spring-boot project ?
It was e dependency version problem
I imported configuration:
<bean class="it.blabla.common.couponing.configuration.CouponingDatabaseConfiguration"></bean>
and change this versions
<spring.version>4.3.2.RELEASE</spring.version>
<spring.data.version>1.10.2.RELEASE</spring.data.version>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.version}</version>
</dependency>
Now it works and I haven't console errors

Cannot get spring-data-neo4j to connect to remote database

I am building a small proof of concept Spring Boot app which is supposed to connect to a Neo4j instance and perform some basic operations on a couple of different Nodes. If I have the main application class wired to create an embedded Neo4j service using the following code, everything works fine. (this is based on the working example https://spring.io/guides/gs/accessing-neo4j-data-rest/)
#Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase("target/hello.db");
}
This is the only code sample I can find though for connecting to a Neo4j server from spring boot. If I try connecting to a remote server, the code fails to start with the exception at the end of this question. Our plan is to run a centralized Neo4j instance which is obviously a common production requirement.
How can or should I configure my bean to connect to a remote Neo4j database or is anyone aware of a solid working example of this kind of setup?
Thanks!
My pom.xml includes the following:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-rest</artifactId>
<version>3.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
I have seen several references to using SpringCypherRestGraphDatabase so I have this being handled in my Main application class is as follows:
import org.neo4j.graphdb.GraphDatabaseService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.rest.SpringCypherRestGraphDatabase;
#SpringBootApplication
#EnableNeo4jRepositories
public class ProfileServiceApplication extends Neo4jConfiguration {
public ProfileServiceApplication() {
setBasePackage("profile");
}
#Bean
public GraphDatabaseService graphDatabaseService() {
return new SpringCypherRestGraphDatabase("http://localhost:7474/db/data/","neo4j","password");
}
public static void main(String[] args) {
SpringApplication.run(ProfileServiceApplication.class, args);
}
}
When I try to run with this configuration, I get the following error:
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.graphdb.GraphDatabaseService]: Circular reference involving containing bean 'profileServiceApplication' - consider declaring the factory method as static for independence from its containing instance. Factory method 'graphDatabaseService' threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/data/neo4j/core/UpdateableState
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
Please share your application as github-project for testing. Perhaps it is also a dependency issue of the spring-boot-starter? Which boot version are you using??
Perhaps you can check mvn dependency:tree if there is any older version of SDN pulled in and if so, update the neo4-version-property for the spring-boot-starter.
Example application is here:
http://neo4j.com/developer/java/#_using_spring_data_neo4j
and it is also in the docs as you correctly saw:
http://docs.spring.io/spring-data/data-neo4j/docs/3.3.0.RELEASE/reference/html/#using_spring_data_neo4j_as_a_neo4j_server_client
The reference which you are giving doesn't contain Neo4j URL.
Hence Here is Application.properties file to connect to your Neo4j.
spring.data.neo4j.uri=bolt://localhost
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=Your_Password
Start your Neo4j Database as a console application which will run on localhost:7474 port most probably.
command to start:
neo4j console
Also check the dependency. As the latest version work with only
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>

Resources