signature:
public class AbstractAndroidMojo { /** * Provides package name for android artifact .
 * @ param artifact android artifact which package have to be extracted
 * @ return package name
 * @ throws MojoExecutionException if there is no AndroidManifest . xml for provided artifact
 * or appears error while parsing in { @ link # extractPackageNameFromAndroidManifest ( File ) }
 * @ see # extractPackageNameFromAndroidManifest ( File ) */
protected String extractPackageNameFromAndroidArtifact ( Artifact artifact ) throws MojoExecutionException { } }

implementation: final File unpackedLibFolder = getUnpackedLibFolder ( artifact ) ; final File manifest = new File ( unpackedLibFolder , "AndroidManifest.xml" ) ; if ( ! manifest . exists ( ) ) { throw new MojoExecutionException ( "AndroidManifest.xml file wasn't found in next place: " + unpackedLibFolder ) ; } return extractPackageNameFromAndroidManifest ( manifest ) ;


signature:
public class AbstractAndroidMojo { /** * Attempts to find the instrumentation test runner from inside the AndroidManifest . xml file .
 * @ param manifestFile the AndroidManifest . xml file to inspect .
 * @ return the instrumentation test runner declared in AndroidManifest . xml , or { @ code null } if it is not declared .
 * @ throws MojoExecutionException */
protected String extractInstrumentationRunnerFromAndroidManifest ( File manifestFile ) throws MojoExecutionException { } }

implementation: final URL xmlURL ; try { xmlURL = manifestFile . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { throw new MojoExecutionException ( "Error while trying to figure out instrumentation runner from inside AndroidManifest.xml file " + manifestFile , e ) ; } final DocumentContainer documentContainer = new DocumentContainer ( xmlURL ) ; final Object instrumentationRunner ; try { instrumentationRunner = JXPathContext . newContext ( documentContainer ) . getValue ( "manifest//instrumentation/@android:name" , String . class ) ; } catch ( JXPathNotFoundException e ) { return null ; } return ( String ) instrumentationRunner ;


signature:
public class AbstractAndroidMojo { /** * < p > Returns the Android SDK to use . < / p >
 * < p > Current implementation looks for System property < code > android . sdk . path < / code > , then
 * < code > & lt ; sdk & gt ; & lt ; path & gt ; < / code > configuration in pom , then environment variable < code > ANDROID _ HOME < / code > .
 * < p > This is where we collect all logic for how to lookup where it is , and which one to choose . The lookup is
 * based on available parameters . This method should be the only one you should need to look at to understand how
 * the Android SDK is chosen , and from where on disk . < / p >
 * @ return the Android SDK to use .
 * @ throws org . apache . maven . plugin . MojoExecutionException
 * if no Android SDK path configuration is available at all . */
protected AndroidSdk getAndroidSdk ( ) throws MojoExecutionException { } }

implementation:
File chosenSdkPath ; String chosenSdkPlatform ; String buildToolsVersion = null ; if ( sdk != null ) { // An < sdk > tag exists in the pom .
buildToolsVersion = sdk . getBuildTools ( ) ; if ( sdk . getPath ( ) != null ) { // An < sdk > < path > tag is set in the pom .
chosenSdkPath = sdk . getPath ( ) ; } else { // There is no < sdk > < path > tag in the pom .
if ( sdkPath != null ) { // - Dandroid . sdk . path is set on command line , or via < properties > < android . sdk . path > . . .
chosenSdkPath = sdkPath ; } else { // No - Dandroid . sdk . path is set on command line , or via < properties > < android . sdk . path > . . .
chosenSdkPath = new File ( getAndroidHomeOrThrow ( ) ) ; } } // Use < sdk > < platform > from pom if it ' s there , otherwise try - Dandroid . sdk . platform from command line or
// < properties > < sdk . platform > . . .
if ( ! isBlank ( sdk . getPlatform ( ) ) ) { chosenSdkPlatform = sdk . getPlatform ( ) ; } else { chosenSdkPlatform = sdkPlatform ; } } else { // There is no < sdk > tag in the pom .
if ( sdkPath != null ) { // - Dandroid . sdk . path is set on command line , or via < properties > < android . sdk . path > . . .
chosenSdkPath = sdkPath ; } else { // No - Dandroid . sdk . path is set on command line , or via < properties > < android . sdk . path > . . .
chosenSdkPath = new File ( getAndroidHomeOrThrow ( ) ) ; } // Use any - Dandroid . sdk . platform from command line or < properties > < sdk . platform > . . .
chosenSdkPlatform = sdkPlatform ; } return new AndroidSdk ( chosenSdkPath , chosenSdkPlatform , buildToolsVersion ) ;


signature:
public class AbstractAndroidMojo { /** * TODO Replace this with a non - static method ( could even replace it with one of the methods above ) . */
public static File getLibraryUnpackDirectory ( File unpackedApkLibsDirectory , Artifact artifact ) { } }

implementation: return new File ( unpackedApkLibsDirectory . getAbsolutePath ( ) , artifact . getArtifactId ( ) ) ;


signature:
public class AbstractAndroidMojo { /** * < p > Returns the Android NDK to use . < / p >
 * < p > Current implementation looks for < code > & lt ; ndk & gt ; & lt ; path & gt ; < / code > configuration in pom , then System
 * property < code > android . ndk . path < / code > , then environment variable < code > ANDROID _ NDK _ HOME < / code > .
 * < p > This is where we collect all logic for how to lookup where it is , and which one to choose . The lookup is
 * based on available parameters . This method should be the only one you should need to look at to understand how
 * the Android NDK is chosen , and from where on disk . < / p >
 * @ return the Android NDK to use .
 * @ throws org . apache . maven . plugin . MojoExecutionException
 * if no Android NDK path configuration is available at all . */
protected AndroidNdk getAndroidNdk ( ) throws MojoExecutionException { } }

implementation:
File chosenNdkPath ; // There is no < ndk > tag in the pom .
if ( ndkPath != null ) { // - Dandroid . ndk . path is set on command line , or via < properties > < ndk . path > . . .
chosenNdkPath = ndkPath ; } else if ( ndk != null && ndk . getPath ( ) != null ) { chosenNdkPath = ndk . getPath ( ) ; } else { // No - Dandroid . ndk . path is set on command line , or via < properties > < ndk . path > . . .
chosenNdkPath = new File ( getAndroidNdkHomeOrThrow ( ) ) ; } return new AndroidNdk ( chosenNdkPath ) ;


signature:
public class AbstractAndroidMojo { /** * Copies the files contained within the source folder to the target folder .
 * The the target folder doesn ' t exist it will be created .
 * @ param sourceFolder Folder from which to copy the resources .
 * @ param targetFolder Folder to which to copy the files .
 * @ throws MojoExecutionException if the files cannot be copied . */
protected final void copyFolder ( File sourceFolder , File targetFolder ) throws MojoExecutionException { } }

implementation: copyFolder ( sourceFolder , targetFolder , TrueFileFilter . TRUE ) ;


signature:
public class UIAutomatorMojo { /** * Helper method to build a comma separated string from a list . Blank strings are filtered out
 * @ param lines
 * A list of strings
 * @ return Comma separated String from given list */
protected static String buildSpaceSeparatedString ( String [ ] lines ) { } }

implementation: if ( lines == null || lines . length == 0 ) { return null ; } return StringUtils . join ( lines , " " ) ;


signature:
public class DependencyResolver { /** * Returns the Set of APKLIB , AAR , APK ( direct or transitive ) dependencies of the supplied artifact .
 * The project is searched until artifact is found and then the library dependencies are looked for recursively .
 * @ param session MavenSession in which to resolve the artifacts .
 * @ param repositorySystem RepositorySystem with which to resolve the artifacts .
 * @ param artifact Artifact for whom to get the dependencies .
 * @ return Set of APK , APKLIB and AAR dependencies .
 * @ throws org . apache . maven . plugin . MojoExecutionException if it couldn ' t resolve any of the dependencies . */
public Set < Artifact > getLibraryDependenciesFor ( MavenSession session , RepositorySystem repositorySystem , Artifact artifact ) throws MojoExecutionException { } }

implementation:
// Set a filter that should only return interesting artifacts .
final ArtifactFilter filter = new ArtifactFilter ( ) { @ Override public boolean include ( Artifact found ) { final String type = found . getType ( ) ; return ( type . equals ( APKLIB ) || type . equals ( AAR ) || type . equals ( APK ) ) ; } } ; log . debug ( "MavenSession = " + session + "  repositorySystem = " + repositorySystem ) ; final ArtifactResolutionRequest request = new ArtifactResolutionRequest ( ) ; request . setArtifact ( artifact ) ; request . setResolveRoot ( false ) ; // Don ' t include source artifact in result
request . setResolveTransitively ( true ) ; // Include direct plus transitive dependencies .
request . setServers ( session . getRequest ( ) . getServers ( ) ) ; request . setMirrors ( session . getRequest ( ) . getMirrors ( ) ) ; request . setProxies ( session . getRequest ( ) . getProxies ( ) ) ; request . setLocalRepository ( session . getLocalRepository ( ) ) ; request . setRemoteRepositories ( session . getCurrentProject ( ) . getRemoteArtifactRepositories ( ) ) ; final ArtifactResolutionResult result = repositorySystem . resolve ( request ) ; final Set < Artifact > libraryDeps = new HashSet < Artifact > ( ) ; for ( final Artifact depArtifact : result . getArtifacts ( ) ) { if ( filter . include ( depArtifact ) ) { libraryDeps . add ( depArtifact ) ; } } return libraryDeps ;


signature:
public class ResourceClassGenerator { /** * Generates R java files those libraries that do not already have their R java in the compile classpath .
 * If we are generating an integration test APK and the APK under test has a reference to a library for which
 * it generated an R java , then we don ' t want to generate that R java again for the test APK because otherwise
 * Proguard will fail when building the test APK because of duplication of the R java in the compile classpath .
 * See { @ link com . android . builder . core . AndroidBuilder # processResources ( com . android . builder . internal . aapt . Aapt ,
 * com . android . builder . internal . aapt . AaptPackageConfig . Builder , boolean ) }
 * @ param libraries AAR libraries for which to generate R java files . */
public void generateLibraryRs ( final Set < Artifact > libraries ) { } }

implementation:
// list of all the symbol tables
final List < SymbolTable > symbolTables = new ArrayList < > ( libraries . size ( ) ) ; // For each dependency , load its symbol file .
for ( final Artifact lib : libraries ) { final File unpackedLibDirectory = mojo . getUnpackedLibFolder ( lib ) ; final File rFile = new File ( unpackedLibDirectory , "R.txt" ) ; if ( rFile . isFile ( ) ) { final File libManifestFile = new File ( unpackedLibDirectory , "AndroidManifest.xml" ) ; final String packageName = new DefaultManifestParser ( libManifestFile ) . getPackage ( ) ; if ( rJavaAlreadyExists ( packageName ) ) { log . info ( "Not creating R for " + packageName + " as it already exists" ) ; continue ; } log . info ( "Generating R for " + packageName + " at " + rFile ) ; SymbolTable libSymbols = SymbolIo . read ( rFile ) ; libSymbols = libSymbols . rename ( packageName , libSymbols . getTableName ( ) ) ; symbolTables . add ( libSymbols ) ; } } if ( symbolTables . isEmpty ( ) ) { return ; } // load the full resources values from the R . txt calculated for the project .
final File projectR = new File ( targetDirectory , "R.txt" ) ; final SymbolTable mainSymbols = SymbolIo . read ( projectR ) ; // now loop on all the package name , merge all the symbols to write , and write them
RGeneration . generateRForLibraries ( mainSymbols , symbolTables , genDirectory . getAbsoluteFile ( ) , false ) ;


signature:
public class DevicesMojo { /** * Display a list of attached devices .
 * @ throws MojoExecutionException
 * @ throws MojoFailureException */
public void execute ( ) throws MojoExecutionException , MojoFailureException { } }

implementation: doWithDevices ( new DeviceCallback ( ) { public void doWithDevice ( final IDevice device ) throws MojoExecutionException { getLog ( ) . info ( DeviceHelper . getDescriptiveNameWithStatus ( device ) ) ; } } ) ;


signature:
public class AarMojo { /** * Creates an appropriate aar / classes . jar that does not include R
 * @ return File which is the AAR classes jar .
 * @ throws MojoExecutionException */
protected File createAarClassesJar ( ) throws MojoExecutionException { } }

implementation: final File obfuscatedJarFile = new File ( obfuscatedJar ) ; if ( obfuscatedJarFile . exists ( ) ) { attachJar ( obfuscatedJarFile ) ; return obfuscatedJarFile ; } final File classesJar = new File ( targetDirectory , finalName + ".aar.classes.jar" ) ; try { JarArchiver jarArchiver = new JarArchiver ( ) ; jarArchiver . setDestFile ( classesJar ) ; jarArchiver . addDirectory ( projectOutputDirectory , classesJarIncludes , classesJarExcludes ) ; jarArchiver . createArchive ( ) ; attachJar ( classesJar ) ; return classesJar ; } catch ( ArchiverException e ) { throw new MojoExecutionException ( "ArchiverException while creating ." + classesJar + " file." , e ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "IOException while creating ." + classesJar + " file." , e ) ; }


signature:
public class AarMojo { /** * Makes sure the string ends with " / "
 * @ param prefix any string , or null .
 * @ return the prefix with a " / " at the end , never null . */
protected String endWithSlash ( String prefix ) { } }

implementation: prefix = StringUtils . defaultIfEmpty ( prefix , "/" ) ; if ( ! prefix . endsWith ( "/" ) ) { prefix = prefix + "/" ; } return prefix ;


signature:
public class AarMojo { /** * Adds a directory to a { @ link JarArchiver } with a directory prefix .
 * @ param zipArchiver ZipArchiver to use to archive the file .
 * @ param directory The directory to add .
 * @ param prefix An optional prefix for where in the Jar file the directory ' s contents should go .
 * @ param includeEmptyFolders Whether to include an entry for empty folder in the archive . */
protected void addDirectory ( ZipArchiver zipArchiver , File directory , String prefix , boolean includeEmptyFolders ) { } }

implementation: if ( directory != null && directory . exists ( ) ) { final DefaultFileSet fileSet = new DefaultFileSet ( ) ; fileSet . setPrefix ( endWithSlash ( prefix ) ) ; fileSet . setDirectory ( directory ) ; fileSet . setIncludingEmptyDirectories ( includeEmptyFolders ) ; zipArchiver . addFileSet ( fileSet ) ; getLog ( ) . debug ( "Added files from " + directory ) ; }


signature:
public class ApkMojo { /** * Creates the APK file using the internal APKBuilder .
 * @ param outputFile the output file
 * @ param dexFile the dex file
 * @ param zipArchive the classes folder
 * @ param sourceFolders the resources
 * @ param jarFiles the embedded java files
 * @ param nativeFolders the native folders
 * @ param signWithDebugKeyStore enables the signature of the APK using the debug key
 * @ throws MojoExecutionException if the APK cannot be created . */
private void doAPKWithAPKBuilder ( File outputFile , File dexFile , File zipArchive , Collection < File > sourceFolders , List < File > jarFiles , Collection < File > nativeFolders , boolean signWithDebugKeyStore ) throws MojoExecutionException { } }

implementation:
getLog ( ) . debug ( "Building APK with internal APKBuilder" ) ; // A when jack is running the classes directory will not get filled ( usually )
// so let ' s skip it if it wasn ' t created by something else
if ( projectOutputDirectory . exists ( ) || ! getJack ( ) . isEnabled ( ) ) { sourceFolders . add ( projectOutputDirectory ) ; } for ( Artifact artifact : filterArtifacts ( getRelevantCompileArtifacts ( ) , skipDependencies , artifactTypeSet . getIncludes ( ) , artifactTypeSet . getExcludes ( ) , artifactSet . getIncludes ( ) , artifactSet . getExcludes ( ) ) ) { getLog ( ) . debug ( "Found artifact for APK :" + artifact ) ; if ( extractDuplicates ) { try { computeDuplicateFiles ( artifact . getFile ( ) ) ; } catch ( Exception e ) { getLog ( ) . warn ( "Cannot compute duplicates files from " + artifact . getFile ( ) . getAbsolutePath ( ) , e ) ; } } jarFiles . add ( artifact . getFile ( ) ) ; } for ( File src : sourceFolders ) { computeDuplicateFilesInSource ( src ) ; } // Check duplicates .
if ( extractDuplicates ) { try { extractDuplicateFiles ( jarFiles , sourceFolders ) ; } catch ( IOException e ) { getLog ( ) . error ( "Could not extract duplicates to duplicate-resources.jar" , e ) ; } } try { final String debugKeyStore = signWithDebugKeyStore ? ApkBuilder . getDebugKeystore ( ) : null ; final ApkBuilder apkBuilder = new ApkBuilder ( outputFile , zipArchive , dexFile , debugKeyStore , null ) ; if ( apkDebug ) { apkBuilder . setDebugMode ( true ) ; } for ( File sourceFolder : sourceFolders ) { getLog ( ) . debug ( "Adding source folder : " + sourceFolder ) ; // Use ApkBuilder # addFile ( ) to explicitly add resource files so that we can add META - INF / services .
addResourcesFromFolder ( apkBuilder , sourceFolder ) ; } for ( File jarFile : jarFiles ) { boolean excluded = false ; if ( excludeJarResourcesPatterns != null ) { final String name = jarFile . getName ( ) ; getLog ( ) . debug ( "Checking " + name + " against patterns" ) ; for ( Pattern pattern : excludeJarResourcesPatterns ) { final Matcher matcher = pattern . matcher ( name ) ; if ( matcher . matches ( ) ) { getLog ( ) . debug ( "Jar " + name + " excluded by pattern " + pattern ) ; excluded = true ; break ; } else { getLog ( ) . debug ( "Jar " + name + " not excluded by pattern " + pattern ) ; } } } if ( excluded ) { continue ; } if ( jarFile . isDirectory ( ) ) { getLog ( ) . debug ( "Adding resources from jar folder : " + jarFile ) ; final String [ ] filenames = jarFile . list ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return PATTERN_JAR_EXT . matcher ( name ) . matches ( ) ; } } ) ; for ( String filename : filenames ) { final File innerJar = new File ( jarFile , filename ) ; getLog ( ) . debug ( "Adding resources from innerJar : " + innerJar ) ; apkBuilder . addResourcesFromJar ( innerJar ) ; } } else { getLog ( ) . debug ( "Adding resources from : " + jarFile ) ; apkBuilder . addResourcesFromJar ( jarFile ) ; } } addSecondaryDexes ( dexFile , apkBuilder ) ; for ( File nativeFolder : nativeFolders ) { getLog ( ) . debug ( "Adding native library : " + nativeFolder ) ; apkBuilder . addNativeLibraries ( nativeFolder ) ; } apkBuilder . sealApk ( ) ; } catch ( ApkCreationException | SealedApkException | IOException e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } catch ( DuplicateFileException e ) { final String msg = String . format ( "Duplicated file: %s, found in archive %s and %s" , e . getArchivePath ( ) , e . getFile1 ( ) , e . getFile2 ( ) ) ; throw new MojoExecutionException ( msg , e ) ; }


