GeoTools JTS orthodromicDistance throws exception for latitude being out of range - geotools

I am trying to get geotools to tell me the distance between two points. I am providing the points in degrees, and I want to get back the distance in meters. I followed this web page for instruction:
http://docs.geotools.org/stable/userguide/library/api/jts.html
Unfortunately when I run it, an exception is thrown because it says my latitude is out of range.
Here is my code:
public double measureDistanceInMeters(double[] coord1, double[] coord2) {
System.out.println("latitude: "+coord1[0]+", longitude: "+coord1[1]);
System.out.println("latitude: "+coord2[0]+", longitude: "+coord2[1]);
CoordinateReferenceSystem crs = DefaultGeocentricCRS.CARTESIAN;
// latitude first, longitude second.
Coordinate start = new Coordinate(coord1[0],coord1[1]);
Coordinate end = new Coordinate(coord2[0],coord2[1]);
double distance = -1;
try {
distance = JTS.orthodromicDistance(start, end, crs);
} catch (TransformException e1) {
e1.printStackTrace();
}
return distance;
When I run it, the console prints this:
latitude: 38.8951, longitude: -77.0367
latitude: 40.7127, longitude: -74.0059
JUnit fails and here is the stack trace:
java.lang.IllegalArgumentException: Latitude �N is out of range (±90°).
at org.geotools.referencing.GeodeticCalculator.checkLatitude(GeodeticCalculator.java:389)
at org.geotools.referencing.GeodeticCalculator.setStartingGeographicPoint(GeodeticCalculator.java:550)
at org.geotools.referencing.GeodeticCalculator.setStartingPosition(GeodeticCalculator.java:591)
at org.geotools.geometry.jts.JTS.orthodromicDistance(JTS.java:635)
at fungle.funfinder.data.geo.GeoToolsRuler.measureDistanceInMeters(GeoToolsRuler.java:49)
at fungle.funfinder.data.geo.GeoRulerBase.getDistance(GeoRulerBase.java:15)
at fungle.funfinder.data.geo.GeoToolsRulerTest.test(GeoToolsRulerTest.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
So I think I am misunderstanding something here. Geotools is huge, and even though it has documentation, it's pretty hard to find the documentation you're looking for because it's so huge and complicated.
I am guessing that I am using the wrong coordinate reference system here, or passing as an arg where I should not be. I don't know what I'm doing wrong. Please help.

You are using the wrong coordinate system, essentially you have told JTS that your coordinates need to be converted to lat/long and then used so they go out of range.
By changing your code to include:
CoordinateReferenceSystem crs = null;
try {
crs = CRS.decode("epsg:4326");
} catch (NoSuchAuthorityCodeException e) {
e.printStackTrace();
} catch (FactoryException e) {
e.printStackTrace();
}
I get the answer 328739.66 m or 328Km which sounds about right (if it isn't then you may need to swap the latitude and longitude values round).
You will also need to add
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>${geotools.version}</version>
</dependency>
to your pom.xml file or the definition of the coordinate system won't be found.

Related

Easymock with Powermock error

I am using Easymock with Powermock. When I try to test, this is the error I get.
java.lang.RuntimeException: Invoking the beforeTestMethod method on PowerMock test listener org.powermock.api.extension.listener.AnnotationEnabler#959a1da3 failed.
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:95)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:298)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:288)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:208)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:121)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:123)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class java.lang.String
at org.easymock.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at org.easymock.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.easymock.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at org.easymock.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.easymock.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at org.easymock.internal.ClassProxyFactory.createProxy(ClassProxyFactory.java:175)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:113)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:98)
at org.easymock.EasyMock.mock(EasyMock.java:128)
at org.easymock.EasyMock.createMock(EasyMock.java:259)
at org.easymock.internal.Injector.createMocksForAnnotations(Injector.java:130)
at org.easymock.internal.Injector.injectMocks(Injector.java:66)
at org.easymock.EasyMockSupport.injectMocks(EasyMockSupport.java:528)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1899)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:801)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:781)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:466)
at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:71)
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:93)
... 24 more
And my class looks like this.
public String renameOrDeleteDirectory(String Directory, String dirExtn, (short) x){
File workDir = new File(Directory);
String OrigDir = null;
File origDir =null;
boolean renamed = false;
try {
if (null != Directory && Directory.length() > 0 ) {
if(new File(Directory).list().length == 0){
new File(Directory).delete();
}
My test case is like this...
#RunWith(PowerMockRunner.class)
#PrepareForTest(value={Utilities.class, File.class})
public class dirTest1 {
#Test
public void testRenameOrDeleteDirectory1() throws Exception {
mockStatic(File.class);
expectNew(File.class, "C:\\Users\\Desktop\\Docs\\Docs2017_03_07_14_docready").andReturn(workDir);
expect(workDir.list().length == 0).andReturn(true);
expect(workDir.delete()).andReturn(true);
// expect(null != Directory && Directory.length() > 0).andReturn(true);
// expect(new File(Directory).list().length == 0).andReturn(true);
// expect(new File(Directory).delete()).andReturn(true);
PowerMock.replay(File.class, workDir);
Utilities utilities = new Utilities();
utilities.renameOrDeleteDirectory("C:\\Users\\Desktop\\Docs\\Docs2017_03_07_14_docready", "_Ready", (short) 0);
PowerMock.verify(File.class, workDir);
}
}
Hint: your real problem is that you are using new all over the place within your production code. That simply creates hard to test code. And thus you end up looking for PowerMock.
Alternatively, you could create a simple
class FileFactory {
File getFileFor(String fileName) { ...
and use that as field within your class. Now, when you need a File for a certain string, you use that FileFactory instance.
The really nice thing here: that FileFactory can be mocked easily.
So instead of needing PowerMock and all its quirks, you could
improve your design
do full unit-testing ... just with frameworks like EasyMock or Mockito
I solved this error.
It was caused because I was mocking a string along with other mocks.

PowerMockito throwing exception when mocking static method of an enum and using that enum object inside a switch statement

I have a enum MyEnum.java which has one static method.
//MyEnum.java
enum MyEnum {
ONE("one"),
TWO("two");
private String value;
MyEnum(String value){
this.value=value;
}
public static MyEnum getMyEnum(String value){
for(MyEnum myEnum : MyEnum.values()){
if(myEnum.value.equalsIgnoreCase(value))
return myEnum;
}
return null;
}
}
I am using PowerMock to mock static methods of this enum. I have included all the necessary conditions like
#Runwith(PowerMockRunner.class)
#PrepareForTest(MyEnum.class)
//Test function
PowerMockito.mockStatic(MyEnum.class);
It all works fine. But if I am using switch method for the object of enum, then it throws the exception.
MyEnum enum = MyEnum.ONE;
switch(enum){
case ONE:
break
}
This code is throwing the following exception.
java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
at javassist.runtime.Desc.getClassObject(Desc.java:43)
at javassist.runtime.Desc.getClazz(Desc.java:52)
at com.newshunt.shared.presenters.tests.DummyTest.testStaticMethod(DummyTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.NullPointerException
at com.newshunt.shared.presenters.tests.DummyTest$1.<clinit>(DummyTest.java:26)
... 37 more
Process finished with exit code -1
Even from the logs it is not clear, what is causing this exception to happen? Anybody else encountered similar issues before ?
My recommendation: consider not using PowerMock.
PowerMock looks like the solution to many problems; but rather sooner than later, it can be the cause of much more problems. It breaks coverage, it makes it harder to change the underlying JVM, and so on.
Seriously: if your design can only be tested with PowerMock, this is very often a clear indication that your design is bad. So: focus on reworking your code under test!
In your case: I would start questioning the need of having a static method on an enum. So, in other words: what is the problem you want to address with this code?
But to answer the actual question: you have to understand that enum constants are represented as inner classes themselves. Therefore you have to use the fullyQualifiedName property for #PrepareForTest. See this newer question for an example.

JSON Schema validator not loading

Need a JSON schema validator for user inputs. I'm planning to use https://github.com/fge/json-schema-validator
Here is what I'm trying to do:
static JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
static {
try {
logger.info("Looking for schema");
JsonSchema schema = factory.getJsonSchema(JSONValidator.class
.getClassLoader()
.getResource("schema.json")
.toString());
} catch (ProcessingException e) {
logger.error("Failed to parse JSON Schema. Cannot validate JSON inputs ", e);
}
}
Get this exception even before reading the schema file. Tested it by removing all code and retaining only this line:
static JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
What could be wrong?
java.lang.NoSuchFieldError: WRITE_BIGDECIMAL_AS_PLAIN
at com.github.fge.jackson.JacksonUtils.newMapper(JacksonUtils.java:155)
at com.github.fge.jackson.JacksonUtils.<clinit>(JacksonUtils.java:55)
at com.github.fge.jackson.JsonNodeReader.<init>(JsonNodeReader.java:82)
at com.github.fge.jackson.JsonLoader.<clinit>(JsonLoader.java:50)
at com.github.fge.jsonschema.SchemaVersion.<init>(SchemaVersion.java:63)
at com.github.fge.jsonschema.SchemaVersion.<clinit>(SchemaVersion.java:44)
at com.github.fge.jsonschema.core.load.configuration.LoadingConfigurationBuilder.<init>(LoadingConfigurationBuilder.java:117)
at com.github.fge.jsonschema.core.load.configuration.LoadingConfiguration.byDefault(LoadingConfiguration.java:151)
at com.github.fge.jsonschema.main.JsonSchemaFactoryBuilder.<init>(JsonSchemaFactoryBuilder.java:67)
at com.github.fge.jsonschema.main.JsonSchemaFactory.newBuilder(JsonSchemaFactory.java:123)
at com.github.fge.jsonschema.main.JsonSchemaFactory.byDefault(JsonSchemaFactory.java:113)
at com.intuit.mumble.validator.JSONValidator.<clinit>(JSONValidator.java:29)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I know that something this JSON Schema Validator expecting in Jackson is not available.
But would like to know if you have encountered this issue with the version that you've used and resolved it already.
json.schema.validator.version 2.2.5
jackson2.version 2.1.0
Fixed by upgrading jackson version to 2.3.2

Message body writer error while doing POST operation with JSON payload using Jersey Client

e I am trying to do a POST operation with JSON payload for REST service using Jersey Client in JUnit .
Here is what I have done:
Resource Class
#Path("/Users")
#Component
public class UserResource{
#POST
#Path("register")
#Consumes({MediaType.APPLICATION_JSON})
#Produces(MediaType.APPLICATION_JSON)
public String registerUser(RegisterRequestJSON requestJson)
{
User user = userManager.getUserInformationByEmail(email);
UserInfoJSON userInfoJSON = new UserInfoJSON();
userInfoJSON.copyFromUserBean(user);
GoodResponseObject gro = new GoodResponseObject(Status.OK.getStatusCode(), Status.OK.getReasonPhrase(), userInfoJSON);
try {
return Formatter.getAsJson(gro, true);
} catch (Exception e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(e).build());
}
}
}
Resource Test
String registerUserUrl = "http://localhost:9998/Users/Path";
JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("accessToken", userAccessToken );
inputJsonObj.put("accessTokenType", "example" );
ClientConfig clientConfigRegisterUser = new DefaultClientConfig();
clientConfigRegisterUser.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,Boolean.TRUE);
Client clientRegisterUser = Client.create(clientConfigRegisterUser);
WebResource registerUser = clientRegisterUser.resource(registerUserUrl);
String registerResponse = registerUser.type(MediaType.APPLICATION_JSON).post(String.class,registerJson);
When I run the test , I get the below error:
com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class com.genie.account.mgmt.json.RegisterRequestJSON, and MIME media type, application/json, was not found
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:151)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:680)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:568)
at com.genie.account.mgmt.resources.UserResourceTest.testGetUserInformationByEmail(UserResourceTest.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class com.genie.account.mgmt.json.RegisterRequestJSON, and MIME media type, application/json, was not found
at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:288)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:213)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
What could be the issue here ?
Your client is not capable of know how to serialize (write) the com.genie.account.mgmt.json.RegisterRequestJSONparameter in order to send it to the REST end point.
By default Jersey try using JAXB for serializing to JSON/XML but your RegisterRequestJSONparameter type should be annotated
Another option is to use custom writers / readers as stated in this answer:
In Jersey, how do I make some methods use the POJO mapping feature and some not?

