How to call Java WS client in Grails - java

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()

Related

Integrationtest javaspark

I build a controller in spark java, but do not know how to test it.
The controller class:
public class PdfController {
public PdfController(final Pdf pdf) {
post("/", (req, res) -> {
InputStream stream = new ByteArrayInputStream(req.bodyAsBytes());
PdfState state = pdf.validate(stream);
res.type("application/json");
return JsonUtil.toJson(state);
});
}
}
I build the test boilerplate
public class PdfControllerTest {
#BeforeClass
public static void beforeClass() {
PdfInspector.main(null);
}
#Test(groups = {"fast"})
public void IsPdfContentRequestValid_StreamValidPdfContent_ExpectJsonSuccess() {
}
#AfterClass
public static void afterClass() {
Spark.stop();
}
}
But do not know how to write a test method.
How to write an integration test in spark java?
Download POSTMAN from chrome web store and make changes in your code so that your code could accept data... and also use "maven install" from eclipse to build your project, javaspark framework will call embedded jetty server and will run on that server...
TRY "localhost:4567/" to access your page from POSTMAN and do send some JSON or other input to that code...

Testing Controllers In Play Framework

I am using Play Framework and using Java as the language of choice. I have a Controller which makes a REST call to an external service. I intend to mock the external service, so that I can test the functionality of my controller. To achieve this, I have created my test cases as shown below (sample). I am embedding a server within my test to mock the external service.
public class SomeControllerTest extends WithApplication {
private static Server SERVER;
#Override
protected Application provideApplication() {
final Module testModule = new AbstractModule() {
#Override
public void configure() {
bind(AppDao.class).to(MockAppDaoImpl.class);
}
};
return new GuiceApplicationBuilder().in(Environment.simple()).overrides(testModule).build();
}
#BeforeClass
public static void setup() {
Router router = new RoutingDsl()
.POST("/api/users")
.routeTo(() -> created())
.build();
SERVER = Server.forRouter(router, 33373);
PORT = SERVER.httpPort();
}
#AfterClass
public static void tearDown() {
SERVER.stop();
}
#Test
public void testCreateUser() {
ObjectNode obj = Json.newObject();
obj.put("name", "John Doe");
obj.put("email", "john.doe#example.com");
Http.RequestBuilder request = new Http.RequestBuilder()
.method(POST)
.bodyJson(obj)
.uri("/some/url/here");
Result result = route(request);
assertEquals(ERR_MSG_STATUS_CODE, CREATED, result.status());
assertEquals(ERR_MSG_CONTENT_TYPE, Http.MimeTypes.JSON, result.contentType().get());
}
My expectation is that when I run the test, the mock server would run and based on my application's test configuration, my controller will make a call to the mock server which would return 201 and my test case would pass.
But, this doesn't happen, because as soon as setup() method completes, the mock server is killed, and my controller cannot make a call to it.
What am I doing wrong here?
Testing of controller should be rather done by inheritance from WithApplication
public class TestController extends WithApplication {
#Test
public void testSomething() {
Helpers.running(Helpers.fakeApplication(), () -> {
// put test stuff
// put asserts
});
}
}
In order to test a controller method use Helpers.fakeRequest and reverse routing.
The external service may be just mocked with mockito or other mocking framework you like.
You can find here several examples.

Showing Grizzly exceptions in Eclipse console

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

How should I mock Jersey HTTP-client requests?

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

MIMEParsingException in REST

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

Categories