Use JAXB (xjc) generated classes in android - android

I am using a Rest-Webservice in Android. The Web Service could handle JSON and XML, the API is described as an XSD. So I used JAXB to generate classes from the XSD and then I used jackson JSON processor to generate JSON from my instances.
The problem is, that JAXB (xjc) generates classes with JAXB annotations and Android can't handle those. I tried to add the jaxb-api.jar to my android project but the Dalvik won't use core classes.
For my first implementation I manually removed the annotations. But now the XSD was updated and I don't want to do this every time this happens.
Do you have any idea how to handle this problem in a better way? Is there a possibility to use jaxb/xjc without annotations or is there another code generater that could do this? Do you know an easy way to remove annotations from java classes (even if they are printed in multiple lines)? Is there a project setting for Android Eclipse projects, that makes the dalvik to allow core libs?
thx, cathixx

I had to do some extra researching to make cathixx's answer work since I'm new to Ant, so I'll share this to help others.
These instructions will take Java files with code like:
import javax.xml.bind.annotation.XmlElement;
#XmlRootElement
public class Response {...
...and comment these occurrences out, so it looks like:
/*import javax.xml.bind.annotation.XmlElement;*/
/*#XmlRootElement*/
public class Response {...
First, create a file build.xml (or whatever you want to call it - must be .xml) in a new Eclipse project (a "General" project is fine).
Then, add the following text to the build.xml file:
<?xml version="1.0"?>
<project
name="CommentOutXmlAnnotations"
basedir="."
default="commentOutXmlAnnotations" >
<!-- This Ant script comments out the following lines from the Java files in this directory:
import javax.xml.bind.annotation.*;
#Xml*
-->
<target
name="commentOutXmlAnnotations"
description="Run" >
<replaceregexp
byline="false"
flags="g" >
<regexp pattern="(#Xml[A-Za-z0-9]+(\([^)]+\))?|import javax\.xml\.bind\.annotation\.[A-Za-z0-9.]+;)[ \t]*(\r?\n)" />
<substitution expression="/*\1*/\3" />
<fileset dir="." >
<include name="*.java" />
</fileset>
</replaceregexp>
</target>
</project>
Put the *.java files you want to comment out the XML imports and annotations for in the same directory as the build.xml file.
Right-click on the build.xml file in Eclipse, and click "Run As->Ant Build".
You should see output like:
Buildfile: D:\Eclipse_Projects\StripAnnotations\build.xml
commentOutXmlAnnotations:
BUILD SUCCESSFUL
Total time: 403 milliseconds
...and the XML imports and annotations should be commented out of your files.
Done!
Note: if you want to include all *.java files in all subdirectories of the build.xml file (for example, to comment out all XML annotations/imports generated for a bunch of JAXB classes in multiple packages), change the fileset tag to:
<fileset dir="." >
<include name="**/*.java" />
</fileset>

now, I solved it by myself by commenting all annotations with the following ant script:
<replaceregexp flags="g" byline="false">
<regexp pattern="(#Xml[A-Za-z0-9]+(\([^)]+\))?|import javax\.xml\.bind\.annotation\.[A-Za-z0-9.]+;)[ \t]*(\r?\n)"/>
<substitution expression="/*\1*/\3"/>
<fileset dir="path/to/files">
<include name="*.java"/>
</fileset>
</replaceregexp>

Related

How does gradle execute an ant build file

Ive been driving myself crazy trying to rebuild my custom_rules.xml into something in gradle and its proving to be quite difficult. So my next step is Im trying to just import the last few things I cant do in gradle as an build.xml.
However this doesnt seem to do anything. When I try using
ant.importBuild 'build.xml'
I get no feed back or no echos from my script. Ive read through gradles documentation a lot especially on ant and for the life of me I cant figure out what Im supposed to do once the build gets imported. How does the script get executed?
This is my build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project>
<target name="postPackage" >
<property name="config_path" location="${cert.dir}" />
<property name="out.pre.widevine.signed.file" location="release-pre-widevine-sign.apk" />
<property name="out.widevine.signed.file" location="release-widevine-signed.apk" />
<echo>sign with widevine certificate</echo>
<touch file="res/raw/wv.properties"/>
<copy file="${out.packaged.file}" tofile="${out.pre.widevine.signed.file}"/>
<java jar="apksigtool.jar" failonerror="true" fork="true">
<arg value="${out.packaged.file}"/>
<arg value="private_key.der" />
<arg value="my.crt" />
</java>
<copy file="${out.packaged.file}" tofile="${out.widevine.signed.file}"/>
</target>
</project>
I was able to accomplish this by using the following snippet in a method
ant.importBuild 'build.xml'
postPackage.doFirst{println("Im starting")}
postPackage.execute()
ant.importBuild will create an equally named Gradle task for each Ant target found in the Ant build. You can then invoke those tasks from the command line and/or make other tasks depend on them. For more information, see "16.2. Importing an Ant build" in the Gradle User Guide,
Hmm I think this Kotlin is working for me;
val t : Task = tasks.named("war").get()
t.actions.forEach { a -> a.execute(t) }

Generating android code coverage though changes in build.xml and ant.properties

I have been trying to generate android code coverage for my android test project which tests a android project which includes a external jar. When I run command
ant emma install debug test
it shows coverage of only the android project but does not include the package and functions of the external jar included.
As per my researches I have found that some changes should be done in ant.properties file and emma report tag in build.xml.
Any suggestions are most welcome.
[Edit]
On furthur study, I went through a blog which says enter the variable
tested.android.library.source.dir="path to external jars" in ant.properties
and same variable should be added in report sourcepath as
<emma>
<report sourcepath="${tested.project.source.absolute.dir}:${tested.project.lib.source.path.value}:${tested.android.library.source.dir}" verbosity="${verbosity}">
<!-- TODO: report.dir or something like should be introduced if necessary -->
<infileset file="${out.absolute.dir}/coverage.ec" />
<infileset file="${tested.project.out.absolute.dir}/coverage.em" />
<!-- TODO: reports in other, indicated by user formats -->
<html outfile="${out.absolute.dir}/coverage.html" />
</report>
</emma>
But still the coverage is not showing functions and package of External jar.
I wanted to know that my jars are not in the android test project but in the android project which is tested. So how to give path to those external jars in ant.properties of the test project.
I am also working on the same from quite some time.
Refer to code coverage reports for library projects
External jars coverage support is in ADT-r20.
I can only point to the direction I am working.
I am working on modifying build.xml inside ant :
<!-- This is macro that enable passing variable list of external jar files to ApkBuilder
Example of use:
<package-helper>
<extra-jars>
<jarfolder path="my_jars" />
<jarfile path="foo/bar.jar" />
<jarfolder path="your_jars" />
</extra-jars>
</package-helper> -->
<macrodef name="package-helper">
<element name="extra-jars" optional="yes" />
<sequential>
<apkbuilder
outfolder="${out.absolute.dir}"
resourcefile="${resource.package.file.name}"
apkfilepath="${out.packaged.file}"
debugpackaging="${build.is.packaging.debug}"
debugsigning="${build.is.signing.debug}"
verbose="${verbose}"
hascode="${manifest.hasCode}"
previousBuildType="${build.last.is.packaging.debug}/${build.last.is.signing.debug}"
buildType="${build.is.packaging.debug}/${build.is.signing.debug}">
<dex path="${intermediate.dex.file}"/>
<sourcefolder path="${source.absolute.dir}"/>
<jarfile refid="project.all.jars.path" />
<nativefolder path="${native.libs.absolute.dir}" />
<nativefolder refid="project.library.native.folder.path" />
<extra-jars/>
</apkbuilder>
</sequential>
</macrodef>
I have no luck till yet.
After lots of searching and trying , finally got the package of my External jar in my Main project.
Just entered tested.android.library.source.dir in ant.properties and build.xml
ant.properties: tested.android.library.source.dir="Path to libs folder of main project where jars are present"
Build.xml : Under emma tag in report tag add this variable seperated by colon.
Now go to command prompt and run
In Main Project :android update project -p .
In Test Project: android update test-project -m "Path of main project" -p .
Now copy test target from build.xml (sdk/tools/ant/build.xml) and paste it in build.xml of test project above the line
<import file="${sdk.dir}/tools/ant/build.xml" />
Dont Forget to Change Version Tag to
Now Again open command prompt and run:
In Main Project: ant emma debug install
In Test Project: ant emma debug install test
Your Code coverage report generated will contain the package of the external jar
I struggled with this for 2 days and eventually figured it out. The code snippet in the first post only generates instrument report from emma metadatafile and runtime coverage file but does not perform instrumentation on jar. To instrument the code you will have to manipulate the byte code, like how android ant build.xml target does it. Take a look at the element nested in <-compile> and you will see comment like it is only instrumenting class files. To instrument the jars add a classpath like element to the jars along with path to class.
Emma Documentation: http://emma.sourceforge.net/reference/ch02s03s02.html
<emma enabled="${emma.enabled}" >
<instr mode="fullcopy"
outdir="${out.instr.dir}"
merge="no"
filter="${emma.filter}">
<instrpath>
<fileset dir="${out.dir}" includes="**/*.jar" />
</instrpath>
</instr>
</emma>
In Android's build.xml. One just have to delete instrpath attribute and make it look like the example above.
756 <emma enabled="true">
757 <instr verbosity="${verbosity}"
758 mode="overwrite"
759 instrpath="${out.absolute.dir}/classes"
760 outdir="${out.absolute.dir}/classes"
761 metadatafile="${emma.coverage.absolute.file}">
762 <filter excludes="${emma.default.filter}" />
763 <filter value="${emma.filter}" />
764 </instr>
765 </emma>
So something like this: (pardon the line#s)
756 <emma enabled="true">
757 <instr verbosity="${verbosity}"
758 mode="overwrite"
760 outdir="${out.absolute.dir}/classes"
761 metadatafile="${emma.coverage.absolute.file}">
759 <instrpath>
759 <pathelement path="${out.absolute.dir}/classes"/>
759 <fileset dir="${you-class-path}"/>
759 <include name="**/*.jar"/>
759 </fileset>
759 </instrpath>
762 <filter excludes="${emma.default.filter}" />
763 <filter value="${emma.filter}" />
764 </instr>
765 </emma>

How to Automatically Modify versionName in Manifest during Build?

So far I have been focusing on my application's programming and paid little attention to making the build process smarter. Thus I have been doing things pretty much manually (the "dumb way"), including updating by hand android:versionCode and android:versionName in AndroidManifest.xml.
I would like now to automatically (i.e. upon Build or upon Export):
Fetch from git the latest tag/branch containing build and version codes.
Parse them so that I can assign them to the respective fields in AndroidManifest.xml.
Modify AndroidManifest.xml accordingly.
Proceed with the normal build process (Eclipse+ADT, no Ant whatsoever), as if I did 1-2-3 by hand...
I found a few clues about a "pre-build step", builders and build.xml, but I have no idea where to find those and where to start.
Any tips or pointers on where I could find more information on the subject? (a step-by-step tutorial would be ideal)
Update 1: I found this thread to be suggesting that I:
Right-click on the project, Properties > Builders
Add a builder that points to the project's Ant build file.
Order that builder to be invoked before the Java builder
Fine, but where is the project's Ant build file? Where do I find it?
Update 2: Apparently, it's possible to export the entire project into an Ant file. But I am not sure that's I want. Must a pre-build step always include an Ant build file?
Update 3: Is building an Ant file, only for the pre-build step, the right approach?
Here's what I use to dynamically assign a versionCode and versionName to AndroidManifest.xml. It works only when building with ant, so you'll have to install it first. Then go to the project directory in your command line and execute "android update project -p .", which will create the necessary files for building with ant, like local.properties and build.xml.
Then open build.xml and place this inside:
<target name="-pre-build" depends="-custom-git-version,-custom-manifest-version">
</target>
<!-- Packages the application. -->
<target name="-post-build">
<antcall target="-custom-restore-manifest"/>
<property name="suffix" value="${git.commits}-${git.version}.apk" />
<exec executable="sed" inputstring="${out.final.file}" outputproperty="out.final.renamedfile">
<arg value="s/\.apk/-${suffix}/" />
</exec>
<copy file="${out.final.file}" tofile="${out.final.renamedfile}" />
<echo>Final file copied to: ${out.final.renamedfile}</echo>
</target>
<!-- Custom targets -->
<target name="-custom-git-version">
<exec executable="sh" outputproperty="git.commits">
<arg value="-c" />
<arg value="git log --pretty=format:'' | wc -l" />
</exec>
<echo>git.commits: ${git.commits}</echo>
<exec executable="git" outputproperty="git.version">
<arg value="describe" />
<arg value="--tags" />
<arg value="--long" />
</exec>
<echo>git.version: ${git.version}</echo>
</target>
<target name="-custom-manifest-version">
<echo>Creating backup of AndroidManifest.xml</echo>
<copy file="AndroidManifest.xml" tofile="AndroidManifest.xml.antbak" preservelastmodified="true" />
<replaceregexp
file="AndroidManifest.xml"
match='android:versionCode="(\d+)"'
replace='android:versionCode="${git.commits}"' />
<replaceregexp
file="AndroidManifest.xml"
match='android:versionName="(\d+\.\d+)\.\d+"'
replace='android:versionName="\1.${git.commits}"' />
</target>
<target name="-custom-restore-manifest">
<echo>Restoring backup of AndroidManifest.xml</echo>
<move file="AndroidManifest.xml.antbak"
tofile="AndroidManifest.xml"
preservelastmodified="true"
overwrite="true" />
</target>
The output of this is not exactly what you want, but it is a start - feel free to modify it :) The result is something like "yourapp--.apk
Using this you'll build your application with executing "ant clean debug", or "ant clean release", depending on what you want. You can also create "ant.properties" file with this content:
key.store=keystore_file
key.store.password=some_password
key.alias=some_alias
key.alias.password=some_other_password
to enable automatic signing of your app.
You should also read this: http://developer.android.com/tools/building/building-cmdline.html
You are on the right track with setting up a pre-build step, but the ant build file is something you'll create yourself from scratch. Eclipse has some ant scripts that it uses externally that handle the automated compilation, packaging and stuff, but you want to create a separate one that just does these extra steps you want.
So, you're going to have to learn a bit about ant scripting to get this done. Some of those links you found give you the basic idea of how to create a simple ant file. To add to that, some of the ant tasks you will probably need to use are:
Exec - You will need this to execute your git command that gets your version info. It has an argument called resultProperty you can use to store the output of the command into a property that ant can access. (or you can just have the command output to a file and ant can access that.)
ReplaceRegExp - You will need this to replace tokens (maybe #VERSIONCODE# and #VERSIONNAME# ) you place in your AndroidManifest.xml where the values should eventually go, with the values returned by the exec.
You will probably also want to execute an exec task at the beginning to restore your AndroidManifest.xml file to it's original state (with the tokens in place) so it's repeatable without manual cleanup. I would provide more info on the git commands you need to run within these exec tasks, but I'm afraid all my experience is with Subversion, so you'll have to fill in the gaps there.
You should consider building with maven-android. Once you have your project building cleanly, use the version-update plugin to automatically increment your version number.
Writing a build script with maven-android can't be described as easy - but the payoff is worth the effort and you should consider this avenue.
Also, this tutorial might come in handy (I use a variant of the technique described here for my own builds)
EDIT (2014):
Consider migrating to Android Studio and using Gradle. See: How to autoincrement versionCode in Android Gradle
The way I managed to achieve this: build > execute shell (we needed some php code to receive some info from a db) and the string replacement happens in php:
#!/usr/bin/php
<?php
$filename = $WORKSPACE."/src/com/me/myapp/MyActivity.java";
$file = #file_get_contents($filename);
if($file) {
$repl = preg_replace("OriginalString", "NewString", $file);
file_put_contents($filename, $repl);
echo "\n\nReplaced some stuff in $filename";
}
?>

How to set strings.xml values at build time?

I'm building my Android application with Ant, and would like to set one of the values in my strings.xml at build time. For example, I could use
<string name="app_name">MyApp-DEBUG</string>
with a debug build, or I could use
<string name="app_name">MyApp<string>
for a release build. Is this possible?
There are two tasks in Ant that can help:
First is the <replace>. You give it a file name that contains parameters that can be replaced, and you give the <replace> task the values for those parameters. It replaces them in the file. I don't like this task because it's used to replace stuff that is under version control, and if you're not careful, you can end up changing the file without meaning to.
settings.xml
<settings>
<properties>
<property name="server" value="#SERVER#"/>
</properties>'
</settings>
Replace Task
<replace file="settings.xml">
<replacetoken token="#SERVER#" value="google.com"/>
</replace>
I've seen plenty of version control repositories where revision #3 of the replaced file was an accidental checkin of the the file with the replaced parameters (and not realizing it until the next release when the parameters didn't get changed). Then version #4 is a duplicate of version #2 which had the replacement parameters. Followed by a bad version #5, followed by a version #6 which restores the file, and on and on.
My preferred method is to copy the file over to another directory, and use <filterset>/<filter> tokens to change the file while being copied:
<copy todir="${target.dir}"
file="settings.xml">
<filterset>
<filter token="SERVER" value="google"/>
</filterset>
</copy>
Both can use a property file instead of specifying individual tokens. The <copy>/<filterset> pair can take a fileset of files and replace a bunch of tokens at once. (Be careful not to pass it a binary file!).
try this code, it works for me
<target name="app-name-debug">
<replaceregexp file="res/values/strings.xml" match='name="app_name"(.*)'
replace='name="app_name">MyApp-DEBUG<\/string>'/>
</target>
<target name="app-name-release">
<replaceregexp file="res/values/strings.xml" match='name="app_name"(.*)'
replace='name="app_name">MyApp<\/string>'/>
</target>

Android - How do I dynamically set the package name at build time for an Open-source project?

I'm working on an Open-source project. As it is intended that anyone can download the source and build it themselves, I do not want to hard-code the package name anywhere - including the directory structure.
I use ant for building. Apparently I can modify build.xml, but I believe this is overwritten by android update. Whatever is used will be committed to the Git repo, and it should not be too complicated.
Currently the process to build the code straight from the Git repo is fairly simple. Here's an excerpt from the README file:
$ cd ~/src/isokeys/IsoKeys
$ android list targets # I build against API level 10.
$ android update project --name IsoKeys --target 1 --path ./ # Only needed first time.
$ ant debug && adb -d install -r bin/IsoKeys-debug.apk
To me, it makes sense to put the package name in local.properties, because this is .gitignore'd. As the package name won't be anywhere else, the build will fail without doing this. So there needs to be at least 1 extra step in the README, but I want to keep it to a minimum.
Edit: Of course, another requirement is that diffs make sense - which they don't if you manually rename the package name.
I did something similar (but not for this reason) which required updating the manifest at build time. The way I accomplished this was by making a second AndroidManifest and putting it under a directory named config.
So in config/AndroidManifest you could have something like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="#CONFIG.APP_PACKAGE_NAME#"
android:versionCode="#CONFIG.APP_VERSION_CODE#"
android:versionName="#CONFIG.APP_VERSION#">
<!-- EVERYTHING ELSE GOES HERE -->
</manifest>
Then you can use the regular bare bones build.xml ant script with just a few modifications (no need to copy the whole script from the android build system as they added some hooks for you to use without reinventing the wheel).
The build script should be reading local.properties by default, but if not add (or uncomment) a line like this:
<property file="local.properties" />
In your build script you should see a task called "-pre-build", change it like this:
<target name="-pre-build">
<copy file="config/AndroidManifest.xml" todir="." overwrite="true" encoding="utf-8">
<filterset>
<filter token="CONFIG.APP_PACKAGE_NAME" value="${app.packagename}" />
<filter token="CONFIG.APP_VERSION" value="${app.version}" />
<filter token="CONFIG.APP_VERSION_CODE" value="${app.versioncode}" />
</filterset>
</copy>
</target>
Then your local.properties file you would put the package name, version name/code like so:
app.version=1.0
app.versioncode=1
app.packagename=com.mypackage.name
Now you just need to make sure in your manifest that you fully qualify all of your activities/services/broadcast listeners etc.. That means you always specify the full package of your source code. If you want the package for your own source code to be dynamic you could replace out each of the prefixes to each class.. But that seems kind of silly.. It is easy enough to package your code up under your own package name and they can use it from any project by simply including the source or a jar in their project.
-- UPDATE --
Oh and one other thing you can do to notify the user that they must define a package name is use the fail tag in your build xml like this:
<fail message="app.packagename is missing. This must be defined in your local.properties file" unless="app.packagename" />
Put this after the line which reads the local.properties file
With thanks to Matt Wolfe for his help, I'm posting a partial answer with my efforts so far.
I noticed that the default barebones build.xml would also import custom_rules.xml:
<import file="custom_rules.xml" optional="true" />
So I created this file and started tinkering. This is what I have come up with so far:
<?xml version="1.0" encoding="UTF-8"?>
<project name="custom_rules" default="debug">
<target name="-pre-build">
<fail message="Please define app.packagename in your local.properties file." unless="app.packagename" />
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
<classpath>
<pathelement location="/usr/share/java/ant-contrib.jar"/>
</classpath>
</taskdef>
<!-- How do I check for propertyregex?
<fail message="Depends on ant-contrib's propertyregex for app.packagename.path." unless="propertyregex" />
-->
<propertyregex property="app.packagename.path"
input="${app.packagename}/"
regexp="\."
replace="/"
global="true"
/>
<copy todir="build/" overwrite="true" encoding="utf-8">
<fileset dir="./">
<include name="AndroidManifest.xml" />
<include name="res/**" />
<include name="lib/**" />
</fileset>
<filterset>
<filter token="CONFIG.APP_PACKAGE_NAME" value="${app.packagename}" />
</filterset>
</copy>
<copy todir="build/src/${app.packagename.path}" overwrite="true" encoding="utf-8">
<fileset dir="./src/isokeys/">
<include name="**" />
</fileset>
<filterset>
<filter token="CONFIG.APP_PACKAGE_NAME" value="${app.packagename}" />
</filterset>
</copy>
</target>
<target name="-pre-clean" description="Removes output files created by -pre-build.">
<delete file="build/AndroidManifest.xml" verbose="${verbose}" />
<delete dir="build/res/" verbose="${verbose}" />
<delete dir="build/lib/" verbose="${verbose}" />
<delete dir="build/src/" verbose="${verbose}" />
</target>
<!-- NOW CHANGE DIRECTORY TO build/ BEFORE HANDING BACK OVER TO build.xml!!! -->
</project>
This sets everything up in build/ (which has the added bonus of keeping things neat and tidy), now the intention is for the sdk tools build.xml to run from this build/ directory. However, I can't find any way of cd'ing.
Easiest way might be replace the package name as late as possible. This way, you don't even have to touch your code. There is a nice article named Renaming the Android Manifest package(http://www.piwai.info/renaming-android-manifest-package/). Summary:
You can use aapt --rename-manifest-package to modify the package name
Alternatively, if you want package name replacement to be a part of the ant build process, you can override the -package-resources target:
copy the -package-resources target from SDK's build.xml
add manifestpackage parameter

Categories

Resources