signature:
public class ApkMojo { /** * Collect all Files from Folder ( recursively ) that are not class files . */
private void collectFiles ( File folder , final List < File > collectedFiles ) { } }

implementation: folder . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File file ) { if ( file . isDirectory ( ) ) { collectFiles ( file , collectedFiles ) ; } else if ( file . isFile ( ) ) { if ( ! file . getName ( ) . endsWith ( ".class" ) ) { collectedFiles . add ( file ) ; } } return false ; } } ) ;


signature:
public class ApkMojo { /** * Adds all non - class files from folder , so that we can add META - INF / services resources . */
private void addResourcesFromFolder ( ApkBuilder builder , File folder ) throws SealedApkException , DuplicateFileException , ApkCreationException , IOException { } }

implementation: final int folderPathLength = folder . getCanonicalPath ( ) . length ( ) ; final List < File > resourceFiles = new ArrayList < > ( ) ; collectFiles ( folder , resourceFiles ) ; for ( final File resourceFile : resourceFiles ) { final String resourceName = resourceFile . getCanonicalPath ( ) . substring ( folderPathLength + 1 ) . replaceAll ( "\\\\" , "/" ) ; getLog ( ) . info ( "Adding resource " + resourceFile + " : " + resourceName ) ; builder . addFile ( resourceFile , resourceName ) ; }


signature:
public class ApkMojo { /** * Copies an input stream into an output stream but does not close the streams .
 * @ param in the input stream
 * @ param out the output stream
 * @ throws IOException if the stream cannot be copied */
private static void copyStreamWithoutClosing ( InputStream in , OutputStream out ) throws IOException { } }

implementation: final int bufferSize = 4096 ; byte [ ] b = new byte [ bufferSize ] ; int n ; while ( ( n = in . read ( b ) ) != - 1 ) { out . write ( b , 0 , n ) ; }


signature:
public class ApkMojo { /** * Copy the Ndk GdbServer into the architecture output folder if the folder exists but the GdbServer doesn ' t . */
private void copyGdbServer ( File destinationDirectory , String architecture ) throws MojoExecutionException { } }

implementation:
try { final File destDir = new File ( destinationDirectory , architecture ) ; if ( destDir . exists ( ) ) { // Copy the gdbserver binary to libs / < architecture > /
final File gdbServerFile = getAndroidNdk ( ) . getGdbServer ( architecture ) ; final File destFile = new File ( destDir , "gdbserver" ) ; if ( ! destFile . exists ( ) ) { getLog ( ) . debug ( "Copying gdbServer to " + destFile ) ; FileUtils . copyFile ( gdbServerFile , destFile ) ; } else { getLog ( ) . info ( "Note: gdbserver binary already exists at destination, will not copy over" ) ; } } } catch ( Exception e ) { getLog ( ) . error ( "Error while copying gdbserver: " + e . getMessage ( ) , e ) ; throw new MojoExecutionException ( "Error while copying gdbserver: " + e . getMessage ( ) , e ) ; }


signature:
public class ApkMojo { /** * Used to populated the { @ link # apkMetaInf } attribute via reflection . */
private MetaInf getDefaultMetaInf ( ) { } }

implementation:
// check for deprecated first
if ( apkMetaIncludes != null && apkMetaIncludes . length > 0 ) { return new MetaInf ( ) . include ( apkMetaIncludes ) ; } return this . pluginMetaInf ;


signature:
public class MonkeyMojo { /** * Actually plays tests .
 * @ throws MojoExecutionException
 * if exercising app threw an exception and isIgnoreTestFailures is false . .
 * @ throws MojoFailureException
 * if exercising app failed and isIgnoreTestFailures is false . */
protected void exerciseApp ( ) throws MojoExecutionException , MojoFailureException { } }

implementation: getLog ( ) . debug ( "Parsed values for Android Monkey invocation: " ) ; getLog ( ) . debug ( "seed:" + parsedSeed ) ; DeviceCallback instrumentationTestExecutor = new DeviceCallback ( ) { @ Override public void doWithDevice ( final IDevice device ) throws MojoExecutionException , MojoFailureException { String deviceLogLinePrefix = DeviceHelper . getDeviceLogLinePrefix ( device ) ; MonkeyTestRunner monkeyTestRunner = new MonkeyTestRunner ( parsedEventCount , device ) ; monkeyTestRunner . setRunName ( "ui monkey tests" ) ; if ( parsedSeed != null ) { monkeyTestRunner . setSeed ( parsedSeed ) ; } if ( parsedPercentTouch != null ) { monkeyTestRunner . setPercentTouch ( parsedPercentTouch ) ; } if ( parsedPercentMotion != null ) { monkeyTestRunner . setPercentTouch ( parsedPercentMotion ) ; } if ( parsedPercentTrackball != null ) { monkeyTestRunner . setPercentTrackball ( parsedPercentTrackball ) ; } if ( parsedPercentNav != null ) { monkeyTestRunner . setPercentNav ( parsedPercentNav ) ; } if ( parsedPercentMajorNav != null ) { monkeyTestRunner . setPercentMajorNav ( parsedPercentMajorNav ) ; } if ( parsedPercentSyskeys != null ) { monkeyTestRunner . setPercentSyskeys ( parsedPercentSyskeys ) ; } if ( parsedPercentAppswitch != null ) { monkeyTestRunner . setPercentAppswitch ( parsedPercentAppswitch ) ; } if ( parsedPercentAnyevent != null ) { monkeyTestRunner . setPercentAnyEvent ( parsedPercentAnyevent ) ; } if ( parsedPackages != null ) { monkeyTestRunner . setPackages ( parsedPackages ) ; } if ( parsedCategories != null ) { monkeyTestRunner . setCategories ( parsedCategories ) ; } monkeyTestRunner . setDebugNoEvents ( parsedDebugNoEvents ) ; monkeyTestRunner . setHprof ( parsedHprof ) ; monkeyTestRunner . setIgnoreCrashes ( parsedIgnoreCrashes ) ; monkeyTestRunner . setIgnoreTimeouts ( parsedIgnoreTimeouts ) ; monkeyTestRunner . setIgnoreSecurityExceptions ( parsedIgnoreSecurityExceptions ) ; monkeyTestRunner . setKillProcessAfterError ( parsedKillProcessAfterError ) ; monkeyTestRunner . setMonitorNativeCrash ( parsedMonitorNativeCrashes ) ; getLog ( ) . info ( deviceLogLinePrefix + "Running ui monkey tests" ) ; try { AndroidTestRunListener testRunListener = new AndroidTestRunListener ( device , getLog ( ) , parsedCreateReport , false , "" , "" , targetDirectory ) ; monkeyTestRunner . run ( testRunListener ) ; if ( testRunListener . hasFailuresOrErrors ( ) && ! isIgnoreTestFailures ( ) ) { throw new MojoFailureException ( deviceLogLinePrefix + "Tests failed on device." ) ; } if ( testRunListener . testRunFailed ( ) ) { throw new MojoFailureException ( deviceLogLinePrefix + "Test run failed to complete: " + testRunListener . getTestRunFailureCause ( ) ) ; } if ( testRunListener . threwException ( ) && ! isIgnoreTestFailures ( ) ) { throw new MojoFailureException ( deviceLogLinePrefix + testRunListener . getExceptionMessages ( ) ) ; } } catch ( TimeoutException e ) { throw new MojoExecutionException ( deviceLogLinePrefix + "timeout" , e ) ; } catch ( AdbCommandRejectedException e ) { throw new MojoExecutionException ( deviceLogLinePrefix + "adb command rejected" , e ) ; } catch ( ShellCommandUnresponsiveException e ) { throw new MojoExecutionException ( deviceLogLinePrefix + "shell command " + "unresponsive" , e ) ; } catch ( IOException e ) { throw new MojoExecutionException ( deviceLogLinePrefix + "IO problem" , e ) ; } } } ; doWithDevices ( instrumentationTestExecutor ) ;


