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!
Related
I'm trying to deal with annotation processors. I followed tutorials. Here is my code:
#ExampleAnnotation
private void someMethod(){
System.out.println("hi");
}
#Retention(RetentionPolicy.SOURCE)
#Target(ElementType.METHOD)
public #interface ExampleAnnotation {
}
#SupportedAnnotationTypes("org.example.ExampleAnnotation")
public class Processor extends AbstractProcessor {
#Override
public boolean process(Set<? extends TypeElement> anots, RoundEnvironment roundEnvironment) {
anots.forEach(System.out::println);
return true;
}
}
I created META-INF/SERVICES/javax.annotation.processing.Processor
and registered my processor: org.example.Processor. It seems like everything is OK, but block of code in the processor just dont start. I have no idea what is wrong. P.S.: I use Gradle and Java 11.
i fixed my issue and decided to make a little step-by-step tutorial to create simple JAP:
Java-Annotation-Processor-guide
This is guide for annotation processing using gradle
I spent 3 days trying to deal with it, but with this little tutorial you will made JAP in 5 minutes.
sorry for bad english :)
So, first you should do is create gradle subproject for your project:
create project itself with gradle init or intellij
add to your main project's settings.gradle file this line include "*your subproject name, lets say:*annotation-processor"
Congrats, now let go to the processor itself
here is so much tutorials on the web about this part, so you can read something like this https://www.baeldung.com/java-annotation-processing-builde,
or this (Если ты русский): https://habr.com/ru/company/e-legion/blog/206208/
Final step is very easy - you will add your annotation processor to main project.
!!! instead of annotation-processor you should use your subproject name !!!
kotlin (or java + kotlin) -> {
add this plugin to your plugins: id "org.jetbrains.kotlin.kapt" version "1.7.21"
add this to your dependencies:
kapt project('annotation-processor')
compileOnly project('annotation-processor')
}
java -> {
add this to your dependencies:
annotationProcessor project('annotation-processor')
compileOnly project('annotation-processor')
}
(or you can read this on github: https://github.com/Blu3cr0ss/Java-Annotation-Processor-guide)
Im having trouble resolving the following runtime error: "Multiple HTTP implementations were found on the classpath. To avoid non-deterministic loading implementations, please explicitly provide an HTTP client via the client builders, set the software.amazon.awssdk.http.service.impl system property with the FQCN of the HTTP service to use as the default, or remove all but one HTTP implementation from the classpath"
I have the following two dependencies in my gradle.build :
implementation 'software.amazon.lambda:powertools-parameters:1.12.3'
implementation 'software.amazon.awssdk:sns:2.15.0'
They both seem to use the default HTTP client and compiler cannot determine which one to use. See below the declaration and use of them in code:
private static SsmClient = SsmClient.builder().region(Region.of((region == null) ? Regions.US_EAST_1.getName() : region)).build();
private static SSMProvider ssmProvider = ParamManager.getSsmProvider(client);
static SnsClient sns = SnsClient.builder().credentialsProvider(DefaultCredentialsProvider.builder().build())
.region((region == null) ? Region.US_EAST_1 : Region.of(region)).build();
I cannot remove one from the class path since I need both for my application and I have not succesfully been able to define an awssdk client via the builders.
I tried this but still got same runtime error:
client = SsmClient.builder().httpClientBuilder(new SdkHttpClient() {
#Override
public void close() {
}
#Override
public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) {
return null;
}
})
Looks like you will have to exclude one of the versions of http-client in your pom
implementation('<dependency>') {
exclude group: '<group>', module: '<module>'
}
where dependency is one of:
'software.amazon.lambda:powertools-parameters:1.12.3'
'software.amazon.awssdk:sns:2.15.0'
You can run gradle dependencies to see the dependency tree to figure out which one you want to exclude from
I have two projects known as (Common and ApiGateway).The common is a Gradle java project and ApiGateway is a Micronaut java application. In the common project, I am keeping all the common things and referencing the jar to the Apigateway project.
Common project
The below code is compiled with ./gradlew build
#Validated
public interface IProductOperation {
#Get(value = "/search/{text}")
#Secured(SecurityRule.IS_ANONYMOUS)
Flux<?> freeTextSearch(#NotBlank String text);
#Get(value = "/{?searchCriteria*}")
#Secured(SecurityRule.IS_ANONYMOUS)
Mono<?> find(FilterProductModel searchCriteria);
}
The API gateway implements the IProductOperation interface which is in the common project. When I navigate to the code base, I can see the below code is generated
#Validated
public interface IProductOperation {
#Get("/search/{text}")
#Secured({"isAnonymous()"})
Flux<?> freeTextSearch(#NotBlank String var1);
#Get("/{?searchCriteria*}")
#Secured({"isAnonymous()"})
Mono<?> find(FilterProductModel var1);
}
Now when I compile the second application the Apigateway project, I get an exception as The route declares a uri variable named [text], but no corresponding method argument is present which is valid because the parameter in freeTextSearch() and find() methods got changed to var1.
I have below dependency in the common project
dependencies {
annotationProcessor "io.micronaut:micronaut-inject-java:3.5.0"
annotationProcessor "io.micronaut:micronaut-validation:3.5.0"
implementation('io.swagger.core.v3:swagger-annotations:2.2.0')
implementation 'io.micronaut:micronaut-core:3.5.0'
implementation "io.micronaut:micronaut-inject:3.5.0"
implementation 'io.micronaut:micronaut-validation:3.5.0'
implementation ('io.micronaut.reactor:micronaut-reactor:2.2.2')
implementation("io.micronaut.security:micronaut-security-jwt:3.6.0")
}
I have build the application and publish to local mavel.
The documentation has a section about retaining parameter names https://docs.micronaut.io/latest/guide/#retainparameternames
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
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.