SEVERE: Context [/SpringMVCPractice1] startup failed due to previous errors - spring-mvc

I am practicing Spring MVC web application (Spring4) using Java config files rather than XML config files. the Tomcat Server is not able to start the web application. during starting Tomcat I've received the following error in the console , but there is not previous message on the console
SEVERE: Context [/SpringMVCPractice1] startup failed due to previous errors
I don't have web.xml file and dispatcher-servlet.xml as it is java file config
here are whole log from console and whole source code
Reference of practice : Spring in Action, 4th Edition: Covers Spring 4
Log:
Mar 05, 2015 4:59:41 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.7.0_80\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\Program Files (x86)\Java\jre7\bin\javaw.exe;C:\apache-maven-3.2.3\bin;.
Mar 05, 2015 4:59:42 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:SpringMVCPractice1' did not find a matching property.
Mar 05, 2015 4:59:42 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Mar 05, 2015 4:59:42 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Mar 05, 2015 4:59:42 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1234 ms
Mar 05, 2015 4:59:42 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Mar 05, 2015 4:59:42 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.37
Mar 05, 2015 4:59:46 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/SpringMVCPractice1] startup failed due to previous errors
Mar 05, 2015 4:59:46 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Mar 05, 2015 4:59:46 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Mar 05, 2015 4:59:46 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 4073 ms
WebConfig.java :
package spittr.config;
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.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("spitter.web")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling( DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
}
SpittrWebAppInitializer.java :
package spittr.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer ;
public class SpittrWebAppInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected String[] getServletMappings(){
return new String[] { "/" };
}
#Override
protected Class[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses(){
return new Class<?>[] { WebConfig.class };
}
}
RootConfig.java :
package spittr.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages = { "spitter" }, excludeFilters = { #Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })
public class RootConfig {
}
HomeController.java :
package spittr.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
import static org.springframework.web.bind.annotation.RequestMethod.*;
#Controller
public class HomeController {
#RequestMapping(value = "/", method = GET)
public String home() {
return "home";
}
}
Under folder ...\WEB-INF\views\
home.jsp :
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Spittr</title>
<link rel="stylesheet"
type="text/css"
href="<c:url value="/resources/style.css" />" >
</head>
<body>
<h1>Welcome to Spittr</h1>
Spittles |
Register
</body>
</html>

Related

Why do I get a constructor exception on JavaFX?

Based on some online reference, I try to bring up a JavaFX applicaion with the simple following code.
#SpringBootApplication
public class DesktopApplication {
public static void main(String[] args) {
Application.launch(ChartApplication.class, args);
}
}
public class ChartApplication extends Application {
#Override
public void start(Stage stage) {
}
}
I can't start up the app due to an error
me#USAUS desktop % java -jar target/desktop-0.0.1-SNAPSHOT.jar
Aug 18, 2022 4:10:10 PM com.sun.javafx.application.PlatformImpl startup
WARNING: Unsupported JavaFX configuration: classes were loaded from 'unnamed module #69ec05a2'
Aug 18, 2022 4:10:15 PM com.sun.glass.ui.mac.MacApplication ambda$waitForReactivation$6
WARNING: Timeout while waiting for app reactivation
Exception in Application constructor
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:108)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:58)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:65)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class com.example.desktop.ChartApplication
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:891)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.NoSuchMethodException: com.example.desktop.ChartApplication.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3585)
at java.base/java.lang.Class.getConstructor(Class.java:2271)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:802)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
I don't get why the class can't get constructed.
I use Java 17 and try various version of OpenJfx (versions from 18.0.2, 19 EA and 20 EA), and Spring Boot (2.7.3, 3.0.0-M4) with the same exception.
The cause is that JavaFX is removed from JDK after Java 11.

Java EE 7 and Wildfly 10.1.0 - IllegalStateException: EJBCLIENT000025