signature:
public class D8Mojo { /** * Figure out the full path to the current java executable .
 * @ return the full path to the current java executable . */
private static File getJavaExecutable ( ) { } }

implementation: final String javaHome = System . getProperty ( "java.home" ) ; final String slash = File . separator ; return new File ( javaHome + slash + "bin" + slash + "java" ) ;


signature:
public class D8Mojo { /** * Adds a Java Resources directory ( typically " src / main / resources " ) to a { @ link JarArchiver } .
 * @ param jarArchiver
 * @ param javaResource
 * The Java resource to add . */
protected void addJavaResource ( JarArchiver jarArchiver , Resource javaResource ) { } }

implementation: if ( javaResource != null ) { final File javaResourceDirectory = new File ( javaResource . getDirectory ( ) ) ; if ( javaResourceDirectory . exists ( ) ) { final DefaultFileSet javaResourceFileSet = new DefaultFileSet ( ) ; javaResourceFileSet . setDirectory ( javaResourceDirectory ) ; javaResourceFileSet . setPrefix ( endWithSlash ( "src/main/resources" ) ) ; jarArchiver . addFileSet ( javaResourceFileSet ) ; } }


signature:
public class AndroidSdk { /** * Get the path for proguard . jar
 * @ return */
public String getProguardJarPath ( ) { } }

implementation: File directory = new File ( getToolsPath ( ) , "proguard" + File . separator + "lib" + File . separator ) ; File proguardJar = new File ( directory , "proguard.jar" ) ; if ( proguardJar . exists ( ) ) { return proguardJar . getAbsolutePath ( ) ; } throw new InvalidSdkException ( "Cannot find " + proguardJar ) ;


signature:
public class AndroidSdk { /** * Get the path for shrinkedAndroid . jar
 * @ return */
public String getShrinkedAndroidJarPath ( ) { } }

implementation: File shrinkedAndroidJar = new File ( getBuildToolsLibDirectoryPath ( ) , "shrinkedAndroid.jar" ) ; if ( shrinkedAndroidJar . exists ( ) ) { return shrinkedAndroidJar . getAbsolutePath ( ) ; } throw new InvalidSdkException ( "Cannot find " + shrinkedAndroidJar ) ;


signature:
public class AndroidSdk { /** * Get the path for build - tools lib directory
 * @ return */
public String getBuildToolsLibDirectoryPath ( ) { } }

implementation: File buildToolsLib = new File ( getBuildToolInfo ( ) . getLocation ( ) , "lib" ) ; if ( buildToolsLib . exists ( ) ) { return buildToolsLib . getAbsolutePath ( ) ; } throw new InvalidSdkException ( "Cannot find " + buildToolsLib ) ;


signature:
public class AndroidSdk { /** * Get the path for mainDexClasses . rules
 * @ return */
public String getMainDexClassesRulesPath ( ) { } }

implementation: File mainDexClassesRules = new File ( getBuildToolInfo ( ) . getLocation ( ) , "mainDexClasses.rules" ) ; if ( mainDexClassesRules . exists ( ) ) { return mainDexClassesRules . getAbsolutePath ( ) ; } throw new InvalidSdkException ( "Cannot find " + mainDexClassesRules ) ;


signature:
public class AndroidSdk { /** * Get the android tool path .
 * @ return */
public String getAndroidPath ( ) { } }

implementation: String cmd = "android" ; String ext = SdkConstants . currentPlatform ( ) == 2 ? ".bat" : "" ; return getPathForTool ( cmd + ext ) ;


signature:
public class AndroidSdk { /** * Resolves the android . jar from this SDK .
 * @ return a < code > File < / code > pointing to the android . jar file .
 * @ throws org . apache . maven . plugin . MojoExecutionException
 * if the file can not be resolved . */
public File getAndroidJar ( ) throws MojoExecutionException { } }

implementation: final String androidJarPath = androidTarget . getPath ( IAndroidTarget . ANDROID_JAR ) ; if ( androidJarPath == null ) { throw new MojoExecutionException ( "No AndroidJar found for " + androidTarget . getLocation ( ) ) ; } return new File ( androidJarPath ) ;


signature:
public class AndroidSdk { /** * This method returns the previously specified version . However , if none have been specified it returns the
 * " latest " version . */
public File getPlatform ( ) { } }

implementation: assertPathIsDirectory ( sdkPath ) ; final File platformsDirectory = new File ( sdkPath , PLATFORMS_FOLDER_NAME ) ; assertPathIsDirectory ( platformsDirectory ) ; final File platformDirectory ; if ( androidTarget == null ) { IAndroidTarget latestTarget = null ; AndroidTargetManager targetManager = sdkManager . getAndroidTargetManager ( progressIndicator ) ; for ( IAndroidTarget target : targetManager . getTargets ( progressIndicator ) ) { if ( target . isPlatform ( ) ) { if ( latestTarget == null || target . getVersion ( ) . getApiLevel ( ) > latestTarget . getVersion ( ) . getApiLevel ( ) ) { latestTarget = target ; } } } platformDirectory = new File ( latestTarget . getLocation ( ) ) ; } else { platformDirectory = new File ( androidTarget . getLocation ( ) ) ; } assertPathIsDirectory ( platformDirectory ) ; return platformDirectory ;


signature:
public class AndroidSdk { /** * Loads the SDK Tools version */
private void loadSDKToolsMajorVersion ( ) { } }

implementation: File propFile = new File ( sdkPath , "tools/" + SOURCE_PROPERTIES_FILENAME ) ; Properties properties = new Properties ( ) ; try { properties . load ( new FileInputStream ( propFile ) ) ; } catch ( IOException e ) { throw new InvalidSdkException ( "Error reading " + propFile . getAbsoluteFile ( ) ) ; } if ( properties . containsKey ( SDK_TOOLS_REVISION_PROPERTY ) ) { try { String versionString = properties . getProperty ( SDK_TOOLS_REVISION_PROPERTY ) ; String majorVersion ; if ( versionString . matches ( ".*[\\.| ].*" ) ) { String [ ] versions = versionString . split ( "[\\.| ]" ) ; majorVersion = versions [ 0 ] ; } else { majorVersion = versionString ; } sdkMajorVersion = Integer . parseInt ( majorVersion ) ; } catch ( NumberFormatException e ) { throw new InvalidSdkException ( "Error - The property '" + SDK_TOOLS_REVISION_PROPERTY + "' in the SDK source.properties file  number is not an Integer: " + properties . getProperty ( SDK_TOOLS_REVISION_PROPERTY ) ) ; } }


signature:
public class ApklibMojo { /** * Adds a Java Resources directory ( typically " src / main / resources " ) to a { @ link JarArchiver } .
 * @ param jarArchiver
 * @ param javaResource The Java resource to add .
 * @ param prefix An optional prefix for where in the Jar file the directory ' s contents should go .
 * @ throws IOException in case the resource path can not be resolved */
protected void addJavaResource ( JarArchiver jarArchiver , Resource javaResource , String prefix ) throws IOException { } }

implementation:
if ( javaResource != null ) { final File javaResourceDirectory = new File ( javaResource . getDirectory ( ) ) ; if ( javaResourceDirectory . exists ( ) ) { final String resourcePath = javaResourceDirectory . getCanonicalPath ( ) ; final String apkLibUnpackBasePath = getUnpackedLibsDirectory ( ) . getCanonicalPath ( ) ; // Don ' t include our dependencies ' resource dirs .
if ( ! resourcePath . startsWith ( apkLibUnpackBasePath ) ) { final DefaultFileSet javaResourceFileSet = new DefaultFileSet ( ) ; javaResourceFileSet . setDirectory ( javaResourceDirectory ) ; javaResourceFileSet . setPrefix ( endWithSlash ( prefix ) ) ; jarArchiver . addFileSet ( javaResourceFileSet ) ; } } }


signature:
public class ApklibMojo { /** * Adds a directory to a { @ link JarArchiver } with a directory prefix .
 * @ param jarArchiver
 * @ param directory The directory to add .
 * @ param prefix An optional prefix for where in the Jar file the directory ' s contents should go . */
protected void addDirectory ( JarArchiver jarArchiver , File directory , String prefix ) { } }

implementation:
if ( directory != null && directory . exists ( ) ) { final DefaultFileSet fileSet = new DefaultFileSet ( ) ; fileSet . setPrefix ( endWithSlash ( prefix ) ) ; fileSet . setDirectory ( directory ) ; // XXX : trying to avoid duplicated sources
fileSet . setExcludes ( new String [ ] { "**/R.java" , "**/BuildConfig.java" } ) ; jarArchiver . addFileSet ( fileSet ) ; getLog ( ) . debug ( "Added files from " + directory ) ; }


signature:
public class ApklibMojo { /** * Adds all shared libraries ( . so ) to a { @ link JarArchiver } under ' libs ' .
 * @ param jarArchiver The jarArchiver to add files to
 * @ param directory The directory to scan for . so files
 * @ param architecture The prefix for where in the jar the . so files will go . */
protected void addSharedLibraries ( JarArchiver jarArchiver , File directory , String architecture ) { } }

implementation: getLog ( ) . debug ( "Searching for shared libraries in " + directory ) ; File [ ] libFiles = directory . listFiles ( new FilenameFilter ( ) { public boolean accept ( final File dir , final String name ) { return name . startsWith ( "lib" ) && name . endsWith ( ".so" ) ; } } ) ; if ( libFiles != null ) { for ( File libFile : libFiles ) { String dest = NATIVE_LIBRARIES_FOLDER + "/" + architecture + "/" + libFile . getName ( ) ; getLog ( ) . debug ( "Adding " + libFile + " as " + dest ) ; jarArchiver . addFile ( libFile , dest ) ; } }


signature:
public class ApklibMojo { /** * Generates an intermediate apk file ( actually . ap _ ) containing the resources and assets .
 * @ throws MojoExecutionException */
private void generateIntermediateApk ( ) throws MojoExecutionException { } }

implementation:
CommandExecutor executor = CommandExecutor . Factory . createDefaultCommmandExecutor ( ) ; executor . setLogger ( this . getLog ( ) ) ; File [ ] overlayDirectories = getResourceOverlayDirectories ( ) ; File androidJar = getAndroidSdk ( ) . getAndroidJar ( ) ; File outputFile = new File ( targetDirectory , finalName + ".ap_" ) ; List < File > dependencyArtifactResDirectoryList = new ArrayList < File > ( ) ; for ( Artifact libraryArtifact : getTransitiveDependencyArtifacts ( APKLIB , AAR ) ) { final File apklibResDirectory = getUnpackedLibResourceFolder ( libraryArtifact ) ; if ( apklibResDirectory . exists ( ) ) { dependencyArtifactResDirectoryList . add ( apklibResDirectory ) ; } } AaptCommandBuilder commandBuilder = AaptCommandBuilder . packageResources ( getLog ( ) ) . forceOverwriteExistingFiles ( ) . setPathToAndroidManifest ( destinationManifestFile ) . addResourceDirectoriesIfExists ( overlayDirectories ) . addResourceDirectoryIfExists ( resourceDirectory ) . addResourceDirectoriesIfExists ( dependencyArtifactResDirectoryList ) . autoAddOverlay ( ) // NB aapt only accepts a single assets parameter - combinedAssets is a merge of all assets
. addRawAssetsDirectoryIfExists ( combinedAssets ) . addExistingPackageToBaseIncludeSet ( androidJar ) . setOutputApkFile ( outputFile ) . addConfigurations ( configurations ) . setVerbose ( aaptVerbose ) ; getLog ( ) . debug ( getAndroidSdk ( ) . getAaptPath ( ) + " " + commandBuilder . toString ( ) ) ; getLog ( ) . info ( "Generating apklib" ) ; try { executor . setCaptureStdOut ( true ) ; List < String > commands = commandBuilder . build ( ) ; executor . executeCommand ( getAndroidSdk ( ) . getAaptPath ( ) , commands , project . getBasedir ( ) , false ) ; } catch ( ExecutionException e ) { throw new MojoExecutionException ( "" , e ) ; }


