aspectj with android, aspect never called - android

In the project I'm working we've recently added some level of security, now i don't want to have to rewrite the entire nework logic if it can be done much more easily with AOP.
So, I'm trying to intercept the "onRequestSuccess" method of the requestListeners that are used throughout the application.
For this I have made a simple aspect:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class NetworkResponseAspect {
#Around("execution(public void *.onRequestSuccess(..))")
public void intercept(ProceedingJoinPoint joinPoint){
System.out.println("call intercepted " + joinPoint);
try {
joinPoint.proceed();
} catch (Throwable e) {
System.out.println("wut");
}
}
}
I've added the aspectj weaver dependency: compile 'org.aspectj:aspectjweaver:1.8.6'
And it seems to work, at least the annotations are recognized by android studio.
I've placed a breakpoint on the "joinpoint.proceed()" call and started the application in debug mode.
But when I log in (an action that triggers one such listener) nothing happens. Am I missing something?

In Maven you would use AspectJ Maven Plugin (current version is 1.7), in Gradle something similar. This is what you need for compilation if you want to use CTW (compile-time weaving). Those plugins should already contain a dependency on aspectjtools.jar which contains the AspectJ compiler and other stuff. If you use CTW, you need aspectjrt.jar (AspectJ runtime) as a default-scoped (compile) or dependency because it is needed during runtime as well.
If you want to use load-time weaving (LTW), though, you need aspectjweaver.jar on your JVM command line via -javaagent:... because the weaving agent needs to hook into class-loading before your first application class is loaded. P.S.: The weaving agent also contains the AspectJ runtime classes, so you do not need an additional dependency on the runtime in this case.

Related

Is it possible to get dependency version at runtime, including from library itself?

Background
Suppose I make an Android library called "MySdk", and I publish it on Jitpack/Maven.
The user of the SDK would use it by adding just the dependency of :
implementation 'com.github.my-sdk:MySdk:1.0.1'
What I'd like to get is the "1.0.1" part from it, whether I do it from within the Android library itself (can be useful to send to the SDK-server which version is used), or from the app that uses it (can be useful to report about specific issues, including via Crashlytics).
The problem
I can't find any reflection or gradle task to reach it.
What I've tried
Searching about it, if I indeed work on the Android library (that is used as a dependency), all I've found is that I can manage the version myself, via code.
Some said I could use BuildConfig of the package name of the library, but then it means that if I forget to update the code a moment before I publish the dependency, it will use the wrong value. Example of using this method:
plugins {
...
}
final def sdkVersion = "1.0.22"
android {
...
buildTypes {
release {
...
buildConfigField "String", "SDK_VERSION", "\"" + sdkVersion + "\""
}
debug {
buildConfigField "String", "SDK_VERSION", "\"" + sdkVersion + "-unreleased\""
}
}
Usage is just checking the value of BuildConfig.SDK_VERSION (after building).
Another possible solution is perhaps from gradle task inside the Android-library, that would be forced to be launched whenever you build the app that uses this library. However, I've failed to find how do it (found something here)
The question
Is it possible to query the dependency version from within the Android library of the dependency (and from the app that uses it, of course), so that I could use it during runtime?
Something automatic, that won't require me to update it before publishing ?
Maybe using Gradle task that is defined in the library, and forced to be used when building the app that uses the library?
You can use a Gradle task to capture the version of the library as presented in the build.gradle dependencies and store the version information in BuildConfig.java for each build type.
The task below captures the version of the "appcompat" dependency as an example.
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.0'
}
task CaptureLibraryVersion {
def libDef = project.configurations.getByName('implementation').allDependencies.matching {
it.group.equals("androidx.appcompat") && it.name.equals("appcompat")
}
if (libDef.size() > 0) {
android.buildTypes.each {
it.buildConfigField 'String', 'LIB_VERSION', "\"${libDef[0].version}\""
}
}
}
For my example, the "appcompat" version was 1.4.0. After the task is run, BuildConfig.java contains
// Field from build type: debug
public static final String LIB_VERSION = "1.4.0";
You can reference this field in code with BuildConfig.LIB_VERSION. The task can be automatically run during each build cycle.
The simple answer to your question is 'yes' - you can do it. But if you want a simple solution to do it so the answer transforms to 'no' - there is no simple solution.
The libraries are in the classpath of your package, thus the only way to access their info at the runtime would be to record needed information during the compilation time and expose it to your application at the runtime.
There are two major 'correct' ways and you kinda have described them in your question but I will elaborate a bit.
The most correct way and relatively easy way is to expose all those variables as BuildConfig or String res values via gradle pretty much as described here. You can try to generify the approach for this using local-prefs(or helper gradle file) to store versions and use them everywhere it is needed. More info here, here, and here
The second correct, but much more complicated way is to write a gradle plugin or at least some set of tasks for collecting needed values during compile-time and providing an interface(usually via your app assets or res) for your app to access them during runtime. A pretty similar thing is already implemented for google libraries in Google Play services Plugins so it would be a good place to start.
All the other possible implementations are variations of the described two or their combination.
You can create buildSrc folder and manage dependencies in there.
after that, you can import & use Versions class in anywhere of your app.

