Ignore java code from debug library - java

On my project I have a Stetho Library that I use just in debug compile. But when I try to generate a release apk, it returns an error when compile javacode saying that the Stetho library couldn`t be found.
build.gradle
//Stetho Library
debugCompile 'com.facebook.stetho:stetho:1.2.0'
debugCompile('com.parse:parseinterceptors:0.0.1') {
exclude group: 'com.parse.bolts';
exclude group: 'com.parse';
}
StethoHelper.java
public class StethoHelper {
public static void initialize(Context context) {
com.facebook.stetho.Stetho.initialize(
com.facebook.stetho.Stetho.newInitializerBuilder(context)
.enableDumpapp(com.facebook.stetho.Stetho.defaultDumperPluginsProvider(context))
.enableWebKitInspector(com.facebook.stetho.Stetho.defaultInspectorModulesProvider(context))
.build());
}
public static void addInterceptor(Parse.Configuration.Builder builder) {
builder.addNetworkInterceptor(new com.parse.interceptors.ParseStethoInterceptor());
}
}
Ok, this error makes sense, but how can I suppress this error without have to comment my code?

you are using debugCompile 'com.facebook.stetho:stetho:1.2.0' which will work only for debug apk. you can change it to compile 'com.facebook.stetho:stetho:1.2.0'.
though you should not enable stetho in release build for security reasons.
Here is simple documentation for your reference.
http://littlerobots.nl/blog/stetho-for-android-debug-builds-only/

Related

imgui-java + Java = UnsatisfiedLinkError(libglfw.so)

I am catching an error when I try to compile the template application from imgui-java library using gradle.
Main.java
import imgui.ImGui;
import imgui.app.Application;
public class Main extends Application {
#Override
protected void configure(Configuration config) {
config.setTitle("Dear ImGui is Awesome!");
}
#Override
public void process() {
ImGui.text("Hello, World!");
}
public static void main(String[] args) {
launch(new Main());
}
}
Error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Failed to dynamically load library: /tmp/lwjglbuwnertys/3.2.3-SNAPSHOT/libglfw.so(error = null)
at org.lwjgl.system.linux.LinuxLibrary.loadLibrary(LinuxLibrary.java:32)
at org.lwjgl.system.linux.LinuxLibrary.<init>(LinuxLibrary.java:19)
at org.lwjgl.system.APIUtil.apiCreateLibrary(APIUtil.java:123)
at org.lwjgl.system.Library.loadNative(Library.java:360)
at org.lwjgl.system.Library.loadNativeFromLibraryPath(Library.java:349)
at org.lwjgl.system.Library.loadNative(Library.java:264)
at org.lwjgl.system.Library.loadNative(Library.java:222)
at org.lwjgl.glfw.GLFW.<clinit>(GLFW.java:674)
at java.base/jdk.internal.misc.Unsafe.ensureClassInitialized0(Native Method)
at java.base/jdk.internal.misc.Unsafe.ensureClassInitialized(Unsafe.java:1042)
at java.base/jdk.internal.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(UnsafeFieldAccessorFactory.java:43)
at java.base/jdk.internal.reflect.ReflectionFactory.newFieldAccessor(ReflectionFactory.java:186)
at java.base/java.lang.reflect.Field.acquireFieldAccessor(Field.java:1105)
at java.base/java.lang.reflect.Field.getFieldAccessor(Field.java:1086)
at java.base/java.lang.reflect.Field.getInt(Field.java:594)
at org.lwjgl.system.APIUtil.apiClassTokens(APIUtil.java:348)
at org.lwjgl.glfw.GLFWErrorCallback$1.<init>(GLFWErrorCallback.java:98)
at org.lwjgl.glfw.GLFWErrorCallback.createPrint(GLFWErrorCallback.java:97)
at imgui.app.Window.initWindow(Window.java:70)
at imgui.app.Window.init(Window.java:48)
at imgui.app.Application.initialize(Application.java:91)
at imgui.app.Application.launch(Application.java:81)
at Main.main(Main.java:54)
build.gradle:
plugins {
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'junit:junit:4.13.1'
implementation 'com.google.guava:guava:30.0-jre'
String imgui_java_version = '1.84.1.0'
implementation "io.github.spair:imgui-java-app:$imgui_java_version"
}
application {
mainClass = 'Main'
}
Creater of this library say:
So you only need one dependency line or one jar in classpath to make
everything to work. You don't need to add separate dependencies to
LWJGL or native libraries, since they are already included.
So I can't understand, why do I have a problem? How can I fix it?
It may depend on the version of imgui-java you're using, on how you actually installed it, maybe on your OS...
My advice: have a look at the project issues. Many users seem to have had similar UnsatisfiedLinkError issues.
In case you're not familiar with Java: UnsatisfiedLinkError is the error you get when Java is trying to load some native library to interact with.
In your case, the missing library is /tmp/lwjglbuwnertys/3.2.3-SNAPSHOT/libglfw.so.
Maybe you could check if it is present at this location? Maybe it is present with another name (something like libimgui-java64.so instead)? If it is the case, try to rename the library.

I faced two error when I run my retrofit test with robolectric befor the test starts

I have written this test in test pakage, for test of a retrofit class, but even before test stars,in addition to unknownable "constants" in #Config, this error is shown:
#Config(constants = BuildConfig.class, sdk =21, manifest="app/manifests/AndroidManifest.xml")
#RunWith(RobolectricTestRunner.class)
public class MultiFactorAPITest {
private MainActivity mainActivity;
#Mock
private MultiFactorAPI mockMultiFactorAPI;
#Captor
private ArgumentCaptor<Callback<List<ValidatePhoneUserResponse>>> callbackArgumentCaptor;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
mainActivity = controller.get();
// Then we need to swap the retrofit api impl. with a mock one
// We store our Retrofit api impl as a static singleton in class RestClient, hence:
RestClient.setApi(mockMultiFactorAPI);
controller.create();
}
The error is:
Annotation processors must be explicitly declared now. The following dependencies on the compile classpath are found to contain annotation processor. Please add them to the annotationProcessor configuration.
- auto-service-1.0-rc4.jar (com.google.auto.service:auto-service:1.0-rc4)
Alternatively, set android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true to continue with previous behavior. Note that this option is deprecated and will be removed in the future.
See https://developer.android.com/r/tools/annotation-processor-error-message.html for more details.
I've added these lines to gargle to:
dependencies {
implementation 'org.robolectric:robolectric:4.3'
implementation "org.mockito:mockito-core:1.10.19"
implementation 'org.hamcrest:hamcrest-library:1.1'
}
in gradle.Madule:
android{
testOptions {
unitTests {
includeAndroidResources = true
}
} }
in gradle.app:
dependencies{
classpath 'org.robolectric:robolectric-gradle-plugin:1.0.1'
}
in gradle.propertice:
android.enableUnitTestBinaryResources=true
android.enableAapt2=false
my problem solved by putting this code in my app.gradle :
dependencies{
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.okhttp3:mockwebserver:3.6.0'
}
and
1) find the location of of your .gradle folder, in Android Studio goto File->Settings and type "gradle" in the search box. You will be able to pick up the correct path there
2)Remove the .gradle directory (mine's location was C:\Users\UserName.gradle), and restart android studio. It will automatically create a new one.
from Android studio: build project error - Failed to complete Gradle execution

Gradle build ignores Jetbrains annotations

Let's say we have the following test code:
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
public class NullTest {
#Test
public void testNull() {
doNothing(null);
}
private #NotNull String doNothing(#NotNull String value) {
return value;
}
}
The test will pass when running gradle test directly or if IDEA delegates the action to gradle.
But it will fail with IllegalArgumentException: Argument for #NotNull parameter 'value' must not be null exception if it runs using IDEA runner (not delegated to gradle).
The question is: how to fail the test running it with gradle?
The easiest solution I have found is to apply org.jetbrains.intellij plugin.
Because among other things this plugin "patches compile tasks to instrument code with nullability assertions".
apply plugin: 'org.jetbrains.intellij'
intellij {
instrumentCode = true
downloadSources = false
}
Try adding the following to your dependencies. It worked for me.
compile 'org.jetbrains:annotations:13.0'
With this code - no way, because you use annotations from org.jetbrains.annotations.*, that use only in intellij idea tests runner. For gradle, annotation #NotNull (or #Nullable) says nothing. Maven also doesn't see this annotation. I can advise you use Objects.requireNonNull(T obj) for null checking.
We found that Lombok's #NonNull works better. But you need to configure IDEA to prefer this one during nullability-related analysis and generation
Adding the following dependency worked for me:
compile group: 'org.jetbrains', name: 'annotations', version: '15.0'
Run the 'dependencies' task & push the refresh button in Gradle.

ClassNotFoundException: org.jboss.naming.remote.client.InitialContextFactory when trying to load InitialContext

I'm testing (with JUnit) an rest service and to make shure everything goes as intended i need to use some EJB methods. Say, i have:
the class under test, wich is of no interest here;
testing class
public class UploadServiceTest {
private final String RemoteBeanLookupKey = "/project/dao/TaskManager!ru.project.dao.TaskManager";
#EJB private TaskManager taskManager;
#Before
public void startEverythingNeeded() throws Exception {
InitialContext ctx = null;
Properties jndiProp = new Properties();
InputStream testConfStream = getClass().getClassLoader().getResourceAsStream("jndi.properties");
jndiProp.load(testConfStream);
ctx = new InitialContext(jndiProp);
taskManager = ((TaskManager) ctx.lookup(RemoteBeanLookupKey));
}
#Test
public void blablabla(){
}
}
jndi.properties
java.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory
java.naming.provider.url=http-remoting://localhost:8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
jboss.naming.client.ejb.context=true
remote.connection.default.username=admin
remote.connection.default.password=admin
gradle dependencies: testCompile group: 'org.wildfly', name: 'wildfly-ejb-client-bom', version: '8.2.0.Final', ext: 'pom', testCompile group: 'junit', name: 'junit', version: '4.11' and provided project(path: ':dao') (this is the module i want to get EJB from).
But when i try to run test, it fails with javax.naming.NoInitialContextException: Cannot instantiate class: org.jboss.naming.remote.client.InitialContextFactory
[Root exception is java.lang.ClassNotFoundException: org.jboss.naming.remote.client.InitialContextFactory]
Other similar questions on here and on the net suggest to add jboss-client to CLASSPATH, but i've looked into README near jboss-client in my distribution and it sayed not to act like this and to make a gradle dependency instead. So I did.
Another strange thing about this: I got code and properties from tests to another module in same project (written by another coder). I tried to run those tests and they work as intended. I copied everything and even more (gradle depency), but get this exception.
I've tried to simplify the code in order to illustrate, I may have something important missing. If needed, I can copy some more parts of setup and code.
I changed the dependency on ejb-client from testCompile group: 'org.wildfly', name: 'wildfly-ejb-client-bom', version: '8.2.0.Final', ext: 'pom' to testCompile 'org.wildfly:wildfly-ejb-client-bom:10.0.0.Final' and it started working. Not sure if it is helpfull.

Gradle project does not build when I add RoboBlender

I have added RoboGuice 3 dependency into my gradle build file it compiles and runs, however the application crashes because of NoClassDefFoundError: AnnotationDatabaseImpl. Did some research that suggested that RoboBlender was necessary to generate the definition (I'm familiar with RoboGuice 2 which does not require RoboBlender) but when I add RoboBlender the project no longer builds.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:21.0.+'
compile 'com.koushikdutta.urlimageviewhelper:urlimageviewhelper:1.0.4'
compile 'de.hdodenhof:circleimageview:1.2.1'
compile 'com.getbase:floatingactionbutton:1.4.0'
compile 'de.hdodenhof:circleimageview:1.2.1'
compile 'org.twitter4j:twitter4j-core:4.0.2'
compile files('libs/json-me.jar')
compile files('libs/twitter_api_me-1.9.jar')
compile('ch.acra:acra:4.5.0') {
exclude group: 'org.json'
}
compile 'org.roboguice:roboguice:3.0.1'
provided 'org.roboguice:roboblender:3.0.1'
}
Build Error:
Error:Execution failed for task ':app:compileDebugJava'.
java.lang.ClassCastException: com.sun.tools.javac.code.Type cannot be cast to javax.lang.model.type.DeclaredType
l>Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.
Whats causing this and how can I fix it?
This kind of error can be caused by using #Inject incorrectly as in the following example:
public class Foo {
#Inject
public Foo(Context context, int code) {
//this won't work because of the primitive in the constructor
//and the #Inject annotation are being used together
}
}
RoboBlender will not be able construct the database because of being unable to cast the primitive as a declared type.
Hence, your error message
java.lang.ClassCastException: com.sun.tools.javac.code.Type cannot be cast to javax.lang.model.type.DeclaredType
means that the primitive (com.sun.tools.javac.code.Type) cannot be cast into a reference type javax.lang.model.type.DeclaredType
Instead, you need to write a Provider:
public class FooProvider implements Provider<Foo> {
Context context;
private static int CODE = 1;
#Inject
public FooProvider(Context context) {
this.context = context;
}
#Override
public Foo get() {
return new Foo(context, CODE);
}
}
and bind Foo to that provider in the module
binder.bind(Foo.class).toProvider(FooProvider.class);
and remove the #Inject from the constructor of Foo.
I suggest you traverse your object graph and look for #Inject annotations on constructors with primitives in them. Delete the annotations and write providers for them as above. RoboBlender will correctly build the AnnotationsDatabaseImpl and your project will compile.
Well I found a workaround, I just disabled AnnotationDatabase processing and removed RoboBlender dependency and that fix my problem. I would still like to know why I'm having this problem in the first place.
I had the same issue and in my case, having a class with 2 constructors:
#Inject
public PaymentSelectionDialog(Context context) {
this.context = context;
}
#Inject
public PaymentSelectionDialog(Context context, PaymentSelectable paymentSelectable) {
this.context = context;
this.paymentSelectable = paymentSelectable;
I had no problems using first constructor, but when I was instantiating my object using second constructor i have that problem. So the problem is that Roboguice is trying to inject an object that implements PaymentSelectable interface but this object is not defined in any module.
Maybe you are using a constructor with a reference that you are not defining in any of your modules.
Hope it helps!

Categories

Resources