signature:
public class GenerateSourcesMojo { /** * Generates the sources .
 * @ throws MojoExecutionException if it fails .
 * @ throws MojoFailureException if it fails . */
public void execute ( ) throws MojoExecutionException , MojoFailureException { } }

implementation:
// If the current POM isn ' t an Android - related POM , then don ' t do
// anything . This helps work with multi - module projects .
if ( ! isCurrentProjectAndroid ( ) ) { return ; } validateStandardLocations ( ) ; try { targetDirectory . mkdirs ( ) ; copyManifest ( ) ; // Check for a deprecated AAR > APKLIB artifact combination
if ( warnOnApklibDependencies ) { checkForApklibDependencies ( ) ; } // TODO Do we really want to continue supporting APKSOURCES ? How long has it been deprecated
extractSourceDependencies ( ) ; // Extract the apklib and aar dependencies into unpacked - libs so that they can be referenced in the build .
extractLibraryDependencies ( ) ; // Copy project assets to combinedAssets so that aapt has a single assets folder to load .
copyFolder ( assetsDirectory , combinedAssets ) ; final String [ ] relativeAidlFileNames1 = findRelativeAidlFileNames ( aidlSourceDirectory ) ; final String [ ] relativeAidlFileNames2 = findRelativeAidlFileNames ( extractedDependenciesJavaSources ) ; final Map < String , String [ ] > relativeApklibAidlFileNames = new HashMap < String , String [ ] > ( ) ; if ( ! isInstrumentationTest ( ) ) { // Only add transitive APKLIB deps if we are building an APK and not an instrumentation test apk .
for ( Artifact artifact : getTransitiveDependencyArtifacts ( APKLIB ) ) { final File libSourceFolder = getUnpackedApkLibSourceFolder ( artifact ) ; final String [ ] apklibAidlFiles = findRelativeAidlFileNames ( libSourceFolder ) ; relativeApklibAidlFileNames . put ( artifact . getId ( ) , apklibAidlFiles ) ; } } checkPackagesForDuplicates ( ) ; checkForConflictingLayouts ( ) ; generateR ( ) ; generateBuildConfig ( ) ; // When compiling AIDL for this project ,
// make sure we compile AIDL for dependencies as well .
// This is so project A , which depends on project B , can
// use AIDL info from project B in its own AIDL
final Map < File , String [ ] > files = new HashMap < File , String [ ] > ( ) ; files . put ( aidlSourceDirectory , relativeAidlFileNames1 ) ; files . put ( extractedDependenciesJavaSources , relativeAidlFileNames2 ) ; if ( ! isInstrumentationTest ( ) ) { // Only add transitive APKLIB deps if we are building an APK and not an instrumentation test apk .
for ( Artifact artifact : getTransitiveDependencyArtifacts ( APKLIB ) ) { final File unpackedLibSourceFolder = getUnpackedApkLibSourceFolder ( artifact ) ; files . put ( unpackedLibSourceFolder , relativeApklibAidlFileNames . get ( artifact . getId ( ) ) ) ; } } generateAidlFiles ( files ) ; } catch ( MojoExecutionException e ) { getLog ( ) . error ( "Error when generating sources." , e ) ; throw e ; }


signature:
public class GenerateSourcesMojo { /** * Performs some level of validation on the configured files and folders in light of the change
 * to AndroidStudio / Gradle style folder structures instead of the original Ant / Eclipse structures .
 * Essentially we will be noisy if we see an artifact that looks like before
 * Android Maven Plugin 4 and is not explicitly configured . */
private void validateStandardLocations ( ) throws MojoExecutionException { } }

implementation: boolean hasNonStandardStructure = false ; if ( androidManifestFilePre4 . exists ( ) && ! androidManifestFilePre4 . equals ( androidManifestFile ) ) { getLog ( ) . warn ( "Non-standard location of AndroidManifest.xml file found, but not configured:\n " + androidManifestFilePre4 + "\nMove to the standard location src/main/AndroidManifest.xml\n" + "Or configure androidManifestFile. \n" ) ; hasNonStandardStructure = true ; } if ( resourceDirectoryPre4 . exists ( ) && ! resourceDirectoryPre4 . equals ( resourceDirectory ) ) { getLog ( ) . warn ( "Non-standard location of Android res folder found, but not configured:\n " + resourceDirectoryPre4 + "\nMove to the standard location src/main/res/\n" + "Or configure resourceDirectory. \n" ) ; hasNonStandardStructure = true ; } if ( assetsDirectoryPre4 . exists ( ) && ! assetsDirectoryPre4 . equals ( assetsDirectory ) ) { getLog ( ) . warn ( "Non-standard location assets folder found, but not configured:\n " + assetsDirectoryPre4 + "\nMove to the standard location src/main/assets/\n" + "Or configure assetsDirectory. \n" ) ; hasNonStandardStructure = true ; } if ( nativeLibrariesDirectoryPre4 . exists ( ) && ! nativeLibrariesDirectoryPre4 . equals ( nativeLibrariesDirectory ) ) { getLog ( ) . warn ( "Non-standard location native libs folder found, but not configured:\n " + nativeLibrariesDirectoryPre4 + "\nMove to the standard location src/main/libs/\n" + "Or configure nativeLibrariesDirectory. \n" ) ; hasNonStandardStructure = true ; } if ( hasNonStandardStructure && failOnNonStandardStructure ) { throw new MojoExecutionException ( "\n\nFound files or folders in non-standard locations in the project!\n" + "....This might be a side-effect of a migration to Android Maven Plugin 4+.\n" + "....Please observe the warnings for specific files and folders above.\n" + "....Ideally you should restructure your project.\n" + "....Alternatively add explicit configuration overrides for files or folders.\n" + "....Finally you could set failOnNonStandardStructure to false, potentially " + "resulting in other failures.\n\n\n" ) ; }


signature:
public class GenerateSourcesMojo { /** * Copy the AndroidManifest . xml from androidManifestFile to destinationManifestFile
 * @ throws MojoExecutionException */
protected void copyManifest ( ) throws MojoExecutionException { } }

implementation: getLog ( ) . debug ( "copyManifest: " + androidManifestFile + " -> " + destinationManifestFile ) ; if ( androidManifestFile == null ) { getLog ( ) . debug ( "Manifest copying disabled. Using default manifest only" ) ; return ; } try { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; Document doc = db . parse ( androidManifestFile ) ; Source source = new DOMSource ( doc ) ; TransformerFactory xfactory = TransformerFactory . newInstance ( ) ; Transformer xformer = xfactory . newTransformer ( ) ; xformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "yes" ) ; FileWriter writer = null ; try { destinationManifestFile . getParentFile ( ) . mkdirs ( ) ; writer = new FileWriter ( destinationManifestFile , false ) ; if ( doc . getXmlEncoding ( ) != null && doc . getXmlVersion ( ) != null ) { String xmldecl = String . format ( "<?xml version=\"%s\" encoding=\"%s\"?>%n" , doc . getXmlVersion ( ) , doc . getXmlEncoding ( ) ) ; writer . write ( xmldecl ) ; } Result result = new StreamResult ( writer ) ; xformer . transform ( source , result ) ; getLog ( ) . info ( "Manifest copied from " + androidManifestFile + " to " + destinationManifestFile ) ; } finally { IOUtils . closeQuietly ( writer ) ; } } catch ( Exception e ) { getLog ( ) . error ( "Error during copyManifest" ) ; throw new MojoExecutionException ( "Error during copyManifest" , e ) ; }


signature:
public class GenerateSourcesMojo { /** * Extract the source dependencies .
 * @ throws MojoExecutionException if it fails . */
protected void extractSourceDependencies ( ) throws MojoExecutionException { } }

implementation: for ( Artifact artifact : getDirectDependencyArtifacts ( ) ) { String type = artifact . getType ( ) ; if ( type . equals ( APKSOURCES ) ) { getLog ( ) . debug ( "Detected apksources dependency " + artifact + " with file " + artifact . getFile ( ) + ". Will resolve and extract..." ) ; final File apksourcesFile = resolveArtifactToFile ( artifact ) ; getLog ( ) . debug ( "Extracting " + apksourcesFile + "..." ) ; extractApksources ( apksourcesFile ) ; } } if ( extractedDependenciesJavaResources . exists ( ) ) { projectHelper . addResource ( project , extractedDependenciesJavaResources . getAbsolutePath ( ) , null , null ) ; project . addCompileSourceRoot ( extractedDependenciesJavaSources . getAbsolutePath ( ) ) ; }


signature:
public class GenerateSourcesMojo { /** * Extracts ApkLib and adds the assets and apklib sources and resources to the build . */
private void extractApklib ( Artifact apklibArtifact ) throws MojoExecutionException { } }

implementation:
getUnpackedLibHelper ( ) . extractApklib ( apklibArtifact ) ; // Copy the assets to the the combinedAssets folder .
// Add the apklib source and resource to the compile .
// NB apklib sources are added to compileSourceRoot because we may need to compile against them .
// This means the apklib classes will be compiled into target / classes and packaged with this build .
copyFolder ( getUnpackedLibAssetsFolder ( apklibArtifact ) , combinedAssets ) ; final File apklibSourceFolder = getUnpackedApkLibSourceFolder ( apklibArtifact ) ; final List < String > resourceExclusions = Arrays . asList ( "**/*.java" , "**/*.aidl" ) ; projectHelper . addResource ( project , apklibSourceFolder . getAbsolutePath ( ) , null , resourceExclusions ) ; project . addCompileSourceRoot ( apklibSourceFolder . getAbsolutePath ( ) ) ;


signature:
public class GenerateSourcesMojo { /** * Extracts AarLib and if this is an APK build then adds the assets and resources to the build . */
private void extractAarLib ( Artifact aarArtifact ) throws MojoExecutionException { } }

implementation:
getUnpackedLibHelper ( ) . extractAarLib ( aarArtifact ) ; // Copy the assets to the the combinedAssets folder , but only if an APK build .
// Ie we only want to package assets that we own .
// Assets should only live within their owners or the final APK .
if ( isAPKBuild ( ) ) { copyFolder ( getUnpackedLibAssetsFolder ( aarArtifact ) , combinedAssets ) ; } // Aar lib resources should only be included if we are building an apk .
// So we need to extract them into a folder that we then add to the resource classpath .
if ( isAPKBuild ( ) ) { // ( If we are including SYSTEM _ SCOPE artifacts when considering resources for APK packaging )
// then adding the AAR resources to the project would have them added twice .
getLog ( ) . debug ( "Not adding AAR resources to resource classpath : " + aarArtifact ) ; }


signature:
public class GenerateSourcesMojo { /** * Copies a dependent APK jar over the top of the placeholder created for it in AarMavenLifeCycleParticipant .
 * This is necessary because we need the classes of the APK added to the compile classpath .
 * NB APK dependencies are uncommon as they should really only be used in a project that tests an apk .
 * @ param artifact APK dependency for this project whose classes will be copied over . */
private void extractApkClassesJar ( Artifact artifact ) throws MojoExecutionException { } }