I created following EJB-Module:
1) My Remote interface
package calculator.beans;
import javax.ejb.Remote;
#Remote
public interface CalculatorRemote {
public int addNum(int num1, int num2);
}
2) A bean which implements the interface
package calculator.beans;
import javax.ejb.Stateless;
#Stateless
public class CalculatorBean implements CalculatorRemote {
#Override
public int addNum(int num1, int num2) {
return num1 + num2;
}
}
3) Next I created a property-file 'jboss-ejb-client.properties'
endpoint.name=client-endpoint
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=127.0.0.1
remote.connection.default.port = 8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.username=appuser
remote.connection.default.password=apppassword
After the deployment to wildfly everything was fine. I get following Information:
INFO [org.jboss.as.ejb3.deployment] (MSC service thread 1-4) WFLYEJB0473: JNDI bindings for session bean named 'CalculatorBean' in deployment unit 'deployment "CalculatorEJB.jar"' are as follows:
java:global/CalculatorEJB/CalculatorBean!calculator.beans.CalculatorRemote
java:app/CalculatorEJB/CalculatorBean!calculator.beans.CalculatorRemote
java:module/CalculatorBean!calculator.beans.CalculatorRemote
java:jboss/exported/CalculatorEJB/CalculatorBean!calculator.beans.CalculatorRemote
java:global/CalculatorEJB/CalculatorBean
java:app/CalculatorEJB/CalculatorBean
java:module/CalculatorBean
4) Then I created my Java Client
package calculator.client;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import calculator.beans.CalculatorRemote;
public class RemoteRechnerClient {
public static void main(String[] args) {
try {
final Hashtable<String, String> jndiProperties = new Hashtable<>();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context ctx = new InitialContext(jndiProperties);
String crName = CalculatorRemote.class.getName();
CalculatorRemote cr = (CalculatorRemote) ctx.lookup("ejb:CalculatorEJB/beans/CalculatorBean!" + crName);
System.out.println("Result: " + cr.addNum(5, 4));
} catch (NamingException ex) {
ex.printStackTrace();
}
}
}
The code is simple enough. But if I run the Client I get following Error-Message:
Apr 06, 2017 3:30:26 PM org.jboss.ejb.client.EJBClient <clinit>
INFO: JBoss EJB Client version 2.0.1.Final
Apr 06, 2017 3:30:26 PM org.xnio.Xnio <clinit>
INFO: XNIO version 3.3.0.Final
Apr 06, 2017 3:30:26 PM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.3.0.Final
Apr 06, 2017 3:30:26 PM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 4.0.6.Final
Apr 06, 2017 3:30:27 PM org.jboss.ejb.client.remoting.VersionReceiver handleMessage
INFO: EJBCLIENT000017: Received server version 2 and marshalling strategies [river]
Apr 06, 2017 3:30:27 PM org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver associate
INFO: EJBCLIENT000013: Successful version handshake completed for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext#3c0f93f1, receiver=Remoting connection EJB receiver [connection=org.jboss.ejb.client.remoting.ConnectionPool$PooledConnection#31dc339b,channel=jboss.ejb,nodename=john-waynes-macbook-pro]} on channel Channel ID b98547a5 (outbound) of Remoting connection 0c84e8ba to /127.0.0.1:8080
Exception in thread "main" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available for handling [appName:CalculatorEJB, moduleName:beans, distinctName:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#2758fe70
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:749)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:116)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:186)
at org.jboss.ejb.client.EJBInvocationHandler.sendRequestWithPossibleRetries(EJBInvocationHandler.java:253)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:198)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:144)
at com.sun.proxy.$Proxy0.addNum(Unknown Source)
at calculator.client.RemoteRechnerClient.main(RemoteRechnerClient.java:27)
/Users/manhthangd/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I am using Netbeans 8.2, Java EE 7 and Wildfly 10.1.0-Final.
What can I do to solve the problem?
Your JNDI lookup name is incorrect.
You need to use the highlighted portion of:
java:jboss/exported/CalculatorEJB/CalculatorBean!calculator.beans.CalculatorRemote
ie.
CalculatorRemote cr = (CalculatorRemote) ctx.lookup("ejb:CalculatorEJB/CalculatorBean!" + crName);
Where did you get "ejb:CalculatorEJB/beans/CalculatorBean!" from?

