RoboSpice throwing okhttp exceptions - java

I use RoboSpice-Retrofit for calling my server REST api which has been working without problems until a few days ago when every single call now throws an exception, Example:
D/Retrofit: java.lang.NoSuchMethodError: No direct method <init>(Lcom/squareup/okhttp/OkHttpClient;Lcom/squareup/okhttp/Request;ZZZLcom/squareup/okhttp/Connection;Lcom/squareup/okhttp/internal/http/RouteSelector;Lcom/squareup/okhttp/internal/http/RetryableSink;Lcom/squareup/okhttp/Response;)V in class Lcom/squareup/okhttp/internal/http/HttpEngine; or its super classes (declaration of 'com.squareup.okhttp.internal.http.HttpEngine' appears in /data/app/com.company.app.customerapp-1/base.apk)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.newHttpEngine(HttpURLConnectionImpl.java:362)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.initHttpEngine(HttpURLConnectionImpl.java:312)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:377)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:497)
at retrofit.client.UrlConnectionClient.readResponse(UrlConnectionClient.java:73)
at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:38)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:321)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
at java.lang.reflect.Proxy.invoke(Proxy.java:393)
at $Proxy0.getTest(Unknown Source)
at com.adoperator.tidyapp.TestActivity$TestRequest.loadDataFromNetwork(TestActivity.java:67)
at com.adoperator.tidyapp.TestActivity$TestRequest.loadDataFromNetwork(TestActivity.java:54)
at com.octo.android.robospice.request.CachedSpiceRequest.loadDataFromNetwork(CachedSpiceRequest.java:48)
at com.octo.android.robospice.request.DefaultRequestRunner.processRequest(DefaultRequestRunner.java:150)
at com.octo.android.robospice.request.DefaultRequestRunner$1.run(DefaultRequestRunner.java:217)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
D/Retrofit: ---- END ERROR
dependencies:
compile 'com.octo.android.robospice:robospice:1.4.14'
compile 'com.octo.android.robospice:robospice-cache:1.4.14'
compile 'com.octo.android.robospice:robospice-retrofit:1.4.14'
I suspect based on the exception that there is something wrong with the compiler, but I just tested on another computer with a fresh install of Java and Android Studio on the same project but same problems still...
This error is driving me crazy...
Anyone knows anything that could be of help? Any help is highly appreciated.
EDIT
MainActivity.java:
SpiceManager spiceManager = new SpiceManager(TestAPIService.class);
protected void onStart() {
super.onStart();
spiceManager.start(this);
spiceManager.execute(new TestRequest(), new RequestListener<ResponseData>() {
...
});
}
TestAPIService.java:
public class TestAPIService extends RetrofitGsonSpiceService {
#Override
public void onCreate() {
super.onCreate();
addRetrofitInterface(TestAPI.class);
}
#Override
protected String getServerUrl() {
return "http://192.168.0.2";
}
}
TestAPI.java:
public interface TestAPI {
#GET("/test")
ResponseData getTest();
}
TestRequest.java:
public class TestRequest extends RetrofitSpiceRequest<ResponseData, TestAPI> {
public TestRequest() {
super(ResponseData.class, TestAPI.class);
}
#Override
public ResponseData loadDataFromNetwork() throws Exception {
ResponseData response;
try {
response = getService().getTest();
}
catch (Exception e) {
e.printStackTrace();
throw e;
}
return response;
}
}