Android library with dependency not resolving properly

So I have an Android library project, SimpleWidget. I publish it to jcenter.
I can make a new project and add implementation 'my.project:simplewidget:1.2.3' and everything works as expected, I can use SimpleWidget instances and their public APIs.
Now I make another Android library project, ComplexWidget. ComplexWidget is a subclass of SimpleWidget. I add implementation 'my.project:simplewidget:1.2.3' to the build.gradle and everything resolves, and in fact I can even get away without lint yelling for something super basic like ComplexWidget complexWidget = new ComplexWidget().
However, the project will not compile. Any ComplexWidget method that has a return or parameter type of SimpleWidget (e.g., many of the inherited methods, or an interface that accepts SimpleWidget arguments, or a Factory that returns SimpleWidget instances) will not compile and Android Studio complains that "Cannot access my.project.SimpleWidget".
Not sure if I should even mention it for fear of muddying the waters, but if I command click SimpleWidget in, for example, public class ComplexWidget extends SimpleWidget, I get a warning at the top of the file that "Library source does not match the byetcode for the class SimpleWidget".
Any ideas?
TYIA
use api 'my.project:SimpleWidget:1.2.3' instead

How to resolve "Obsolete custom lint check" for my custom IssueRegistry written in Kotlin and make it work (Android)