Log4J not working properly with spring boot mvc api

I am new to SpringBoot and I am trying to configure the Log4J but i am facing a wired behavior, please help.
This is my project structure:
enter image description here
Below is code of my files:-
Log4J2PropertiesConf:
package Log4J;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Log4J2PropertiesConf {
private static Logger logger = LogManager.getLogger();
public static void main(String[] args) {
logger.info("Started");
TestClass.test("Before");
SpringApplication.run(Log4J2PropertiesConf.class, args);
TestClass.test("After");
}
}
TestClass:
package Log4J;
import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;
public class TestClass {
private static Logger logger = LogManager.getLogger(TestClass.class);
public static void test(String s) {
logger.info("IN Class Test: " + s);
}
}
Testcontroller:
package Log4J.controller;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class Testcontroller {
private static Logger logger = LogManager.getLogger(Testcontroller.class);
#RequestMapping(method = RequestMethod.GET, value = "/Get")
public ResponseEntity<String> GetValue() {
logger.debug("This is a debug message: Test1");
logger.info("This is an info message");
logger.warn("This is a warn message");
logger.error("This is an error message");
logger.fatal("This is a fatal message");
return new ResponseEntity<String>("Reached", HttpStatus.OK);
}
}
Log4J2PropertiesConfTest:
package Log4J;
import org.junit.Test;
public class Log4J2PropertiesConfTest {
#Test
public void testPerformSomeTask() throws Exception {
TestClass.test("from Test");
}
}
log4j2.properties:
name=PropertiesConfig
property.filename = logs
appenders = console, file
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/propertieslogs.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
loggers=file
logger.file.name=Log4J
logger.file.level = debug
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE
logger.file.additivity = false
rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
That is all i am trying, I am using maven and I have all the dependencies added in pom file.
Now when I am running this as Springboot app, I am getting below on console:
[main] INFO org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat started on port(s): 10053 (http)
[main] INFO Log4J.Log4J2PropertiesConf - Started Log4J2PropertiesConf in 2.982 seconds (JVM running for 3.868)
2017-01-04 21:59:13.832 INFO 7544 --- [ main] L.TestClass : **IN Class Test: After**
AND I am getting below in log file at the same time:
[INFO ] 2017-01-04 21:59:10.740 [main] Log4J2PropertiesConf - **Started**
[INFO ] 2017-01-04 21:59:10.742 [main] TestClass - **IN Class Test: Before**
Now if i invoke the GetValue(http:localhost:10053/Get) method, I am getting below on console:
2017-01-04 22:02:18.531 INFO 7544 --- [io-10053-exec-1] L.c.Testcontroller : **This is an info message**
2017-01-04 22:02:18.532 WARN 7544 --- [io-10053-exec-1] L.c.Testcontroller : **This is a warn message**
2017-01-04 22:02:18.532 ERROR 7544 --- [io-10053-exec-1] L.c.Testcontroller : **This is an error message**
2017-01-04 22:02:18.532 FATAL 7544 --- [io-10053-exec-1] L.c.Testcontroller : **This is a fatal message**
AND nothing gets updated in log.
When I run the unit test, i get below in log file:
[INFO ] 2017-01-04 22:03:36.650 [main] TestClass - **IN Class Test: from Test**
So, I am expecting every log entry to go into the log file, not to console. Not sure how it is putting some information to console and some to file, although I have logger.file.additivity = false in my properties file also.
I want to have everything to go into the log file. Please help.

Spring MVC Java Configuration