The NoSuchMethodError is happening because HttpURLConnectionImpl is trying to invoke a constructor on HttpEngine that is not defined. Now your project depends on:
com.octo.android.robospice:robospice-retrofit:1.4.14
Which depends on:
com.squareup.retrofit:retrofit:1.6.1
Which depends on both:
com.squareup.okhttp:okhttp:2.0.0
and
com.squareup.okhttp:okhttp-urlconnection:2.0.0
As of version 2.0.0, HttpURLConnectionImpl is in the okhttp-urlconnection module and HttpEngine is in the okhttp module.
The retrofit.client.UrlConnectionClient portion of your stack trace correctly matches retrofit:1.6.1, but the com.squareup.okhttp.internal.huc.HttpURLConnectionImpl portion doesn't match okhttp-urlconnection:2.0.0; it matches okhttp-urlconnection:2.4.0. The constructor that the NoSuchMethodError is complaining about is indeed defined in okhttp:2.4.0, so that means there is a different HttpEngine on your classpath, most likely from a different version of okhttp that is getting pulled in by a transitive dependency. You should be able to fix the problem by specifying the following dependencies:
compile('com.squareup.okhttp:okhttp:2.0.0') {
force = true
}
compile('com.squareup.okhttp:okhttp-urlconnection:2.0.0') {
force = true
}
If that doesn't work for whatever reason, the solution to your problem will still be to get your versions of okhttp and okhttp-urlconnection synced up and at a version that is compatible with your version of retrofit. Declare dependencies similar to above, find the jars that contain HttpURLConnectionImpl and HttpEngine, figure out how they're getting pulled in to your build, and use exclusions to get rid of problematic transitive dependencies.

Related

How to call Java method (custom class) with an interface typed parameter in Nativescript

