I have a question about MIMEParsingException.
I use Java EE 6 with NetBeans 6.8. I write a simple REST web service in Java to print "hello world", it runs well.
Then I write a REST web services client (Java Main Class) to test REST :
public class HelloWorldClient {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
String xml = service.path("resources").path("helloworld").accept(MediaType.TEXT_XML).get(String.class);
System.out.println(xml);
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/HelloWorldApplication").build();
}
}
It complies without error, but when I run it, it throws MIMEParsingException at this line :
Client client = Client.create(config);
Exception in thread "main" com.sun.jersey.spi.service.ServiceConfigurationError: jersey-client-components: A dependent class, org/jvnet/mimepull/MIMEParsingException, of the class com.sun.jersey.multipart.impl.MultiPartReader implementing the provider class java.lang.Object is not found. The provider implementation is ignored.
at com.sun.jersey.spi.service.ServiceFinder.fail(ServiceFinder.java:388)
at com.sun.jersey.spi.service.ServiceFinder.access$200(ServiceFinder.java:144)
at com.sun.jersey.spi.service.ServiceFinder$LazyClassIterator.next(ServiceFinder.java:595)
at com.sun.jersey.spi.service.ServiceFinder$LazyClassIterator.next(ServiceFinder.java:571)
at com.sun.jersey.spi.service.ServiceFinder.toClassArray(ServiceFinder.java:374)
at com.sun.jersey.api.client.Client.(Client.java:167)
at com.sun.jersey.api.client.Client.(Client.java:139)
at com.sun.jersey.api.client.Client.create(Client.java:466)
at helloWorld.client.HelloWorldClient.main(HelloWorldClient.java:29)
Who can resolve this problem ? Thanks a lot.
You're missing a dependency:
Non-maven developers require:
mimepull.jar,
jersey-multipart.jar
Related
Recently I've started developing with Java, and was introduced to the Dropwizard framework. But what's got me stumped here, is that I'm not getting any resources online which would explain how to set it up a Jetty server with my Dropwizard application (I previously made use of Apache Tomcat, but was told that Jetty is a much better alternative). Also, what is use of Embedded-jetty in it?
(I realize that the nature of the question is rather amateurish, but I couldn't come across any online resource that would explain this succinctly :( ...)
The application part:
import io.dropwizard.Application;
public class App extends Application<AppConfiguration> {
public static void main(String[] args) throws Exception {
new App().run(args);
}
#Override
public void run(AppConfiguration configuration, Environment environment) {
final AppResource resource = new AppResource();
environment.jersey().register(resource);
}
The resource with a dummy API to get version:
public class AppResource {
#GET
#UnitOfWork(readOnly = true)
#Path("/version")
#ApiOperation(
value = "Retrieve the version")
#Timed
public Version getVersion() {
return new Version();
}
}
I am following the instructions in the official documentation of Play framework 2.5.x to Java Websockets, I created a controller with this function
public static LegacyWebSocket<String> socket() {
return WebSocket.withActor(MyWebSocketActor::props);
}
And an Actor class MyWebSocketActor:
public class MyWebSocketActor extends UntypedActor {
public static Props props(ActorRef out) {
return Props.create(MyWebSocketActor.class, out);
}
private final ActorRef out;
public MyWebSocketActor(ActorRef out) {
this.out = out;
}
public void onReceive(Object message) throws Exception {
if (message instanceof String) {
out.tell("I received your message: " + message, self());
}
}
}
Then the app is started I try to connect at ws://localhost:9000 as is written in the official documentation:
Tip: You can test your WebSocket controller on
https://www.websocket.org/echo.html. Just set the location to
ws://localhost:9000.
But the web socket seems unreachable, how can I test it?
Thanks
In order to handle WebSocket connections, you also have to add a route in your routes file.
GET /ws controllers.Application.socket()
Then your WebSocket endpoint will be ws://localhost:9000/ws - use it for testing with the echo service.
Finally with the help of Anton I solved it!
First: remove static from socket() method
public LegacyWebSocket<String> socket() {
return WebSocket.withActor(MyWebSocketActor::props);
}
Then add an endpoint in routes file for the socket() method
GET /ws controllers.HomeController.socket()
At this point you have to start the application with SSL/TLS in this way, for example:
activator run -Dhttps.port=9443
In websocket.org/echo.html insert wss://localhost:9443/ws in Location field and it connects to websocket!
Furthermore if I visit https://localhost:9443/ws I continue to obtain the message
Upgrade to WebSocket required
When launching a simple REST interface with Eclipse using the jersey-container-grizzly2-http Maven dependency version 2.13, I do not get any exceptions shown after triggering errors in the browser. Other log output gets shown in the console just fine, but Exceptions just get swallowed.
I created an Exception handler which is neither instantiated or called:
package mypackage.rest;
#Provider
class ExceptionHandler implements ExceptionMapper<Throwable>
{
#Override public Response toResponse(Throwable t)
{
System.out.println("toResponse called");
t.printStackTrace();
return Response.status(Status.BAD_REQUEST).entity(t.getMessage()).build();
}
}
The Grizzly Server construction:
package mypackage.rest;
public class GrizzlyHttpUtil
{
public static final URI baseURI = UriBuilder.fromUri("http://localhost/").port(10010).build();
public static HttpServer startThisServer()
{
ResourceConfig resCon = new ResourceConfig().packages("mypackage.rest");
return server = GrizzlyHttpServerFactory.createHttpServer(baseURI, resCon);
}
}
The REST API class
package mypackage.rest;
#Path("")
public class Rest
{
#GET #Path("datasets") #Produces(MediaType.TEXT_HTML)
public static String datasets()
{
throw new RuntimeException();
}
}
Update
I got it to work with resCon.register(ExceptionHandler.class);. Why is that necessary? Why does ResourceConfig().packages(...) not handle this on its own?
I've just had to solve the same problem. Here is my initialization code that convinces Grizzly HTTP server to display errors: http://source.apidesign.org/hg/bck2brwsr/rev/18ae4fbcfb87
Logger l = Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler");
l.setLevel(Level.FINE);
l.setUseParentHandlers(false);
ConsoleHandler ch = new ConsoleHandler();
ch.setLevel(Level.ALL);
l.addHandler(ch);
I am using Grizzly 2.3.3
I set up WS server using this tutorial http://java.dzone.com/articles/jax-ws-hello-world (that Java client works correctly, of course) and trying to call the client in Grails project like this:
Client.java
public class Client {
public static void main(String[] args) {
GreetingImplService service = new GreetingImplService();
Greeting greeting = service.getGreetingImplPort();
System.out.println("------->> Call Started");
System.out.println(greeting.sayHello("Ali"));
System.out.println("------->> Call Ended");
}
}
TestController.groovy
class TestController {
def index() {
Client.main(null);
}
}
In case of Grails, exception is thrown on this command:
Greeting greeting = service.getGreetingImplPort();
full stacktrace is here http://pastebin.ca/2316018
how to fix it?
Install the WSClient plugin for Grails, then write:
def proxy = webService.getClient(wsdlURL)
def result = proxy.getGreetingImplPort()
This is the class I'm trying to test (it calculates the size of HTTP page):
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.*;
public class Loader {
private Client client;
public Loader(Client c) {
this.client = c;
}
public Integer getLength(URI uri) throws Exception {
return c.resource(uri) // returns WebResource
.accept(MediaType.APPLICATION_XML) // returns WebResource.Builder
.get(String.class) // returns String
.length();
}
}
Of course it just an example, not a real-life solution. Now I'm trying to test this class:
public class LoaderTest {
#Test public void shouldCalculateLength() throws Exception {
String mockPage = "test page"; // length is 9
Client mockedClient = /* ??? */;
Loader mockedLoader = new Loader(mockedClient);
assertEquals(
mockPage.length(),
mockedLoader.getLength(new URI("http://example.com"))
);
}
}
How should I mock com.sun.jersey.api.client.Client class? I'm trying to use Mockito, but any other framework will be OK, since I'm a newbie here..
Not really related to your question, but may come in handy later, is the Jersey Test Framework. Check out these blog entries by one of the Jersey contributors;
http://blogs.oracle.com/naresh/entry/jersey_test_framework_makes_it
http://blogs.oracle.com/naresh/entry/jersey_test_framework_re_visited
Back on topic, to test your Loader class you can simply instantiate it with a Client obtained from Client.create(). If you are using Maven you can create a dummy test endpoint (in src/test/java) to call and the Jersey Test framework will load it in Jetty.
You example is really complex, i wasnt able to run it with newest version of jersey, so i created those classes and here is how i mock it with EasyMock.
String mockPage = "test page"; // length is 9
RequestBuilder requestBuilderMock = createNiceControl().createMock(RequestBuilder.class);
expect(requestBuilderMock.get((Class < String >) anyObject())).andReturn("12345678").anyTimes();
replay(requestBuilderMock);
WebResource webResourcemock = createNiceControl().createMock(WebResource.class);
expect(webResourcemock.accept((String[]) anyObject())).andReturn(requestBuilderMock).anyTimes();
replay(webResourcemock);
Client clientMock = createNiceControl().createMock(Client.class);
expect(clientMock.resource((URI) anyObject())).andReturn(webResourcemock).anyTimes();
replay(clientMock);
Loader mockedLoader = new Loader(clientMock);
assertEquals((Integer) mockPage.length(), mockedLoader.getLength(new URI("http://example.com")));
If any of classes that you are trying to mock doesnt have default constructor then you should use
http://easymock.org/api/easymock/3.0/org/easymock/IMockBuilder.html#withConstructor%28java.lang.Class...%29