Hi I am trying to use Spring MVC Java config and Content View resolver.
Files:-
public class WebInitializer implements WebApplicationInitializer {
/*
* (non-Javadoc)
*
* #see
* org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet
* .ServletContext)
*/
#Override
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
ctx.setServletContext(servletContext);
ctx.refresh();
Dynamic servlet = servletContext.addServlet("dispatcher",
new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
servlet.setAsyncSupported(false);
}
}
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.sambhav.mvc.controller" })
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
/*
* #Bean public UrlBasedViewResolver setupViewResolver() {
* UrlBasedViewResolver resolver = new UrlBasedViewResolver();
* resolver.setPrefix("/WEB-INF/jsp/"); resolver.setSuffix(".jsp");
* resolver.setViewClass(TilesView.class); return resolver; }
*/
#Bean
public TilesViewResolver getTilesViewResolver() {
TilesViewResolver tilesViewResolver = new TilesViewResolver();
/*
* tilesViewResolver.setPrefix("/WEB-INF/jsp/");
* tilesViewResolver.setSuffix(".jsp");
*/
tilesViewResolver.setViewClass(TilesView.class);
return tilesViewResolver;
}
#Bean
public TilesConfigurer getTilesConfigurer() {
TilesConfigurer tilesConfigurer = new TilesConfigurer();
tilesConfigurer.setCheckRefresh(true);
tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/tiles.xml" });
return tilesConfigurer;
}
#Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.TEXT_HTML)
.mediaType("json", MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML)
.favorPathExtension(true); // default is true. just for clarity
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/*").addResourceLocations(
"/WEB-INF/css/*");
registry.addResourceHandler("/js/*").addResourceLocations(
"/WEB-INF/js/*");
registry.addResourceHandler("/img/*").addResourceLocations(
"/WEB-INF/img/*");
}
}
When trying to run the app, I don't the dispatcher servlet getting registered - no related info logs appear. Running in debug mode with break point in WebInitializer also indicates that its not getting called.
Jul 12, 2013 5:06:57 PM com.springsource.tcserver.serviceability.rmi.JmxSocketListener init
INFO: Started up JMX registry on 127.0.0.1:6969 in 68 ms
Jul 12, 2013 5:06:57 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 573 ms
Jul 12, 2013 5:06:57 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jul 12, 2013 5:06:57 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: VMware vFabric tc Runtime 2.8.2.RELEASE/7.0.35.B.RELEASE
Jul 12, 2013 5:06:57 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor D:\Installations\sts3.2\vfabric-tc-server-developer-2.8.2.RELEASE\base-instance\conf\Catalina\localhost\spring-mvc-config.xml
Jul 12, 2013 5:06:57 PM org.apache.catalina.startup.SetContextPropertiesRule begin
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:spring-mvc-config' did not find a matching property.
Jul 12, 2013 5:06:57 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory D:\Installations\sts3.2\vfabric-tc-server-developer-2.8.2.RELEASE\base-instance\webapps\manager
Jul 12, 2013 5:06:57 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory D:\Installations\sts3.2\vfabric-tc-server-developer-2.8.2.RELEASE\base-instance\webapps\ROOT
Jul 12, 2013 5:06:57 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Jul 12, 2013 5:06:57 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 311 ms
This results in 404 at / or any other path.
I am wondering what went wrong here.
Thanks for your help.
I know its old question. With newer Spring Boot, it is now far easier to configure any Spring application. Refer Spring Boot starter project here :-
Spring Boot Blog
Possible reasons:
web.xml. I advice you to delete it at all and use servlet-api with version higher than 3.0.
Incorrect #RequestMapping in controllers. Show them, please.
And finally, here you can find good step-by-step guide for base Spring MVC app with java configuration:
http://www.javacodegeeks.com/2013/03/spring-mvc-creation-of-a-simple-controller-with-java-based-config.html

Protocol Buffers MIME problem

Help!
Trying to implement Protocol Buffers via Rest (Jersey), but get this exception.
class com.util.ProtobufMessageBodyReader
class com.util.ProtobufMessageBodyWriter
Jul 6, 2010 3:43:37 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-9102
Jul 6, 2010 3:43:37 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 45485 ms
Jul 6, 2010 3:49:00 PM org.apache.catalina.connector.CoyoteAdapter convertURI
SEVERE: Invalid URI encoding; using HTTP default
Jul 6, 2010 3:49:00 PM com.sun.jersey.spi.container.ContainerRequest getEntity
SEVERE: A message body reader for Java type, class com.example.tutorial.ProfileRequestProto$ProfileRequest, and MIME media type, application/x-protobuf, was not found
I loaded ProtobufMessageBodyReader/Writer in the Apache ContextLoader.
From the log above, it seems Tomcat found the class but it apparent it fails when it reads
#Consumes("application/x-protobuf")
Here is ProtobufMessageBodyReader
#Provider
#Component
#Consumes("application/x-protobuf")
public class ProtobufMessageBodyReader implements MessageBodyReader<Message> {
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Message.class.isAssignableFrom(type);
}
public Message readFrom(Class<Message> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
try {
Method newBuilder = type.getMethod("newBuilder");
GeneratedMessage.Builder<?> builder = (GeneratedMessage.Builder<?>) newBuilder.invoke(type);
return builder.mergeFrom(entityStream).build();
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
#Override
public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2) {
// TODO Auto-generated method stub
return false;
}
And here is ProtobufMessageBodyWriter
#Provider
#Component
#Produces("application/x-protobuf")
public class ProtobufMessageBodyWriter implements MessageBodyWriter<Message> {
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Message.class.isAssignableFrom(type);
}
public long getSize(Message m, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return m.getSerializedSize();
}
public void writeTo(Message m, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String,Object> httpHeaders,OutputStream entityStream) throws IOException, WebApplicationException {
entityStream.write(m.toByteArray());
}
Here is the code from client :
URL url = new URL(URL);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setDoInput(true);
http.setDoOutput(true);
http.setUseCaches(false);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-protobuf");
http.setRequestProperty("Accept", "application/x-protobuf");
DataOutputStream stream = new DataOutputStream(http.getOutputStream ());
if(contentType.equals("application/x-protobuf")) {
ProfileRequest.Builder profile = ProfileRequest.newBuilder();
profile.setName("John");
profile.setId("123");
profile.build().writeTo(http.getOutputStream());
}
stream.flush();
stream.close();
And here is the code from server
#POST
#Consumes("application/x-protobuf")
public byte[] processProtoRequest(ProfileRequest protoRequest) {
byte[] result = null;
ProfileRequest.Builder profile = ProfileRequest.newBuilder();
profile.mergeFrom(protoRequest);
result = getProfileProtoResponse(profile);
}catch(Exception e){
}
return result;
}
I cannot figure out what is the problem.
Is there anything with Jersey config? Or something is wrong when I sent protocol request via HTTP?
Any help will be appreciate it.
Thanks
You mostly nailed the issue yourself already I think:
and MIME media type, application/x-protobuf, was not found
[...]
From the log above, it seems Tomcat found the class but it apparent it fails when it reads
#Consumes("application/x-protobuf")
The media types supported by Jersey (or rather JSR-311/JAX-RS) out of the box are defined in class MediaType. To resolve your issue it might be enough to define an appropriate media type for application/x-protobuf, see thread [Jersey] MediaType-s? for a discussion and samples regarding this.
I just met the same problem on my maven+jersey+protobuf project,and I am using tomcat 6. to me the problems is that the Provider Class the tomcat hasn't found.
After I solve this problem the tomcat 6.0 shows like this :
Deploying configuration descriptor jerseydemo2.xml
一月 26, 2015 11:13:41 上午 com.sun.jersey.api.core.WebAppResourceConfig init
信息: Scanning for root resource and provider classes in the Web app resource paths:
/WEB-INF/lib
/WEB-INF/classes
一月 26, 2015 11:13:41 上午 com.sun.jersey.api.core.ScanningResourceConfig logClasses
信息: Root resource classes found:
class sample.hello.resources.AddressBookResource
一月 26, 2015 11:13:41 上午 com.sun.jersey.api.core.ScanningResourceConfig logClasses
信息: Provider classes found:
class sample.pb.ProtobufMessageBodyReader
class sample.pb.ProtobufMessageBodyWriter
一月 26, 2015 11:13:41 上午 com.sun.jersey.server.impl.application.WebApplicationImpl initiate
信息: Initiating Jersey application, version 'Jersey: 1.2-SNAPSHOT 01/27/2010 01:47 AM'
before it showed the Provider classes not found.
my problems is that the web.xml file has set the specific path for the tomcat to find all the resouces. now I have changed it like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
hope it helps you !

Resources