I'm creating a Nativescript plugin. It includes a custom Android Library (AAR) and I want to use it from the Typescript code. When I run a demo (in device or emulator) I get a TypeError: sender.registerListener is not a function error when calling this registerListener method, which is weird because I'm able to call other methods of the same object.
I think that it could be because I am not implementing properly the interface required as parameter. I think that I can explain it better with code:
Sender.java: the public class I will use in Typescript:
package com.berriart.android.myplugin;
public class Sender {
public static final String TAG = "Sender";
private Context _context = null;
public Sender(Context context) {
_context = context;
}
public void send(final String messagePath, final String messageToSend) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "Send call: " + messagePath + " " + messageToSend);
}
}
public void registerListener(MessageListener listener) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "registerListener");
}
}
// Other code here
}
MessageListener.java: the interface that must be implemented by the registerListener parameter:
package com.berriart.android.myplugin;
public interface MessageListener {
void receive(String messagePath, String messageReceived);
}
This is the Typescript (Nativescript) code of the plugin ( to ):
import * as app from "tns-core-modules/application";
export class WearMessaging {
public static send(messagePath: string, messageToSend: string) {
let sender = new com.berriart.android.myplugin.Sender(app.android.context);
sender.send(messagePath, messageToSend);
}
public static registerListener(receiveCallback: (messagePath: string, messageReceived: string) => void) {
let messageListener = new com.berriart.android.myplugin.MessageListener({
receive: receiveCallback
});
let sender = new com.berriart.android.myplugin.Sender(app.android.context);
sender.registerListener(messageListener);
}
}
If I include WearMessaging.send("/demo", "Hola"); in my nativescript application it compiles and run properly, it's call the Java method successfuly. But if I run:
WearMessaging.registerListener((messagePath: string, messageReceived: string) => {
console.log(messagePath);
console.log(messageReceived);
});
The application stops at run time and throws: TypeError: sender.registerListener is not a function refering to the myplugin.android.ts file.
I'm getting crazy trying to make this work, so, let me know if you have any clue. As I say I think that is because I'm missing something when implementing the interface and because the parameter type do not match them method is not being recognized, but maybe I'm wrong.
Here you can see some official doc:
https://docs.nativescript.org/runtimes/android/generator/extend-class-interface
Thanks in advance.
Ok, I solved it :S
It seems that the incremental build was doing something wrong. After deleting manually the build files of the demo everything went fine:
rm -rf platforms/android/build/*
rm -rf platforms/android/app/build/*
# Then build & deploy again
So, question code seems to be fine if you need to do something similar.

Null Pointer Exception in netflix hystrix library

Recently I started working on netflix hystrix library. I created a HystrixCommand object but I get a NPE. Ideally, it shouldn't happen. Any help will be appreciated. Is it a known issue ?
Please find the stack trace :
Exception in thread "main" java.lang.NullPointerException
at com.netflix.config.ConcurrentMapConfiguration.clearConfigurationListeners(ConcurrentMapConfiguration.java:330)
at org.apache.commons.configuration.event.EventSource.<init>(EventSource.java:76)
at org.apache.commons.configuration.AbstractConfiguration.<init>(AbstractConfiguration.java:63)
at com.netflix.config.ConcurrentMapConfiguration.<init>(ConcurrentMapConfiguration.java:68)
at com.netflix.config.ConcurrentCompositeConfiguration.<init>(ConcurrentCompositeConfiguration.java:172)
at com.netflix.config.ConfigurationManager.getConfigInstance(ConfigurationManager.java:125)
at com.netflix.config.DynamicPropertyFactory.getInstance(DynamicPropertyFactory.java:263)
at com.netflix.config.DynamicProperty.getInstance(DynamicProperty.java:245)
at com.netflix.config.PropertyWrapper.<init>(PropertyWrapper.java:58)
at com.netflix.hystrix.strategy.properties.archaius.HystrixDynamicPropertiesArchaius$ArchaiusDynamicProperty.<init>(HystrixDynamicPropertiesArchaius.java:62)
at com.netflix.hystrix.strategy.properties.archaius.HystrixDynamicPropertiesArchaius$StringDynamicProperty.<init>(HystrixDynamicPropertiesArchaius.java:73)
at com.netflix.hystrix.strategy.properties.archaius.HystrixDynamicPropertiesArchaius.getString(HystrixDynamicPropertiesArchaius.java:34)
at com.netflix.hystrix.strategy.HystrixPlugins.getPluginImplementationViaProperties(HystrixPlugins.java:344)
at com.netflix.hystrix.strategy.HystrixPlugins.getPluginImplementation(HystrixPlugins.java:334)
at com.netflix.hystrix.strategy.HystrixPlugins.getPropertiesStrategy(HystrixPlugins.java:243)
at com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory.getCommandProperties(HystrixPropertiesFactory.java:62)
at com.netflix.hystrix.AbstractCommand.initCommandProperties(AbstractCommand.java:204)
at com.netflix.hystrix.AbstractCommand.<init>(AbstractCommand.java:163)
at com.netflix.hystrix.HystrixCommand.<init>(HystrixCommand.java:61)
I faced similar issue, and here is how I solved it.
Hystrix -> uses archaius-core-0.4.1.jar -> which uses commons-configuration-1.8.jar
But due to jar conflicts in my current project, commons-configuration-1.3.jar is present instead of commons-configuration-1.8.jar
Unfortunately, there seems to be a bug in commons-configuration-1.3.jar in the constructor of org.apache.commons.configuration.event.EventSource (which I will explain below)
So, my suggestion is take a look into your classpath and I am sure you will find commons-configuration-1.3.jar. If so, just make sure you have the correct commons-configuration-1.8.jar. This should solve your problem!
Root Cause:
com.netflix.config.ConcurrentMapConfiguration -> is a sub class of
org.apache.commons.configuration.AbstractConfiguration -> which is a sub class of org.apache.commons.configuration.event.EventSource
Here is the skeleton
public class ConcurrentMapConfiguration extends AbstractConfiguration {
...
private Collection<ConfigurationListener> listeners = new CopyOnWriteArrayList<ConfigurationListener>();
...
public ConcurrentMapConfiguration() {
...
}
...
#Override
public void clearConfigurationListeners() {
listeners.clear(); // Here is the null pointer exception
}
...
}
But in EventSource (commons-configuration-1.3.jar)
public class EventSource {
...
public EventSource()
{
clearConfigurationListeners(); // This is the culprit
}
...
public void clearConfigurationListeners()
{
listeners = new LinkedList();
}
...
}
As you clearly see in the constructor of EventSource, you see an invocation to method clearConfigurationListeners(). And this method has been overriden in subclass ConcurrentMapConfiguration. So, the subclass method will be invoked. But by this time listeners is still null, because only after super class constructor is done the subclass can start initializing its stuff. Hence the NPE.
But in EventSource (commons-configuration-1.4.jar and above) - it is fixed
public class EventSource {
...
public EventSource()
{
initListeners(); // this is good
}
...
private void initListeners() // private method... Much better! No one can override this :)
{
listeners = new LinkedList();
...
}
...
}
Hope this helps!

SonarLint - RedundantThrowsDeclarationCheck - false positive?

In the following code I get a warning from the squid:RedundantThrowsDeclarationCheck rule on the Foo1Exception (behind the throws keyword): Remove the redundant '!unknownSymbol!' thrown exception declaration(s).
Foo.java:
public class Foo {
public static boolean bar(final String test) throws Foo1Exception, Foo2Exception {
if (test.startsWith("a")) {
throw new Foo1Exception();
} else if (test.startsWith("b")) {
throw new Foo2Exception();
} else if (test.startsWith("c")) {
return true;
}
return false;
}
}
Both exceptions are decrlared in seperate files:
Foo1Exception.java:
class Foo1Exception extends Exception {}
Foo2Exception.java:
class Foo2Exception extends Exception {}
I think this is a false positive, isn't it?
Also interesting: I don't get this message directly in SonarQube (web interface) only in the SonarLint plugin in IntelliJ IDEA.
Any Ideas?
I'm using: IntelliJ IDEA 2016.2.2; SonarLint 2.3 (with working server binding); SonarQube 5.6; SonarQube Java Plugin 4.0; Java 8
This seems to be fixed in SonarLint 2.3.1.

doesn't compile: sparkjava exception handling

I am trying to follow the sparkjava exception handling example located here, without success: http://sparkjava.com/documentation.html#exception-mapping. It appears the code they posted isn't quite right? I was able to fix one of the posted methods so that it compiles. The method on the documentation page which doesn't compile was:
get("/throwexception", (request, response) -> {
throw new NotFoundException();
});
I changed to this code and it compiles:
get(new Route("/throwexception") {
#Override
public Object handle(Request request, Response response) {
throw new IllegalArgumentException();
}
});
However, I am unable to get this method to compile. What is wrong? I am using java 8 and IntelliJ community edition 15.0.2 to compile. My java module is set to language level 8. Here is the suspect method:
exception(Exception.class, (e, request, response) -> {
//TODO: implement this after it compiles.
});
Here is the error I get from the compiler:
Error:(83, 9) java: cannot find symbol
symbol: method exception(java.lang.Class<java.lang.Exception>,(e,request[...]->{ })
location: class org.me.JournalController
To confirm that I really am using java 8, this example using a lambda expression does compile:
public class Lambdas {
public static void main(String[] args) throws Exception {
new Lambdas().start();
Thread.sleep(1000);
}
public void start(){
Interface f = () -> System.out.println("test");
}
}
The original code uses lambda expressions, you should use Java 8 to compile it.
My maven file had sparkjava dependency listed twice. I think my IDE automatically imported 1.1.1 for me at some point and I didn't realize it. I had 1.1.1 and 2.3. When I removed the outdated 1.1.1 sparkjava dependency then everything works as expected.
You can extract your throw statement into a function:
get("/throwexception", () -> BlowUp());
(snip)
public static void BlowUp()
{
throw new NotFoundException();
});

Google Cast - Cannot Resolve mSelectedDevice

I am having a problem making a Google Cast Service. I can not seem to find what to use for mSelectedDevice. Both tutorials that I am using do not provide enough explanation for this, and neither go into detail of what mSelectedDevice should be.
public class CastMediaRouterCallback extends MediaRouter.Callback{
#Override
public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo info) {
mSelectedDevice = CastDevice.getFromBundle(info.getExtras());
String routeId = info.getId();
//Startd NanoHTTPD, Find URI of photo/video, and display on Cast device
}
#Override
public void onRouteUnselected(MediaRouter router, MediaRouter.RouteInfo info) {
teardown();
mSelectedDevice = null;
}
}
(Tutorials I am using: https://developers.google.com/cast/docs/android_sender /// https://www.binpress.com/tutorial/building-an-android-google-cast-sender-app/161)
mSelecteDevice is an instance variable that is of type CastDevice. Not sure what you mean by "Google Cast Service" in your question but it seems you might be better off grabbing a sample project from oue GitHub repo as your starting point.

Categories