I am trying to implement custom lint checks (using Kotlin). I have set up a module for my custom checks and added classes to test my first lew lint check, mostly following these two tutorials here and here.
So I now have a module, I have a custom IssueRegistry, I've created an issue and a Detector class for it. So far it seems complete. I've added a test to check if my lint check works and it looks alright.
I have added my module to the project by referencing it in settings.gradle like this: include ':app', ':somemodule', ':mylintmodule'
Now if I run the linter using ./gradlew lint I get a lint result file telling me this:
Lint found an issue registry (com.myproject.mylintmodule) which requires a newer API level. That means that the custom lint checks are intended for a newer lint version; please upgrade
Lint can be extended with "custom checks": additional checks implemented by developers and libraries to for example enforce specific API usages required by a library or a company coding style guideline.
The Lint APIs are not yet stable, so these checks may either cause a performance degradation, or stop working, or provide wrong results.
This warning flags custom lint checks that are found to be using obsolete APIs and will need to be updated to run in the current lint environment.
It may also flag issues found to be using a newer version of the API, meaning that you need to use a newer version of lint (or Android Studio or Gradle plugin etc) to work with these checks.
To suppress this error, use the issue id "ObsoleteLintCustomCheck" as explained in the Suppressing Warnings and Errors section.
So it tells me that I am using a newer API verion in my custom lint check, right? This is my custom IssueRegistry (minus some parts not relevant for this problem):
class MyCustomIssueRegistry : IssueRegistry() {
override val issues: List<Issue>
get() = listOf(ISSUE_NAMING_PATTERN)
override val api: Int = com.android.tools.lint.detector.api.CURRENT_API
override val minApi: Int = 1
}
From googling this problem and finding this issue I figured I have to override and set the right API version (and maybe the min API?) by overriding these properties like I did above (this version is my last attempt, directly taken from that issue).
So this property can be set to values between -1 and 5, meaning this (taken right out of the lint.detector.api class):
/** Describes the given API level */
fun describeApi(api: Int): String {
return when (api) {
5 -> "3.5+" // 3.5.0-alpha07
4 -> "3.4" // 3.4.0-alpha03
3 -> "3.3" // 3.3.0-alpha12
2 -> "3.2" // 3.2.0-alpha07
1 -> "3.1" // Initial; 3.1.0-alpha4
0 -> "3.0 and older"
-1 -> "Not specified"
else -> "Future: $api"
}
I have tried all of them, plus the one above adding a minApi override too, and I keep getting the exact same result for each of them.
Also I am unable to locate what other API version this is compared with. Is there a place where this is set for the regular linter in an Android project?
It's also unclear to me what I have to do to make sure my changes got applied - is it enough to change some code, then run lint, or do I have to compile the project first, or build & clean?
Following the tutorials, I added my custom lint check by adding this to the app's build.gradle: lintChecks project(":mylintmodule")
Is that even right? The API issue on my registry class shows up no matter if my lint check is referenced (and hopefully used) like that or not. I have also tried the other method described in the first tutorial, adding this task to the linter module build.gradle:
defaultTasks 'assemble'
task copyLintJar(type: Copy) {
description = 'Copies the lint jar file into the {user.home}/.android/lint folder.'
from('build/libs/')
into(System.getProperty("user.home") + '/.android/lint')
include("*.jar")
}
// Runs the copyLintJar task after build has completed.
build.finalizedBy(copyLintJar)
But since I can't figure out how to see if my custom checks are actually run, I don't know if that works as intended either.
So how do I get this warning resolved (since I interpret the text as "As long as the versions don't match I will not try to run your lint check"), and how can I make sure my lint check is actually run by the linter?

Scala reflection java.rmi dependency, can it work on Android?

I would like to use the Scala (2.11) reflection package's runtime mirror in a Scala application compiled for android which is being build using Scala on android.
I was able to fiddle with ProGuard options in order to make it include the required Scala classes. However when I try to get a mirror instance:
universe.runtimeMirror(this.getClass.getClassLoader)
(Indeed it fails during the lazy computation of universe)
The application crashes in run time:
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/rmi/Remote;
at scala.reflect.internal.Definitions$DefinitionsClass.RemoteInterfaceClass$lzycompute(Definitions.scala:370)
at scala.reflect.internal.Definitions$DefinitionsClass.RemoteInterfaceClass(D efinitions.scala:370)
at scala.reflect.runtime.JavaUniverseForce$class.force(JavaUniverseForce.scal a:255)
at scala.reflect.runtime.JavaUniverse.force(JavaUniverse.scala:16)
at scala.reflect.runtime.JavaUniverse.init(JavaUniverse.scala:147)
at scala.reflect.runtime.JavaUniverse.<init>(JavaUniverse.scala:78)
at scala.reflect.runtime.package$.universe$lzycompute(package.scala:17)
at scala.reflect.runtime.package$.universe(package.scala:17)
This crash is for me as expected as it isn't:
It is expected as java.rmi is not part of the Android API and I should expect any code trying to load its classes to crash.
It is unexpected as I didn't know that Scala's reflect package used java.rmi
I have traced the code to were rmi is required, that is to JavaUniverse (a trait mixed in JavaUniverse class) force method:
...
definitions.RemoteInterfaceClass
...
Which leads to DefinitionsClass:
lazy val RemoteInterfaceClass = requiredClass[java.rmi.Remote]
Am I wrong to think that this is a no-go for Scala reflection in Android?
If I am, what could be a workaround to this problem?
To summarize your solution and a related solution, it is sufficient to add two files, and modify build.sbt to include:
dexAdditionalParams in Android += "--core-library"
Add java/rmi/Remote.java to your project with the content:
package java.rmi;
public interface Remote {}
Add java/rmi/RemoteException.java to your project with the content:
package java.rmi;
public interface RemoteException {}

log4j support in Android

I am attempting to shoehorn an existing SDK onto an android device and one of the dependencies of said SDK is Apache log4j. I am able to load my test program onto the android emulator but when the log4j object "PropertySetter" is called the program fails with a verification exception. Is there a way to ameliorate this issue?
Actually using slf4j turned out a remarkably painless process for me, and it seems the common case, at least for libraries that use straightforward log4j features. You don't really need to swap slf4j in for log4j, only add two slf4j libraries to your project from http://www.slf4j.org/download.html:
-- the slf4j library for Android (currently slf4j-android-1.6.1-RC1.jar)
-- the log4j over slf4j (http://www.slf4j.org/legacy.html#log4j-over-slf4j) bridge.
The latter defines the core log4j classes used by typical implementations and bind them to the slf4j Android implementation. Once the libraries are added the code works.
I successfully got log4j working on android with a Socket Appender and Log4j Chainsaw. All code is located in this repository. Slf4j set up and working too. Be aware you have to configure it programmatically. You cannot use .properties or .xml files the parser wont work on android. Enjoy.
https://sourceforge.net/projects/log4j-android/
There is a new project, which enables log4j on android. Also using log4j over slf4j is possible. It also provides an appender for LogCat. See Logging in Android using Log4J.
The following example shows how to configure and use log4j in Android.
Configure the log4j system in Android
import org.apache.log4j.Level;
import android.os.Environment;
import de.mindpipe.android.logging.log4j.LogConfigurator;
/**
* Simply place a class like this in your Android applications classpath.
*/
public class ConfigureLog4J {
static {
final LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(Environment.getExternalStorageDirectory() + "myapp.log");
logConfigurator.setRootLevel(Level.DEBUG);
// Set log level of a specific logger
logConfigurator.setLevel("org.apache", Level.ERROR);
logConfigurator.configure();
}
}
Logging in Android using log4j using slf4j API
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExampleLog4JOverSLF4J {
private final Logger log = LoggerFactory.getLogger(ExampleLog4JOverSLF4J.class);
public void myMethod() {
log.info("This message should be seen in log file and logcat");
}
}
Logging in Android using log4j API
import org.apache.log4j.Logger;
public class ExampleLog4J {
private final Logger log = Logger.getLogger(LogConfiguratorTest.class);
public void myMethod() {
log.info("This message should be seen in log file and logcat");
}
}
I would recommend trying to swap in slf4j in place of log4j. It's not a painless switch but its likely to be easier than what you have. slf4j provides a common front-end for several loggers including log4j and there is an slf4j-android package.
No, Android's logging mechanism is not decent. It's very inadequate compared to what log4j can do for you.
The parser for log4j configuration files is not android safe.slf4j's android compatibility thing with log4j just overrides the log4j classes you will use and forces them to use android logcat style logging. You still don't get the full flexibility of log4j on android. I ported log4j on android in my project https://sourceforge.net/projects/log4j-android/ all you have to do is add the two jars in the binaries directory to you classpath. Then
static {
org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger();
final SocketAppender appender = new SocketAppender("192.168.1.4", 4445);
root.addAppender(appender);
}
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MyClass.class);
static {
logger.info("Hello logger");
}
This will start sending out messages to the remote host you specified. You can then see this messages with Chainsaw http://logging.apache.org/log4j/docs/webstart/chainsaw/chainsawWebStart.jnlp. To make chainsaw work click the second check box on the dialog that pops up hit ok, start your app and a new tab should appear. Be aware your firewall might block it...
Check out this project for a complete implementation: http://code.google.com/p/log4j-android/

Categories

Resources