smartGWT ListGrid JSON issue

I have created a REST API at URL: http://localhost:8888/rest/contacts with this JSON output:
{
"contact": {
"address": [
{
"city":"Shanghai",
"street":"Long Hua Street"
},
{
"city":"Shanghai",
"street":"Dong Quan Street"
}
],
"id": "huangyim",
"name": "Huang Yi Ming"
}
}
I want to print only the id value in a smartGWT ListGrid.
public class ExampleEntry implements EntryPoint {
#Override
public void onModuleLoad() {
DataSource dataSource = new DataSource();
dataSource.setDataFormat(DSDataFormat.JSON);
dataSource.setDataURL("http://localhost:8888/rest/contacts");
dataSource.setRecordXPath("/contact");
DataSourceTextField field = new DataSourceTextField("id", "id");
dataSource.addField(field);
final ListGrid grid = new ListGrid();
grid.setDataSource(dataSource);
grid.setAutoFetchData(true);
grid.draw();
}
}
But it is throwing the following exception:
15:33:12.766 [ERROR] [jerseyexample] 15:33:12.747:XRP2:WARN:RPCManager:xmlHttpRequest.getAllResponseHeaders() returned null
com.smartgwt.client.core.JsObject$SGWT_WARN: 15:33:12.747:XRP2:WARN:RPCManager:xmlHttpRequest.getAllResponseHeaders() returned null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:105)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Unknown Source)
I tried searching google to find a fix but that did not help. Please let me know if anyone knows a solution for this issue.
You just need to change the data url, instead of using an absolute path use a relative one.
change
dataSource.setDataURL("http://localhost:8888/rest/contacts");
to
dataSource.setDataURL("rest/contacts");
This is also neccesary when you'll have to deploy it to a remote server.
I recommend you use a RestDataSource instead of a plain DataSource, it has been designed specificaly for REST services, as you've said you use.
Using a RestDataSource is as simple as using DataSource.
#Override
public void onModuleLoad() {
RestDataSource dataSource = new RestDataSource();
dataSource.setDataFormat(DSDataFormat.JSON);
dataSource.setDataURL("rest/contacts");
dataSource.setRecordXPath("/contact");
DataSourceTextField field = new DataSourceTextField("id", "id");
dataSource.addField(field);
OperationBinding get=new OperationBinding();
get.setOperationType(DSOperationType.FETCH);
dataSource.setOperationBindings(get);
final ListGrid grid = new ListGrid();
grid.setDataSource(dataSource);
grid.setAutoFetchData(true);
grid.draw();
}
You can map each OperationBinding with each http method (GET, POST PUT, DELETE) or whatever suits your REST API.
Cheers!
You can put directly Xpath in the field you want to map
RecordXPath can be specified directly on the DataSource for a simple read-only DataSource only capable of "fetch" operations.
field.setRecordXPath("contact")