implementation: final File apkClassesJar = getUnpackedLibHelper ( ) . getJarFileForApk ( artifact ) ; final File unpackedClassesJar = getUnpackedLibHelper ( ) . getUnpackedClassesJar ( artifact ) ; try { FileUtils . copyFile ( apkClassesJar , unpackedClassesJar ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Could not copy APK classes jar " + apkClassesJar + " to " + unpackedClassesJar , e ) ; } getLog ( ) . debug ( "Copied APK classes jar into compile classpath : " + unpackedClassesJar ) ;


signature:
public class GenerateSourcesMojo { /** * Traverses the list of project dependencies looking for & quot ; AAR depends on APKLIB & quot ; artifact combination
 * that has been deprecated . For each occurrence of an AAR artifact with APKLIB direct or transitive dependency ,
 * produces a warning message to inform the user . Future plugin versions may default to skipping or not handling
 * unsupported artifacts during build lifecycle .
 * @ throws MojoExecutionException */
private void checkForApklibDependencies ( ) throws MojoExecutionException { } }

implementation: final boolean isAarBuild = project . getPackaging ( ) . equals ( AAR ) ; final DependencyResolver dependencyResolver = getDependencyResolver ( ) ; final Set < Artifact > allArtifacts = project . getArtifacts ( ) ; Set < Artifact > dependencyArtifacts = getArtifactResolverHelper ( ) . getFilteredArtifacts ( allArtifacts ) ; boolean foundApklib = false ; for ( Artifact artifact : dependencyArtifacts ) { final String type = artifact . getType ( ) ; if ( type . equals ( APKLIB ) && isAarBuild ) { getLog ( ) . warn ( "Detected APKLIB transitive dependency: " + artifact . getId ( ) ) ; foundApklib = true ; } else if ( type . equals ( AAR ) ) { final Set < Artifact > dependencies = dependencyResolver . getLibraryDependenciesFor ( session , repositorySystem , artifact ) ; for ( Artifact dependency : dependencies ) { if ( dependency . getType ( ) . equals ( APKLIB ) ) { getLog ( ) . warn ( "Detected " + artifact . getId ( ) + " that depends on APKLIB: " + dependency . getId ( ) ) ; foundApklib = true ; } } } } if ( foundApklib ) { getLog ( ) . warn ( "AAR libraries should not depend or include APKLIB artifacts.\n" + "APKLIBs have been deprecated and the combination of the two may yield unexpected results.\n" + "Check the problematic AAR libraries for newer versions that use AAR packaging." ) ; }


signature:
public class GenerateSourcesMojo { /** * Checks packages in AndroidManifest . xml file of project and all dependent libraries for duplicates .
 * < p > Generate warning if duplicates presents .
 * < p > ( in case of packages similarity R . java and BuildConfig files will be overridden )
 * @ throws MojoExecutionException */
private void checkPackagesForDuplicates ( ) throws MojoExecutionException { } }

implementation:
Set < Artifact > dependencyArtifacts = getTransitiveDependencyArtifacts ( AAR , APKLIB ) ; if ( dependencyArtifacts . isEmpty ( ) ) { // if no AAR or APKLIB dependencies presents than only one package presents
return ; } Map < String , Set < Artifact > > packageCompareMap = getPackageCompareMap ( dependencyArtifacts ) ; List < String > duplicatesMessageList = new ArrayList < String > ( ) ; for ( Map . Entry < String , Set < Artifact > > entry : packageCompareMap . entrySet ( ) ) { Set < Artifact > artifacts = entry . getValue ( ) ; if ( artifacts != null && artifacts . size ( ) > 1 ) { StringBuilder messageBuilder = new StringBuilder ( ) ; for ( Artifact item : artifacts ) { messageBuilder . append ( messageBuilder . length ( ) > 0 ? ", " : "    [" ) . append ( item . getArtifactId ( ) ) ; } messageBuilder . append ( "] have similar package='" ) . append ( entry . getKey ( ) ) . append ( "'" ) ; duplicatesMessageList . add ( messageBuilder . toString ( ) ) ; } } if ( ! duplicatesMessageList . isEmpty ( ) ) { List < String > messageList = new ArrayList < String > ( ) ; messageList . add ( "" ) ; messageList . add ( "Duplicate packages detected in AndroidManifest.xml files" ) ; messageList . add ( "" ) ; messageList . add ( "Such scenario generally means that the build will fail with a compilation error due to" + " missing resources in R file." ) ; messageList . add ( "You should consider renaming some of the duplicate packages listed below" + " to avoid the conflict." ) ; messageList . add ( "" ) ; messageList . add ( "Conflicting artifacts:" ) ; messageList . addAll ( duplicatesMessageList ) ; messageList . add ( "" ) ; if ( failOnDuplicatePackages ) { StringBuilder builder = new StringBuilder ( ) ; for ( String line : messageList ) { builder . append ( line ) ; builder . append ( "\n" ) ; } builder . append ( "\n" ) ; builder . append ( "You can downgrade the failure to a warning " ) ; builder . append ( "by setting the 'failOnDuplicatePackages' plugin property to false." ) ; throw new MojoExecutionException ( builder . toString ( ) ) ; } for ( String messageLine : messageList ) { getLog ( ) . warn ( messageLine ) ; } }


signature:
public class GenerateSourcesMojo { /** * Looks for dependencies that have a layout file with the same name as either one of the project layout files
 * or one of the other dependencies . If such a duplicate occurs then it will fail the build or generate a warning
 * depending upon the value of the < strong > failOnConflictingLayouts < / strong > build parameter .
 * @ throws MojoExecutionException */
private void checkForConflictingLayouts ( ) throws MojoExecutionException { } }

implementation:
final ConflictingLayoutDetector detector = new ConflictingLayoutDetector ( ) ; // Add layout files for this project
final FileRetriever retriever = new FileRetriever ( "layout*/*.xml" ) ; detector . addLayoutFiles ( getAndroidManifestPackageName ( ) , retriever . getFileNames ( resourceDirectory ) ) ; // Add layout files for all dependencies .
for ( final Artifact dependency : getTransitiveDependencyArtifacts ( AAR , APKLIB ) ) { final String packageName = extractPackageNameFromAndroidArtifact ( dependency ) ; final String [ ] layoutFiles = retriever . getFileNames ( getUnpackedLibResourceFolder ( dependency ) ) ; detector . addLayoutFiles ( packageName , layoutFiles ) ; } final Collection < ConflictingLayout > conflictingLayouts = detector . getConflictingLayouts ( ) ; getLog ( ) . debug ( "checkConflictingLayouts - conflicts : " + conflictingLayouts ) ; if ( ! conflictingLayouts . isEmpty ( ) ) { final List < String > sb = new ArrayList < String > ( ) ; sb . add ( "" ) ; sb . add ( "" ) ; sb . add ( "Duplicate layout files have been detected across more than one Android package." ) ; sb . add ( "" ) ; sb . add ( "Such a scenario generally means that the build will fail with a compilation error due to" ) ; sb . add ( "missing resource files. You should consider renaming some of the layout files listed below" ) ; sb . add ( "to avoid the conflict." ) ; sb . add ( "" ) ; sb . add ( "However, if you believe you know better, then you can downgrade the failure to a warning" ) ; sb . add ( "by setting the failOnConflictingLayouts plugin property to false." ) ; sb . add ( "But you really don't want to do that." ) ; sb . add ( "" ) ; sb . add ( "Conflicting Layouts:" ) ; for ( final ConflictingLayout layout : conflictingLayouts ) { sb . add ( "    " + layout . getLayoutFileName ( ) + "  packages=" + layout . getPackageNames ( ) . toString ( ) ) ; } sb . add ( "" ) ; if ( failOnConflictingLayouts ) { final StringBuilder builder = new StringBuilder ( ) ; for ( final String line : sb ) { builder . append ( line ) ; builder . append ( "\n" ) ; } throw new MojoExecutionException ( builder . toString ( ) ) ; } for ( final String line : sb ) { getLog ( ) . warn ( line ) ; } }


signature:
public class GenerateSourcesMojo { /** * Provides map with all provided dependencies or project itself grouped by package name
 * @ param dependencyArtifacts artifacts that should be grouped by package name
 * @ return map of with package names ( String ) and sets of artifacts ( Set < Artifact > )
 * that have similar package names
 * @ throws MojoExecutionException */
Map < String , Set < Artifact > > getPackageCompareMap ( Set < Artifact > dependencyArtifacts ) throws MojoExecutionException { } }

implementation: if ( dependencyArtifacts == null ) { throw new IllegalArgumentException ( "dependencies must be initialized" ) ; } Map < String , Set < Artifact > > packageCompareMap = new HashMap < String , Set < Artifact > > ( ) ; Set < Artifact > artifactSet = new HashSet < Artifact > ( ) ; artifactSet . add ( project . getArtifact ( ) ) ; packageCompareMap . put ( getAndroidManifestPackageName ( ) , artifactSet ) ; for ( Artifact artifact : dependencyArtifacts ) { String libPackage = extractPackageNameFromAndroidArtifact ( artifact ) ; Set < Artifact > artifacts = packageCompareMap . get ( libPackage ) ; if ( artifacts == null ) { artifacts = new HashSet < Artifact > ( ) ; packageCompareMap . put ( libPackage , artifacts ) ; } artifacts . add ( artifact ) ; } return packageCompareMap ;


signature:
public class GenerateSourcesMojo { /** * Generate correct R . java for apklibs dependencies of a current project
 * @ throws MojoExecutionException */
private void generateCorrectRJavaForApklibDependencies ( ResourceClassGenerator resourceGenerator ) throws MojoExecutionException { } }

implementation:
getLog ( ) . debug ( "" ) ; getLog ( ) . debug ( "#generateCorrectRJavaFoApklibDeps" ) ; // Generate R . java for apklibs
// Compatibility with Apklib which isn ' t present in AndroidBuilder
getLog ( ) . debug ( "Generating Rs for apklib deps of project " + project . getArtifact ( ) ) ; final Set < Artifact > apklibDependencies = getTransitiveDependencyArtifacts ( APKLIB ) ; for ( final Artifact artifact : apklibDependencies ) { getLog ( ) . debug ( "Generating apklib R.java for " + artifact . getArtifactId ( ) + "..." ) ; generateRForApkLibDependency ( artifact ) ; } // Generate corrected R . java for APKLIB dependencies , but only if this is an APK build .
if ( ! apklibDependencies . isEmpty ( ) && APK . equals ( project . getArtifact ( ) . getType ( ) ) ) { // Generate R . java for each APKLIB based on R . txt
getLog ( ) . debug ( "" ) ; getLog ( ) . debug ( "Rewriting R files for APKLIB dependencies : " + apklibDependencies ) ; resourceGenerator . generateLibraryRs ( apklibDependencies ) ; }


signature:
public class GenerateSourcesMojo { /** * Generate correct R . java for aar dependencies of a current project
 * @ throws MojoExecutionException if it could not generate the R java for one of the libraries . */
private void generateCorrectRJavaForAarDependencies ( ResourceClassGenerator resourceGenerator ) throws MojoExecutionException { } }

implementation:
// Generate corrected R . java for AAR dependencies .
final Set < Artifact > aarLibraries = getTransitiveDependencyArtifacts ( AAR ) ; if ( ! aarLibraries . isEmpty ( ) ) { // Generate R . java for each AAR based on R . txt
getLog ( ) . debug ( "Generating R file for AAR dependencies" ) ; resourceGenerator . generateLibraryRs ( aarLibraries ) ; }


signature:
public class GenerateSourcesMojo { /** * Executes aapt to generate the R class for the given apklib .
 * @ param apklibArtifact apklib for which to generate the R class .
 * @ throws MojoExecutionException if it fails . */
private void generateRForApkLibDependency ( Artifact apklibArtifact ) throws MojoExecutionException { } }

implementation:
final File unpackDir = getUnpackedLibFolder ( apklibArtifact ) ; getLog ( ) . debug ( "Generating incomplete R file for apklib: " + apklibArtifact . getGroupId ( ) + ":" + apklibArtifact . getArtifactId ( ) ) ; final File apklibManifest = new File ( unpackDir , "AndroidManifest.xml" ) ; final File apklibResDir = new File ( unpackDir , "res" ) ; List < File > dependenciesResDirectories = new ArrayList < File > ( ) ; final Set < Artifact > apklibDeps = getDependencyResolver ( ) . getLibraryDependenciesFor ( this . session , this . repositorySystem , apklibArtifact ) ; getLog ( ) . debug ( "apklib=" + apklibArtifact + "  dependencies=" + apklibDeps ) ; for ( Artifact dependency : apklibDeps ) { // Add in the resources that are dependencies of the apklib .
final String extension = dependency . getType ( ) ; final File dependencyResDir = getUnpackedLibResourceFolder ( dependency ) ; if ( ( extension . equals ( APKLIB ) || extension . equals ( AAR ) ) && dependencyResDir . exists ( ) ) { dependenciesResDirectories . add ( dependencyResDir ) ; } } // Create combinedAssets for this apklib dependency - can ' t have multiple - A args
final File apklibCombAssets = new File ( getUnpackedLibFolder ( apklibArtifact ) , "combined-assets" ) ; for ( Artifact dependency : apklibDeps ) { // Accumulate assets for dependencies of the apklib ( if they exist ) .
final String extension = dependency . getType ( ) ; final File dependencyAssetsDir = getUnpackedLibAssetsFolder ( dependency ) ; if ( ( extension . equals ( APKLIB ) || extension . equals ( AAR ) ) ) { copyFolder ( dependencyAssetsDir , apklibCombAssets ) ; } } // Overlay the apklib dependency assets ( if they exist )
final File apkLibAssetsDir = getUnpackedLibAssetsFolder ( apklibArtifact ) ; copyFolder ( apkLibAssetsDir , apklibCombAssets ) ; final CommandExecutor executor = CommandExecutor . Factory . createDefaultCommmandExecutor ( ) ; executor . setLogger ( getLog ( ) ) ; final AaptCommandBuilder commandBuilder = AaptCommandBuilder . packageResources ( getLog ( ) ) . makeResourcesNonConstant ( ) . makePackageDirectories ( ) . setResourceConstantsFolder ( genDirectory ) . generateRIntoPackage ( extractPackageNameFromAndroidManifest ( apklibManifest ) ) . setPathToAndroidManifest ( apklibManifest ) . addResourceDirectoryIfExists ( apklibResDir ) . addResourceDirectoriesIfExists ( dependenciesResDirectories ) . autoAddOverlay ( ) . addRawAssetsDirectoryIfExists ( apklibCombAssets ) . addExistingPackageToBaseIncludeSet ( getAndroidSdk ( ) . getAndroidJar ( ) ) . addConfigurations ( configurations ) . setVerbose ( aaptVerbose ) . addExtraArguments ( aaptExtraArgs ) // We need to generate R . txt for all projects as it needs to be consumed when generating R class .
// It also needs to be consumed when packaging aar .
. generateRTextFile ( unpackDir ) ; getLog ( ) . debug ( getAndroidSdk ( ) . getAaptPath ( ) + " " + commandBuilder . toString ( ) ) ; try { executor . setCaptureStdOut ( true ) ; final List < String > commands = commandBuilder . build ( ) ; executor . executeCommand ( getAndroidSdk ( ) . getAaptPath ( ) , commands , project . getBasedir ( ) , false ) ; } catch ( ExecutionException e ) { throw new MojoExecutionException ( "" , e ) ; }


signature:
public class GenerateSourcesMojo { /** * Check if given artifact includes a matching BuildConfig class
 * @ throws MojoExecutionException */
private boolean isBuildConfigPresent ( Artifact artifact ) throws MojoExecutionException { } }

implementation: String depPackageName = extractPackageNameFromAndroidArtifact ( artifact ) ; return isBuildConfigPresent ( artifact , depPackageName ) ;


signature:
public class GenerateSourcesMojo { /** * Check whether the artifact includes a BuildConfig located in a given package .
 * @ param artifact an AAR artifact to look for BuildConfig in
 * @ param packageName BuildConfig package name
 * @ throws MojoExecutionException */
private boolean isBuildConfigPresent ( Artifact artifact , String packageName ) throws MojoExecutionException { } }

implementation: try { JarFile jar = new JarFile ( getUnpackedAarClassesJar ( artifact ) ) ; JarEntry entry = jar . getJarEntry ( packageName . replace ( '.' , '/' ) + "/BuildConfig.class" ) ; return ( entry != null ) ; } catch ( IOException e ) { getLog ( ) . error ( "Error generating BuildConfig " , e ) ; throw new MojoExecutionException ( "Error generating BuildConfig" , e ) ; }


signature:
public class GenerateSourcesMojo { /** * Given a map of source directories to list of AIDL ( relative ) filenames within each ,
 * runs the AIDL compiler for each , such that all source directories are available to
 * the AIDL compiler .
 * @ param files Map of source directory File instances to the relative paths to all AIDL files within
 * @ throws MojoExecutionException If the AIDL compiler fails */
private void generateAidlFiles ( Map < File /* sourceDirectory */
, String [ ] /* relativeAidlFileNames */
> files ) throws MojoExecutionException { } }

implementation: List < String > protoCommands = new ArrayList < String > ( ) ; protoCommands . add ( "-p" + getAndroidSdk ( ) . getPathForFrameworkAidl ( ) ) ; genDirectoryAidl . mkdirs ( ) ; getLog ( ) . info ( "Adding AIDL gen folder to compile classpath: " + genDirectoryAidl ) ; project . addCompileSourceRoot ( genDirectoryAidl . getPath ( ) ) ; Set < File > sourceDirs = files . keySet ( ) ; for ( File sourceDir : sourceDirs ) { protoCommands . add ( "-I" + sourceDir ) ; } for ( File sourceDir : sourceDirs ) { for ( String relativeAidlFileName : files . get ( sourceDir ) ) { File targetDirectory = new File ( genDirectoryAidl , new File ( relativeAidlFileName ) . getParent ( ) ) ; targetDirectory . mkdirs ( ) ; final String shortAidlFileName = new File ( relativeAidlFileName ) . getName ( ) ; final String shortJavaFileName = shortAidlFileName . substring ( 0 , shortAidlFileName . lastIndexOf ( "." ) ) + ".java" ; final File aidlFileInSourceDirectory = new File ( sourceDir , relativeAidlFileName ) ; List < String > commands = new ArrayList < String > ( protoCommands ) ; commands . add ( aidlFileInSourceDirectory . getAbsolutePath ( ) ) ; commands . add ( new File ( targetDirectory , shortJavaFileName ) . getAbsolutePath ( ) ) ; try { CommandExecutor executor = CommandExecutor . Factory . createDefaultCommmandExecutor ( ) ; executor . setLogger ( this . getLog ( ) ) ; executor . setCaptureStdOut ( true ) ; executor . executeCommand ( getAndroidSdk ( ) . getAidlPath ( ) , commands , project . getBasedir ( ) , false ) ; } catch ( ExecutionException e ) { throw new MojoExecutionException ( "" , e ) ; } } }


signature:
public class DexMojo { /** * Gets the input files for dex . This is a combination of directories and jar files .
 * @ return */
private Set < File > getDexInputFiles ( ) throws MojoExecutionException { } }

implementation:
Set < File > inputs = new HashSet < File > ( ) ; if ( obfuscatedJar != null && obfuscatedJar . exists ( ) ) { // proguard has been run , use this jar
getLog ( ) . debug ( "Adding dex input (obfuscatedJar) : " + obfuscatedJar ) ; inputs . add ( obfuscatedJar ) ; } else { getLog ( ) . debug ( "Using non-obfuscated input" ) ; // no proguard , use original config
inputs . add ( projectOutputDirectory ) ; getLog ( ) . debug ( "Adding dex input : " + project . getBuild ( ) . getOutputDirectory ( ) ) ; for ( Artifact artifact : filterArtifacts ( getTransitiveDependencyArtifacts ( ) , skipDependencies , artifactTypeSet . getIncludes ( ) , artifactTypeSet . getExcludes ( ) , artifactSet . getIncludes ( ) , artifactSet . getExcludes ( ) ) ) { if ( artifact . getType ( ) . equals ( Const . ArtifactType . NATIVE_SYMBOL_OBJECT ) || artifact . getType ( ) . equals ( Const . ArtifactType . NATIVE_IMPLEMENTATION_ARCHIVE ) ) { // Ignore native dependencies - no need for dexer to see those
} else if ( artifact . getType ( ) . equals ( APKLIB ) ) { // Any jars in the libs folder should now be
// automatically included because they will be a transitive dependency .
} else if ( artifact . getType ( ) . equals ( AAR ) ) { // The Aar classes . jar should now be automatically included
// because it will be a transitive dependency . As should any jars in the libs folder .
} else if ( artifact . getType ( ) . equals ( APK ) ) { // We need to dex the APK classes including the APK R .
// But we don ' t want to add a second instance of the embedded Rs for any of the APK ' s dependencies
// as they will already have been generated to target / classes . The R values from the APK will be
// the correct ones , so best solution is to extract the APK classes ( including all Rs ) to
// target / classes overwriting any generated Rs and let dex pick up the values from there .
getLog ( ) . debug ( "Extracting APK classes to target/classes : " + artifact . getArtifactId ( ) ) ; final File apkClassesJar = getUnpackedLibHelper ( ) . getJarFileForApk ( artifact ) ; getLog ( ) . debug ( "Extracting APK : " + apkClassesJar + " to " + targetDirectory ) ; final ZipExtractor extractor = new ZipExtractor ( getLog ( ) ) ; extractor . extract ( apkClassesJar , targetDirectory , ".class" ) ; } else { getLog ( ) . debug ( "Adding dex input : " + artifact . getFile ( ) ) ; inputs . add ( artifact . getFile ( ) . getAbsoluteFile ( ) ) ; } } } return inputs ;


signature:
public class ZipalignMojo { /** * Execute the mojo by parsing the confign and actually doing the zipalign .
 * @ throws MojoExecutionException */
public void execute ( ) throws MojoExecutionException , MojoFailureException { } }

implementation:
// If we ' re not on a supported packaging with just skip ( Issue 87)
// http : / / code . google . com / p / maven - android - plugin / issues / detail ? id = 87
if ( ! SUPPORTED_PACKAGING_TYPES . contains ( project . getPackaging ( ) ) ) { getLog ( ) . info ( "Skipping zipalign on " + project . getPackaging ( ) ) ; return ; } ConfigHandler configHandler = new ConfigHandler ( this , this . session , this . execution ) ; configHandler . parseConfiguration ( ) ; parsedInputApk = FilenameUtils . separatorsToSystem ( parsedInputApk ) ; parsedOutputApk = FilenameUtils . separatorsToSystem ( parsedOutputApk ) ; getLog ( ) . debug ( "skip:" + parsedSkip ) ; getLog ( ) . debug ( "verbose:" + parsedVerbose ) ; getLog ( ) . debug ( "inputApk:" + parsedInputApk ) ; getLog ( ) . debug ( "outputApk:" + parsedOutputApk ) ; getLog ( ) . debug ( "classifier:" + parsedClassifier ) ; if ( parsedSkip ) { getLog ( ) . info ( "Skipping zipalign" ) ; } else { boolean outputToSameFile = sameOutputAsInput ( ) ; CommandExecutor executor = CommandExecutor . Factory . createDefaultCommmandExecutor ( ) ; executor . setLogger ( this . getLog ( ) ) ; String command = getAndroidSdk ( ) . getZipalignPath ( ) ; List < String > parameters = new ArrayList < String > ( ) ; if ( parsedVerbose ) { parameters . add ( "-v" ) ; } parameters . add ( "-f" ) ; // force overwriting existing output file
parameters . add ( "4" ) ; // byte alignment has to be 4!
parameters . add ( parsedInputApk ) ; String outputApk = outputToSameFile ? getTemporaryOutputApkFilename ( ) : parsedOutputApk ; parameters . add ( outputApk ) ; try { getLog ( ) . info ( "Running command: " + command ) ; getLog ( ) . info ( "with parameters: " + parameters ) ; executor . setCaptureStdOut ( true ) ; executor . executeCommand ( command , parameters ) ; if ( FileUtils . fileExists ( outputApk ) ) { if ( outputToSameFile ) { // No needs to attach zipaligned apk to artifacts
try { FileUtils . rename ( new File ( outputApk ) , new File ( parsedInputApk ) ) ; } catch ( IOException e ) { getLog ( ) . error ( "Failed to replace original apk with aligned " + getFullPathWithName ( outputApk ) , e ) ; } } else { // Attach the resulting artifact ( Issue 88)
// http : / / code . google . com / p / maven - android - plugin / issues / detail ? id = 88
projectHelper . attachArtifact ( project , APK , parsedClassifier , new File ( outputApk ) ) ; getLog ( ) . info ( "Attach " + getFullPathWithName ( outputApk ) + " as '" + parsedClassifier + "' to the project" ) ; } } else { getLog ( ) . error ( "Cannot attach " + getFullPathWithName ( outputApk ) + " to the project" + " - The file does not exist" ) ; } } catch ( ExecutionException e ) { throw new MojoExecutionException ( "" , e ) ; } }


signature:
public class ZipalignMojo { /** * used via PullParameter annotation - do not remove */
private String getInputApkPath ( ) { } }

implementation: if ( apkFile == null ) { apkFile = new File ( targetDirectory , finalName + "." + APK ) ; } return apkFile . getAbsolutePath ( ) ;


signature:
public class ZipalignMojo { /** * used via PullParameter annotation - do not remove */
private String getOutputApkPath ( ) { } }

implementation: if ( alignedApkFile == null ) { alignedApkFile = new File ( targetDirectory , finalName + "-aligned." + APK ) ; } return alignedApkFile . getAbsolutePath ( ) ;


signature:
public class PullMojo { /** * Retrieves the corresponding { @ link FileEntry } on the emulator / device for
 * a given file path .
 * If the file path starts with the symlink " sdcard " , it will be resolved
 * statically to " / mnt / sdcard " .
 * @ param filePath path to file or directory on device or emulator
 * @ param fileListingService { @ link FileListingService } for retrieving the
 * { @ link FileEntry }
 * @ return a { @ link FileEntry } object for the given file path
 * @ throws MojoExecutionException if the file path could not be found on the device */
private FileEntry getFileEntry ( String filePath , FileListingService fileListingService ) throws MojoExecutionException { } }

implementation:
// static resolution of symlink
if ( filePath . startsWith ( "/sdcard" ) ) { filePath = "/mnt" + filePath ; } String [ ] destinationPathSegments = StringUtils . split ( filePath , "/" ) ; FileEntry fileEntry = fileListingService . getRoot ( ) ; for ( String destinationPathSegment : destinationPathSegments ) { // build up file listing cache
fileListingService . getChildren ( fileEntry , true , null ) ; fileEntry = fileEntry . findChild ( destinationPathSegment ) ; if ( fileEntry == null ) { throw new MojoExecutionException ( "Cannot execute goal: " + filePath + " does not exist on device." ) ; } } return fileEntry ;


signature:
public class AndroidPublisherHelper { /** * Ensure the client secrets file has been filled out .
 * @ param clientSecrets the GoogleClientSecrets containing data from the
 * file */
private static void checkClientSecretsFile ( GoogleClientSecrets clientSecrets ) { } }

implementation: if ( clientSecrets . getDetails ( ) . getClientId ( ) . startsWith ( "[[INSERT" ) || clientSecrets . getDetails ( ) . getClientSecret ( ) . startsWith ( "[[INSERT" ) ) { LOG . error ( "Enter Client ID and Secret from " + "APIs console into resources/client_secrets.json." ) ; System . exit ( 1 ) ; }


signature:
public class AndroidPublisherHelper { /** * Performs all necessary setup steps for running requests against the API .
 * @ param applicationName the name of the application : com . example . app
 * @ param serviceAccountEmail the Service Account Email ( empty if using
 * installed application )
 * @ return the { @ Link AndroidPublisher } service
 * @ throws GeneralSecurityException
 * @ throws IOException */
public static AndroidPublisher init ( String applicationName , @ Nullable String serviceAccountEmail ) throws IOException , GeneralSecurityException { } }

implementation:
Preconditions . checkArgument ( ! Strings . isNullOrEmpty ( applicationName ) , "applicationName cannot be null or empty!" ) ; // Authorization .
newTrustedTransport ( ) ; Credential credential ; credential = authorizeWithServiceAccount ( serviceAccountEmail ) ; // Set up and return API client .
return new AndroidPublisher . Builder ( httpTransport , JSON_FACTORY , credential ) . setApplicationName ( applicationName ) . build ( ) ;


signature:
public class AndroidPublisherHelper { /** * Performs all necessary setup steps for running requests against the API .
 * @ param serviceAccountEmail the Service Account Email ( empty if using
 * installed application )
 * @ return the { @ Link AndroidPublisher } service
 * @ throws GeneralSecurityException
 * @ throws IOException */
public static AndroidPublisher init ( String applicationName , String serviceAccountEmail , File pk12File ) throws IOException , GeneralSecurityException { } }

implementation:
// Authorization .
newTrustedTransport ( ) ; Credential credential = authorizeWithServiceAccount ( serviceAccountEmail , pk12File ) ; // Set up and return API client .
return new AndroidPublisher . Builder ( httpTransport , JSON_FACTORY , credential ) . setApplicationName ( applicationName ) . build ( ) ;


signature:
public class ClasspathModifierLifecycleParticipant { /** * Add jar files in libs into the project classpath . */
private void addLibsJarsToClassPath ( UnpackedLibHelper helper , MavenProject project , Artifact artifact ) throws MavenExecutionException { } }

implementation:
try { final File unpackLibFolder = helper . getUnpackedLibFolder ( artifact ) ; final File artifactFile = helper . getArtifactToFile ( artifact ) ; ZipFile zipFile = new ZipFile ( artifactFile ) ; Enumeration enumeration = zipFile . entries ( ) ; while ( enumeration . hasMoreElements ( ) ) { ZipEntry entry = ( ZipEntry ) enumeration . nextElement ( ) ; String entryName = entry . getName ( ) ; // Only jar files under ' libs ' directory to be processed .
if ( Pattern . matches ( "^libs/.+\\.jar$" , entryName ) ) { final File libsJarFile = new File ( unpackLibFolder , entryName ) ; log . warn ( "Adding jar from libs folder to classpath: " + libsJarFile ) ; // In order to satisfy the LifecycleDependencyResolver on execution up to a phase that
// has a Mojo requiring dependency resolution I need to create a dummy classesJar here .
if ( ! libsJarFile . getParentFile ( ) . exists ( ) ) { libsJarFile . getParentFile ( ) . mkdirs ( ) ; } libsJarFile . createNewFile ( ) ; // Add the jar to the classpath .
final Dependency dependency = createSystemScopeDependency ( artifact , libsJarFile , libsJarFile . getName ( ) ) ; project . getModel ( ) . addDependency ( dependency ) ; addedJarFromLibs = true ; } } } catch ( MojoExecutionException e ) { log . debug ( "Error extract jars" ) ; } catch ( ZipException e ) { log . debug ( "Error" ) ; } catch ( IOException e ) { log . debug ( "Error" ) ; }


signature:
public class ClasspathModifierLifecycleParticipant { /** * Add the dependent library classes to the project classpath . */
private void addClassesToClasspath ( UnpackedLibHelper helper , MavenProject project , Artifact artifact ) throws MavenExecutionException { } }

implementation:
// Work out where the dep will be extracted and calculate the file path to the classes jar .
// This is location where the GenerateSourcesMojo will extract the classes .
final File classesJar = helper . getUnpackedClassesJar ( artifact ) ; log . debug ( "Adding to classpath : " + classesJar ) ; // In order to satisfy the LifecycleDependencyResolver on execution up to a phase that
// has a Mojo requiring dependency resolution I need to create a dummy classesJar here .
if ( ! classesJar . exists ( ) ) { classesJar . getParentFile ( ) . mkdirs ( ) ; try { final ZipOutputStream zipOutputStream = new ZipOutputStream ( new FileOutputStream ( classesJar ) ) ; zipOutputStream . putNextEntry ( new ZipEntry ( "dummy" ) ) ; zipOutputStream . close ( ) ; log . debug ( "Created dummy " + classesJar . getName ( ) + " exist=" + classesJar . exists ( ) ) ; } catch ( IOException e ) { throw new MavenExecutionException ( "Could not add " + classesJar . getName ( ) + " as dependency" , e ) ; } } // Modify the classpath to use an extracted dex file . This will overwrite
// any exisiting dependencies with the same information .
final Dependency dependency = createSystemScopeDependency ( artifact , classesJar , null ) ; final Dependency providedJar = findProvidedDependencies ( dependency , project ) ; if ( providedJar != null ) { project . getModel ( ) . removeDependency ( providedJar ) ; } project . getModel ( ) . addDependency ( dependency ) ;


signature:
public class LintMojo { /** * Execute the mojo by parsing the config and actually invoking the lint command from the Android SDK .
 * @ throws MojoExecutionException */
@ Override public void execute ( ) throws MojoExecutionException , MojoFailureException { } }

implementation: ConfigHandler configHandler = new ConfigHandler ( this , this . session , this . execution ) ; configHandler . parseConfiguration ( ) ; getLog ( ) . debug ( "Parsed values for Android Lint invocation: " ) ; getLog ( ) . debug ( "failOnError:" + parsedFailOnError ) ; getLog ( ) . debug ( "skip:" + parsedSkip ) ; getLog ( ) . debug ( "legacy:" + parsedLegacy ) ; getLog ( ) . debug ( "quiet:" + parsedQuiet ) ; getLog ( ) . debug ( "ignoreWarnings:" + parsedIgnoreWarnings ) ; getLog ( ) . debug ( "warnAll:" + parsedWarnAll ) ; getLog ( ) . debug ( "warningsAsErrors:" + parsedWarningsAsErrors ) ; getLog ( ) . debug ( "config2:" + parsedConfig ) ; getLog ( ) . debug ( "fullPath:" + parsedFullPath ) ; getLog ( ) . debug ( "showAll:" + parsedShowAll ) ; getLog ( ) . debug ( "disableSourceLines:" + parsedDisableSourceLines ) ; getLog ( ) . debug ( "enablehtml: " + parsedEnableHtml ) ; getLog ( ) . debug ( "htmlOutputPath:" + parsedHtmlOutputPath ) ; getLog ( ) . debug ( "enableSimpleHtml: " + parsedEnableSimpleHtml ) ; getLog ( ) . debug ( "simpleHtmlOutputPath:" + parsedSimpleHtmlOutputPath ) ; getLog ( ) . debug ( "enableXml: " + parsedEnableXml ) ; getLog ( ) . debug ( "xmlOutputPath:" + parsedXmlOutputPath ) ; getLog ( ) . debug ( "sources:" + parsedSources ) ; getLog ( ) . debug ( "classpath:" + parsedClasspath ) ; getLog ( ) . debug ( "libraries:" + parsedLibraries ) ; if ( parsedSkip ) { getLog ( ) . info ( "Skipping lint analysis." ) ; } else { getLog ( ) . info ( "Performing lint analysis." ) ; if ( parsedLegacy ) { getLog ( ) . info ( "Using Lint from the Android SDK." ) ; executeWhenConfigured ( ) ; } else { getLog ( ) . info ( "Using Lint dependency library." ) ; runLint ( ) ; } }


signature:
public class LintMojo { /** * used via PullParameter annotation - do not remove */
private String getHtmlOutputPath ( ) { } }

implementation: if ( parsedHtmlOutputPath == null ) { File reportPath = new File ( targetDirectory , "lint-results/lint-results-html" ) ; createReportDirIfNeeded ( reportPath ) ; return reportPath . getAbsolutePath ( ) ; } return parsedHtmlOutputPath ;


signature:
public class LintMojo { /** * used via PullParameter annotation - do not remove */
private String getSimpleHtmlOutputPath ( ) { } }

implementation: if ( parsedSimpleHtmlOutputPath == null ) { File reportPath = new File ( targetDirectory , "lint-results/lint-results-simple-html" ) ; createReportDirIfNeeded ( reportPath ) ; return reportPath . getAbsolutePath ( ) ; } return parsedSimpleHtmlOutputPath ;


signature:
public class LintMojo { /** * used via PullParameter annotation - do not remove */
private String getXmlOutputPath ( ) { } }

implementation: getLog ( ) . debug ( "get parsed xml output path:" + parsedXmlOutputPath ) ; if ( parsedXmlOutputPath == null ) { File reportPath = new File ( targetDirectory , "lint-results/lint-results.xml" ) ; createReportDirIfNeeded ( reportPath ) ; return reportPath . getAbsolutePath ( ) ; } return parsedXmlOutputPath ;


signature:
public class PluginInfo { /** * Get the Maven GAV string of the plugin .
 * @ return */
public static String getGAV ( ) { } }

implementation: StringBuilder builder = new StringBuilder ( ) . append ( groupId ) . append ( COLON ) . append ( artifactId ) . append ( COLON ) . append ( version ) ; return builder . toString ( ) ;


signature:
public class AndroidExtension { /** * Determine whether or not a { @ link MavenProject } ' s packaging is an
 * Android project .
 * @ param packaging Project packaging .
 * @ return True if an Android project . */
public static boolean isAndroidPackaging ( String packaging ) { } }

implementation: return APK . equals ( packaging ) || APKLIB . equals ( packaging ) || APKSOURCES . equals ( packaging ) || AAR . equalsIgnoreCase ( packaging ) ;


signature:
public class ProguardMojo { /** * Convert the jvm arguments in parsedJvmArguments as populated by the config in format as needed by the java
 * command . Also preserve backwards compatibility in terms of dashes required or not . . */
private void collectJvmArguments ( List < String > commands ) { } }

implementation:
if ( parsedJvmArguments != null ) { for ( String jvmArgument : parsedJvmArguments ) { // preserve backward compatibility allowing argument with or without dash ( e . g .
// Xmx512m as well as - Xmx512m should work ) ( see
// http : / / code . google . com / p / maven - android - plugin / issues / detail ? id = 153)
if ( ! jvmArgument . startsWith ( "-" ) ) { jvmArgument = "-" + jvmArgument ; } commands . add ( jvmArgument ) ; } }


signature:
public class ProguardMojo { /** * Finds a library file in either the primary or alternate lib directory .
 * @ param fileName The base name of the file .
 * @ return Either a canonical filename , or { @ code null } if not found . */
private File getJVMLibrary ( String fileName ) { } }

implementation: File libFile = new File ( getJavaLibDir ( ) , fileName ) ; if ( ! libFile . exists ( ) ) { libFile = new File ( getAltJavaLibDir ( ) , fileName ) ; if ( ! libFile . exists ( ) ) { libFile = null ; } } return libFile ;


signature:
public class AbstractInstrumentationMojo { /** * Helper method to build a comma separated string from a list .
 * Blank strings are filtered out
 * @ param lines A list of strings
 * @ return Comma separated String from given list */
protected static String buildCommaSeparatedString ( List < String > lines ) { } }

implementation:
if ( lines == null || lines . size ( ) == 0 ) { return null ; } List < String > strings = new ArrayList < String > ( lines . size ( ) ) ; for ( String str : lines ) { // filter out blank strings
if ( StringUtils . isNotBlank ( str ) ) { strings . add ( StringUtils . trimToEmpty ( str ) ) ; } } return StringUtils . join ( strings , "," ) ;


signature:
public class RunMojo { /** * { @ inheritDoc } */
@ Override public void execute ( ) throws MojoExecutionException , MojoFailureException { } }

implementation: if ( project . getPackaging ( ) . equals ( APK ) ) { try { LauncherInfo launcherInfo ; launcherInfo = getLauncherActivity ( ) ; ConfigHandler configHandler = new ConfigHandler ( this , this . session , this . execution ) ; configHandler . parseConfiguration ( ) ; launch ( launcherInfo ) ; } catch ( Exception ex ) { getLog ( ) . info ( "Unable to run launcher Activity" ) ; getLog ( ) . debug ( ex ) ; } } else { getLog ( ) . info ( "Project packaging is not apk, skipping run action." ) ; }


signature:
public class RunMojo { /** * Gets the first " Launcher " Activity by running an XPath query on < code > AndroidManifest . xml < / code > .
 * @ return A { @ link LauncherInfo }
 * @ throws MojoFailureException
 * @ throws ParserConfigurationException
 * @ throws IOException
 * @ throws SAXException
 * @ throws XPathExpressionException */
private LauncherInfo getLauncherActivity ( ) throws ParserConfigurationException , SAXException , IOException , XPathExpressionException , MojoFailureException { } }

implementation:
Document document ; DocumentBuilder documentBuilder ; DocumentBuilderFactory documentBuilderFactory ; Object result ; XPath xPath ; XPathExpression xPathExpression ; XPathFactory xPathFactory ; // Setup JAXP stuff
documentBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; documentBuilder = documentBuilderFactory . newDocumentBuilder ( ) ; document = documentBuilder . parse ( destinationManifestFile ) ; xPathFactory = XPathFactory . newInstance ( ) ; xPath = xPathFactory . newXPath ( ) ; xPathExpression = xPath . compile ( "//manifest/application/activity/intent-filter[action[@name=\"android.intent.action.MAIN\"] " + "and category[@name=\"android.intent.category.LAUNCHER\"]]/.." ) ; // Run XPath query
result = xPathExpression . evaluate ( document , XPathConstants . NODESET ) ; if ( result instanceof NodeList ) { NodeList activities ; activities = ( NodeList ) result ; if ( activities . getLength ( ) > 0 ) { // Grab the first declared Activity
LauncherInfo launcherInfo ; launcherInfo = new LauncherInfo ( ) ; String activityName = activities . item ( 0 ) . getAttributes ( ) . getNamedItem ( "android:name" ) . getNodeValue ( ) ; if ( ! activityName . contains ( "." ) ) { activityName = "." + activityName ; } if ( activityName . startsWith ( "." ) ) { String packageName = document . getElementsByTagName ( "manifest" ) . item ( 0 ) . getAttributes ( ) . getNamedItem ( "package" ) . getNodeValue ( ) ; activityName = packageName + activityName ; } launcherInfo . activity = activityName ; launcherInfo . packageName = renameManifestPackage != null ? renameManifestPackage : document . getDocumentElement ( ) . getAttribute ( "package" ) . toString ( ) ; return launcherInfo ; } else { // If we get here , we couldn ' t find a launcher activity .
throw new MojoFailureException ( "Could not find a launcher activity in manifest" ) ; } } else { // If we get here we couldn ' t find any Activity
throw new MojoFailureException ( "Could not find any activity in manifest" ) ; }


signature:
public class RunMojo { /** * Executes the " Launcher activity " .
 * @ param info A { @ link LauncherInfo } .
 * @ throws MojoFailureException
 * @ throws MojoExecutionException */
private void launch ( final LauncherInfo info ) throws MojoExecutionException , MojoFailureException { } }

implementation: final String command ; final int debugPort = findDebugPort ( ) ; command = String . format ( "am start %s-n %s/%s" , debugPort >= 0 ? "-D " : "" , info . packageName , info . activity ) ; doWithDevices ( new DeviceCallback ( ) { @ Override public void doWithDevice ( IDevice device ) throws MojoExecutionException , MojoFailureException { String deviceLogLinePrefix = DeviceHelper . getDeviceLogLinePrefix ( device ) ; try { getLog ( ) . info ( deviceLogLinePrefix + "Attempting to start " + info . packageName + "/" + info . activity ) ; CollectingOutputReceiver shellOutput = new CollectingOutputReceiver ( ) ; device . executeShellCommand ( command , shellOutput ) ; if ( shellOutput . getOutput ( ) . contains ( "Error" ) ) { throw new MojoFailureException ( shellOutput . getOutput ( ) ) ; } if ( debugPort > 0 ) { int pid = findPid ( device , "ps" ) ; if ( pid == - 1 ) { pid = findPid ( device , "ps -Af" ) ; } if ( pid == - 1 ) { throw new MojoFailureException ( "Cannot find stated process " + info . packageName ) ; } getLog ( ) . info ( deviceLogLinePrefix + "Process " + debugPort + " launched" ) ; try { createForward ( device , debugPort , pid ) ; getLog ( ) . info ( deviceLogLinePrefix + "Debugger listening on " + debugPort ) ; } catch ( Exception ex ) { throw new MojoFailureException ( "Cannot create forward tcp: " + debugPort + " jdwp: " + pid , ex ) ; } } } catch ( IOException ex ) { throw new MojoFailureException ( deviceLogLinePrefix + "Input/Output error" , ex ) ; } catch ( TimeoutException ex ) { throw new MojoFailureException ( deviceLogLinePrefix + "Command timeout" , ex ) ; } catch ( AdbCommandRejectedException ex ) { throw new MojoFailureException ( deviceLogLinePrefix + "ADB rejected the command" , ex ) ; } catch ( ShellCommandUnresponsiveException ex ) { throw new MojoFailureException ( deviceLogLinePrefix + "Unresponsive command" , ex ) ; } } private int findPid ( IDevice device , final String cmd ) throws IOException , TimeoutException , AdbCommandRejectedException , ShellCommandUnresponsiveException { CollectingOutputReceiver processOutput = new CollectingOutputReceiver ( ) ; device . executeShellCommand ( cmd , processOutput ) ; BufferedReader r = new BufferedReader ( new StringReader ( processOutput . getOutput ( ) ) ) ; int pid = - 1 ; for ( ; ; ) { String line = r . readLine ( ) ; if ( line == null ) { break ; } if ( line . endsWith ( info . packageName ) ) { String [ ] values = line . split ( " +" ) ; if ( values . length > 2 ) { pid = Integer . valueOf ( values [ 1 ] ) ; break ; } } } r . close ( ) ; return pid ; } } ) ;


signature:
public class AndroidNdk { /** * Tries to resolve the toolchain based on the path of the file .
 * @ param file Native library
 * @ return String
 * @ throws MojoExecutionException When no toolchain is found */
public String getToolchain ( File file ) throws MojoExecutionException { } }

implementation:
String resolvedNdkToolchain = null ; // try to resolve the toolchain now
String ndkArchitecture = file . getParentFile ( ) . getName ( ) ; if ( ndkArchitecture . startsWith ( "armeabi" ) ) { resolvedNdkToolchain = resolveNdkToolchain ( ARM_TOOLCHAIN ) ; } else if ( ndkArchitecture . startsWith ( "arm64" ) ) { resolvedNdkToolchain = resolveNdkToolchain ( ARM64_TOOLCHAIN ) ; } else if ( ndkArchitecture . startsWith ( "x86_64" ) ) { resolvedNdkToolchain = resolveNdkToolchain ( X86_64_TOOLCHAIN ) ; } else if ( ndkArchitecture . startsWith ( "x86" ) ) { resolvedNdkToolchain = resolveNdkToolchain ( X86_TOOLCHAIN ) ; } else if ( ndkArchitecture . startsWith ( "mips64" ) ) { resolvedNdkToolchain = resolveNdkToolchain ( MIPS64_TOOLCHAIN ) ; } else if ( ndkArchitecture . startsWith ( "mips" ) ) { resolvedNdkToolchain = resolveNdkToolchain ( MIPS_TOOLCHAIN ) ; } // if no toolchain can be found
if ( resolvedNdkToolchain == null ) { throw new MojoExecutionException ( "Can not resolve automatically a toolchain to use. Please specify one." ) ; } return resolvedNdkToolchain ;


signature:
public class AndroidNdk { /** * Returns the complete path for the ndk - build tool , based on this NDK .
 * @ return the complete path as a < code > String < / code > , including the tool ' s filename . */
public String getNdkBuildPath ( ) { } }

implementation: if ( SystemUtils . IS_OS_WINDOWS ) { return new File ( ndkPath , "/ndk-build.cmd" ) . getAbsolutePath ( ) ; } else { return new File ( ndkPath , "/ndk-build" ) . getAbsolutePath ( ) ; }


signature:
public class DeviceHelper { /** * Get a device identifier string that is suitable for filenames as well as log messages .
 * This means it is human readable and contains no spaces .
 * Used for instrumentation test report file names so see more at
 * AbstractInstrumentationMojo # testCreateReport javadoc since
 * that is the public documentation . */
public static String getDescriptiveName ( IDevice device ) { } }

implementation:
// if any of this logic changes update javadoc for
// AbstractInstrumentationMojo # testCreateReport
StringBuilder identfier = new StringBuilder ( ) . append ( device . getSerialNumber ( ) ) ; if ( device . getAvdName ( ) != null ) { identfier . append ( SEPARATOR ) . append ( device . getAvdName ( ) ) ; } String manufacturer = getManufacturer ( device ) ; if ( StringUtils . isNotBlank ( manufacturer ) ) { identfier . append ( SEPARATOR ) . append ( manufacturer ) ; } String model = getModel ( device ) ; if ( StringUtils . isNotBlank ( model ) ) { identfier . append ( SEPARATOR ) . append ( model ) ; } return FileNameHelper . fixFileName ( identfier . toString ( ) ) ;


signature:
public class ManifestUpdateMojo { /** * Read manifest using JAXP */
private Document readManifest ( File manifestFile ) throws IOException , ParserConfigurationException , SAXException { } }

implementation: DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; Document doc = db . parse ( manifestFile ) ; return doc ;


signature:
public class ManifestUpdateMojo { /** * Write manifest using JAXP transformer */
private void writeManifest ( File manifestFile , Document doc ) throws IOException , TransformerException { } }

implementation: TransformerFactory xfactory = TransformerFactory . newInstance ( ) ; Transformer xformer = xfactory . newTransformer ( ) ; xformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "yes" ) ; Source source = new DOMSource ( doc ) ; OutputStreamWriter writer = null ; try { manifestFile . getParentFile ( ) . mkdirs ( ) ; String encoding = doc . getXmlEncoding ( ) != null ? doc . getXmlEncoding ( ) : "UTF-8" ; writer = new OutputStreamWriter ( new FileOutputStream ( manifestFile , false ) , encoding ) ; if ( doc . getXmlEncoding ( ) != null && doc . getXmlVersion ( ) != null ) { String xmldecl = String . format ( "<?xml version=\"%s\" encoding=\"%s\"?>%n" , doc . getXmlVersion ( ) , doc . getXmlEncoding ( ) ) ; writer . write ( xmldecl ) ; } Result result = new StreamResult ( writer ) ; xformer . transform ( source , result ) ; } finally { IOUtils . closeQuietly ( writer ) ; }


signature:
public class ManifestUpdateMojo { /** * Expose the version properties and other simple parsed manifest entries . */
private void exportProperties ( ) { } }

implementation: project . getProperties ( ) . setProperty ( "android.manifest.versionName" , parsedVersionName ) ; project . getProperties ( ) . setProperty ( "android.manifest.versionCodeAutoIncrement" , String . valueOf ( parsedVersionCodeAutoIncrement ) ) ; project . getProperties ( ) . setProperty ( "android.manifest.versionCodeUpdateFromVersion" , String . valueOf ( parsedVersionCodeUpdateFromVersion ) ) ; project . getProperties ( ) . setProperty ( "android.manifest.debuggable" , String . valueOf ( parsedDebuggable ) ) ; if ( parsedSharedUserId != null ) { project . getProperties ( ) . setProperty ( "android.manifest.sharedUserId" , parsedSharedUserId ) ; }


signature:
public class ManifestUpdateMojo { /** * If the specified version name cannot be properly parsed then fall back to
 * an automatic method .
 * If the version can be parsed then generate a version code from the
 * version components . In an effort to preseve uniqueness two digits
 * are allowed for both the minor and incremental versions .
 * @ throws MojoExecutionException */
private void performVersionCodeUpdateFromVersion ( Element manifestElement ) throws MojoExecutionException { } }

implementation: String verString = project . getVersion ( ) ; getLog ( ) . debug ( "Generating versionCode for " + verString ) ; String verCode = generateVersionCodeFromVersionName ( verString ) ; getLog ( ) . info ( "Setting " + ATTR_VERSION_CODE + " to " + verCode ) ; manifestElement . setAttribute ( ATTR_VERSION_CODE , verCode ) ; project . getProperties ( ) . setProperty ( "android.manifest.versionCode" , String . valueOf ( verCode ) ) ;


signature:
public class NativeHelper { /** * Extracts , if embedded correctly , the artifacts architecture from its classifier . The format of the
 * classifier , if including the architecture is & lt ; architecture & gt ; - & lt ; classifier & gt ; . If no
 * architecture is embedded in the classifier , ' armeabi ' will be returned .
 * @ param artifact The artifact to retrieve the classifier from .
 * @ param defaultArchitecture The architecture to return if can ' t be resolved from the classifier
 * @ return The retrieved architecture , or < code > defaulArchitecture < / code > if not resolveable */
public static String extractArchitectureFromArtifact ( Artifact artifact , final String defaultArchitecture ) { } }

implementation:
String classifier = artifact . getClassifier ( ) ; if ( classifier != null ) { // We loop backwards to catch the case where the classifier is
// potentially armeabi - v7a - this collides with armeabi if looping
// through this loop in the other direction
for ( int i = AndroidNdk . NDK_ARCHITECTURES . length - 1 ; i >= 0 ; i -- ) { String ndkArchitecture = AndroidNdk . NDK_ARCHITECTURES [ i ] ; if ( classifier . startsWith ( ndkArchitecture ) ) { return ndkArchitecture ; } } } // Default case is to return the default architecture
return defaultArchitecture ;