This repository was archived by the owner on Feb 26, 2023. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathAndroidManifestFinder.java
More file actions
520 lines (421 loc) · 19.5 KB
/
Copy pathAndroidManifestFinder.java
File metadata and controls
520 lines (421 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/**
* Copyright (C) 2010-2016 eBusiness Information, Excilys Group
* Copyright (C) 2016-2018 the AndroidAnnotations project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed To in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.androidannotations.internal.helper;
import static org.androidannotations.helper.CaseHelper.upperCaseFirst;
import static org.androidannotations.helper.ModelConstants.classSuffix;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.lang.model.util.Elements;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.androidannotations.AndroidAnnotationsEnvironment;
import org.androidannotations.Option;
import org.androidannotations.helper.AndroidManifest;
import org.androidannotations.internal.exception.AndroidManifestNotFoundException;
import org.androidannotations.logger.Logger;
import org.androidannotations.logger.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class AndroidManifestFinder {
public static final Option OPTION_MANIFEST = new Option("androidManifestFile", null);
public static final Option OPTION_LIBRARY = new Option("library", "false");
private static final Logger LOGGER = LoggerFactory.getLogger(AndroidManifestFinder.class);
private final AndroidAnnotationsEnvironment environment;
public AndroidManifestFinder(AndroidAnnotationsEnvironment environment) {
this.environment = environment;
}
public AndroidManifest extractAndroidManifest() throws AndroidManifestNotFoundException {
try {
File androidManifestFile = findManifestFile();
String projectDirectory = androidManifestFile.getParent();
boolean libraryOption = environment.getOptionBooleanValue(OPTION_LIBRARY);
if (libraryOption) {
return parse(androidManifestFile, true);
}
File projectProperties = new File(projectDirectory, "project.properties");
boolean libraryProject = false;
if (projectProperties.exists()) {
Properties properties = new Properties();
try {
properties.load(new FileInputStream(projectProperties));
if (properties.containsKey("android.library")) {
String androidLibraryProperty = properties.getProperty("android.library");
libraryProject = androidLibraryProperty.equals("true");
LOGGER.debug("Found android.library={} property in project.properties", libraryProject);
}
} catch (IOException ignored) {
// we assume the project is not a library
}
}
return parse(androidManifestFile, libraryProject);
} catch (FileNotFoundException exception) {
throw new AndroidManifestNotFoundException("Unable to find AndroidManifest.xml", exception);
}
}
private File findManifestFile() throws FileNotFoundException {
String androidManifestFile = environment.getOptionValue(OPTION_MANIFEST);
if (androidManifestFile != null) {
return findManifestInSpecifiedPath(androidManifestFile);
} else {
return findManifestInKnownPaths();
}
}
private File findManifestInSpecifiedPath(String androidManifestPath) throws FileNotFoundException {
File androidManifestFile = new File(androidManifestPath);
if (!androidManifestFile.exists()) {
LOGGER.error("Could not find the AndroidManifest.xml file in specified path : {}", androidManifestPath);
throw new FileNotFoundException();
} else {
LOGGER.debug("AndroidManifest.xml file found with specified path: {}", androidManifestFile.toString());
}
return androidManifestFile;
}
private File findManifestInKnownPaths() throws FileNotFoundException {
FileHelper.FileHolder holder = FileHelper.findRootProjectHolder(environment.getProcessingEnvironment());
return findManifestInKnownPathsStartingFromGenFolder(holder.sourcesGenerationFolder.getAbsolutePath());
}
File findManifestInKnownPathsStartingFromGenFolder(String sourcesGenerationFolder) throws FileNotFoundException {
Iterable<AndroidManifestFinderStrategy> strategies = Arrays.asList(new GradleAndroidManifestFinderStrategy(sourcesGenerationFolder),
new MavenAndroidManifestFinderStrategy(sourcesGenerationFolder), new EclipseAndroidManifestFinderStrategy(sourcesGenerationFolder));
AndroidManifestFinderStrategy applyingStrategy = null;
for (AndroidManifestFinderStrategy strategy : strategies) {
if (strategy.applies()) {
applyingStrategy = strategy;
break;
}
}
File androidManifestFile = null;
if (applyingStrategy != null) {
androidManifestFile = applyingStrategy.findAndroidManifestFile();
}
if (androidManifestFile != null) {
LOGGER.debug("{} AndroidManifest.xml file found using generation folder {}: {}", applyingStrategy.name, sourcesGenerationFolder, androidManifestFile.toString());
} else {
LOGGER.error("Could not find the AndroidManifest.xml file, using generation folder [{}])", sourcesGenerationFolder);
}
return androidManifestFile;
}
private static abstract class AndroidManifestFinderStrategy {
final String name;
final Matcher matcher;
AndroidManifestFinderStrategy(String name, Pattern sourceFolderPattern, String sourceFolder) {
this.name = name;
this.matcher = sourceFolderPattern.matcher(sourceFolder);
}
File findAndroidManifestFile() {
for (String location : possibleLocations()) {
File manifestFile = new File(matcher.group(1), location + "/AndroidManifest.xml");
if (manifestFile.exists()) {
return manifestFile;
}
}
return null;
}
boolean applies() {
return matcher.matches();
}
abstract Iterable<String> possibleLocations();
}
private static class GradleAndroidManifestFinderStrategy extends AndroidManifestFinderStrategy {
static final Pattern GRADLE_GEN_FOLDER = Pattern.compile("^(.*?)build[\\\\/]generated[\\\\/]source[\\\\/](k?apt)(.*)$");
private static final List<String> SUPPORTED_ABI_SPLITS = Arrays.asList("arm64-v8a", "armeabi", "armeabi-v7a", "mips", "mips64", "x86", "x86_64");
private static final List<String> SUPPORTED_DENSITY_SPLITS = Arrays.asList("hdpi", "ldpi", "mdpi", "xhdpi", "xxhdpi", "xxxhdpi");
private static final String BUILD_TOOLS_V32_MANIFEST_PATH = "build/intermediates/merged_manifests";
GradleAndroidManifestFinderStrategy(String sourceFolder) {
super("Gradle", GRADLE_GEN_FOLDER, sourceFolder);
}
@Override
Iterable<String> possibleLocations() {
String path = matcher.group(1);
String mode = matcher.group(2);
String gradleVariant = matcher.group(3);
String variantPart = gradleVariant.substring(1);
ArrayList<String> possibleLocations = new ArrayList<>();
findPossibleLocationsV32(path, variantPart, possibleLocations);
for (String directory : Arrays.asList("build/intermediates/manifests/full", "build/intermediates/bundles", "build/intermediates/manifests/aapt")) {
findPossibleLocations(path, directory, variantPart, possibleLocations);
}
return possibleLocations;
}
private void findPossibleLocationsV32(String basePath, String variantPart, List<String> possibleLocations) {
String[] directories = new File(basePath + BUILD_TOOLS_V32_MANIFEST_PATH).list();
if (directories == null) {
return;
}
if (variantPart.startsWith("/") || variantPart.startsWith("\\")) {
variantPart = variantPart.substring(1);
}
String[] variantParts = variantPart.split("[/\\\\]");
if (variantParts.length > 1) {
StringBuilder sb = new StringBuilder(variantParts[0]);
for (int i = 1; i < variantParts.length; i++) {
String part = variantParts[i];
sb.append(upperCaseFirst(part));
}
variantPart = sb.toString();
}
String processManifest = "process" + upperCaseFirst(variantPart) + "Manifest";
String possibleLocation = BUILD_TOOLS_V32_MANIFEST_PATH + "/" + variantPart + "/" + processManifest + "/merged";
File variantDir = new File(basePath + possibleLocation);
if (variantDir.isDirectory()) {
possibleLocations.add(possibleLocation);
addPossibleSplitLocations(basePath, possibleLocation, possibleLocations);
}
}
private void findPossibleLocations(String basePath, String targetPath, String variantPart, List<String> possibleLocations) {
String[] directories = new File(basePath + targetPath).list();
if (directories == null) {
return;
}
if (variantPart.startsWith("/") || variantPart.startsWith("\\")) {
variantPart = variantPart.substring(1);
}
for (String directory : directories) {
String possibleLocation = targetPath + "/" + directory;
File variantDir = new File(basePath + possibleLocation);
if (variantDir.isDirectory() && variantPart.toLowerCase().startsWith(directory.toLowerCase())) {
String remainingPart = variantPart.substring(directory.length());
if (remainingPart.length() == 0) {
possibleLocations.add(possibleLocation);
addPossibleSplitLocations(basePath, possibleLocation, possibleLocations);
} else {
findPossibleLocations(basePath, possibleLocation, remainingPart, possibleLocations);
}
}
}
}
private void addPossibleSplitLocations(String basePath, String possibleLocation, List<String> possibleLocations) {
for (String abiSplit : SUPPORTED_ABI_SPLITS) {
File splitDir = new File(basePath + possibleLocation + "/" + abiSplit);
if (splitDir.isDirectory()) {
possibleLocations.add(possibleLocation + "/" + abiSplit);
for (String densitySplit : SUPPORTED_DENSITY_SPLITS) {
File splitSubDir = new File(basePath + possibleLocation + "/" + abiSplit + "/" + densitySplit);
if (splitSubDir.isDirectory()) {
possibleLocations.add(possibleLocation + "/" + abiSplit + "/" + densitySplit);
}
}
}
}
for (String densitySplit : SUPPORTED_DENSITY_SPLITS) {
File splitDir = new File(basePath + possibleLocation + "/" + densitySplit);
if (splitDir.isDirectory()) {
possibleLocations.add(possibleLocation + "/" + densitySplit);
}
}
}
}
private static class MavenAndroidManifestFinderStrategy extends AndroidManifestFinderStrategy {
static final Pattern MAVEN_GEN_FOLDER = Pattern.compile("^(.*?)target[\\\\/]generated-sources.*$");
MavenAndroidManifestFinderStrategy(String sourceFolder) {
super("Maven", MAVEN_GEN_FOLDER, sourceFolder);
}
@Override
Iterable<String> possibleLocations() {
return Arrays.asList("target", "src/main", "");
}
}
private static class EclipseAndroidManifestFinderStrategy extends AndroidManifestFinderStrategy {
static final Pattern ECLIPSE_GEN_FOLDER = Pattern.compile("^(.*?)\\.apt_generated.*$");
EclipseAndroidManifestFinderStrategy(String sourceFolder) {
super("Eclipse", ECLIPSE_GEN_FOLDER, sourceFolder);
}
@Override
Iterable<String> possibleLocations() {
return Collections.singleton("");
}
}
private AndroidManifest parse(File androidManifestFile, boolean libraryProject) throws AndroidManifestNotFoundException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
Document doc;
try {
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse(androidManifestFile);
} catch (Exception e) {
LOGGER.error("Could not parse the AndroidManifest.xml file at path {}", androidManifestFile, e);
throw new AndroidManifestNotFoundException("Could not parse the AndroidManifest.xml file at path {}" + androidManifestFile, e);
}
Element documentElement = doc.getDocumentElement();
documentElement.normalize();
String applicationPackage = documentElement.getAttribute("package");
int minSdkVersion = -1;
int maxSdkVersion = -1;
int targetSdkVersion = -1;
NodeList sdkNodes = documentElement.getElementsByTagName("uses-sdk");
if (sdkNodes.getLength() > 0) {
Node sdkNode = sdkNodes.item(0);
minSdkVersion = extractAttributeIntValue(sdkNode, "android:minSdkVersion", -1);
maxSdkVersion = extractAttributeIntValue(sdkNode, "android:maxSdkVersion", -1);
targetSdkVersion = extractAttributeIntValue(sdkNode, "android:targetSdkVersion", -1);
}
if (libraryProject) {
return AndroidManifest.createLibraryManifest(applicationPackage, minSdkVersion, maxSdkVersion, targetSdkVersion);
}
NodeList applicationNodes = documentElement.getElementsByTagName("application");
String applicationClassQualifiedName = null;
boolean applicationDebuggableMode = false;
if (applicationNodes.getLength() > 0) {
Node applicationNode = applicationNodes.item(0);
Node nameAttribute = applicationNode.getAttributes().getNamedItem("android:name");
applicationClassQualifiedName = manifestNameToValidQualifiedName(applicationPackage, nameAttribute);
if (applicationClassQualifiedName == null) {
if (nameAttribute != null) {
LOGGER.warn("The class application declared in the AndroidManifest.xml cannot be found in the compile path: [{}]", nameAttribute.getNodeValue());
}
}
Node debuggableAttribute = applicationNode.getAttributes().getNamedItem("android:debuggable");
if (debuggableAttribute != null) {
applicationDebuggableMode = debuggableAttribute.getNodeValue().equalsIgnoreCase("true");
}
}
NodeList activityNodes = documentElement.getElementsByTagName("activity");
List<String> activityQualifiedNames = extractComponentNames(applicationPackage, activityNodes);
NodeList serviceNodes = documentElement.getElementsByTagName("service");
List<String> serviceQualifiedNames = extractComponentNames(applicationPackage, serviceNodes);
NodeList receiverNodes = documentElement.getElementsByTagName("receiver");
List<String> receiverQualifiedNames = extractComponentNames(applicationPackage, receiverNodes);
NodeList providerNodes = documentElement.getElementsByTagName("provider");
List<String> providerQualifiedNames = extractComponentNames(applicationPackage, providerNodes);
List<String> componentQualifiedNames = new ArrayList<>();
componentQualifiedNames.addAll(activityQualifiedNames);
componentQualifiedNames.addAll(serviceQualifiedNames);
componentQualifiedNames.addAll(receiverQualifiedNames);
componentQualifiedNames.addAll(providerQualifiedNames);
NodeList metaDataNodes = documentElement.getElementsByTagName("meta-data");
Map<String, AndroidManifest.MetaDataInfo> metaDataQualifiedNames = extractMetaDataQualifiedNames(metaDataNodes);
NodeList usesPermissionNodes = documentElement.getElementsByTagName("uses-permission");
List<String> usesPermissionQualifiedNames = extractUsesPermissionNames(usesPermissionNodes);
List<String> permissionQualifiedNames = new ArrayList<>();
permissionQualifiedNames.addAll(usesPermissionQualifiedNames);
return AndroidManifest.createManifest(applicationPackage, applicationClassQualifiedName, componentQualifiedNames, metaDataQualifiedNames, permissionQualifiedNames,
minSdkVersion, maxSdkVersion, targetSdkVersion, applicationDebuggableMode);
}
private int extractAttributeIntValue(Node node, String attribute, int defaultValue) {
try {
NamedNodeMap attributes = node.getAttributes();
if (attributes.getLength() > 0) {
Node attributeNode = attributes.getNamedItem(attribute);
if (attributeNode != null) {
return Integer.parseInt(attributeNode.getNodeValue());
}
}
} catch (NumberFormatException ignored) {
// we assume the manifest is well-formed
}
return defaultValue;
}
private List<String> extractComponentNames(String applicationPackage, NodeList componentNodes) {
List<String> componentQualifiedNames = new ArrayList<>();
for (int i = 0; i < componentNodes.getLength(); i++) {
Node activityNode = componentNodes.item(i);
Node nameAttribute = activityNode.getAttributes().getNamedItem("android:name");
String qualifiedName = manifestNameToValidQualifiedName(applicationPackage, nameAttribute);
if (qualifiedName != null) {
componentQualifiedNames.add(qualifiedName);
} else {
if (nameAttribute != null) {
LOGGER.warn("A class activity declared in the AndroidManifest.xml cannot be found in the compile path: [{}]", nameAttribute.getNodeValue());
} else {
LOGGER.warn("The {} activity node in the AndroidManifest.xml has no android:name attribute", i);
}
}
}
return componentQualifiedNames;
}
private Map<String, AndroidManifest.MetaDataInfo> extractMetaDataQualifiedNames(NodeList metaDataNodes) {
Map<String, AndroidManifest.MetaDataInfo> metaDataQualifiedNames = new HashMap<String, AndroidManifest.MetaDataInfo>();
for (int i = 0; i < metaDataNodes.getLength(); i++) {
Node node = metaDataNodes.item(i);
Node nameAttribute = node.getAttributes().getNamedItem("android:name");
Node valueAttribute = node.getAttributes().getNamedItem("android:value");
Node resourceAttribute = node.getAttributes().getNamedItem("android:resource");
if (nameAttribute == null || (valueAttribute == null && resourceAttribute == null)) {
if (nameAttribute != null) {
LOGGER.warn("A malformed <meta-data> has been found in the manifest with name {}", nameAttribute.getNodeValue());
} else {
LOGGER.warn("A malformed <meta-data> has been found in the manifest");
}
} else {
String name = nameAttribute.getNodeValue();
String value = valueAttribute != null ? valueAttribute.getNodeValue() : null;
String resource = resourceAttribute != null ? resourceAttribute.getNodeValue() : null;
metaDataQualifiedNames.put(name, new AndroidManifest.MetaDataInfo(name, value, resource));
}
}
return metaDataQualifiedNames;
}
private String manifestNameToValidQualifiedName(String applicationPackage, Node nameAttribute) {
if (nameAttribute != null) {
String activityName = nameAttribute.getNodeValue();
if (activityName.startsWith(applicationPackage)) {
return returnClassIfExistsOrNull(activityName);
} else {
if (activityName.startsWith(".")) {
return returnClassIfExistsOrNull(applicationPackage + activityName);
} else {
if (classOrModelClassExists(activityName)) {
return activityName;
} else {
return returnClassIfExistsOrNull(applicationPackage + "." + activityName);
}
}
}
} else {
return null;
}
}
private boolean classOrModelClassExists(String className) {
Elements elementUtils = environment.getProcessingEnvironment().getElementUtils();
if (className.endsWith(classSuffix())) {
className = className.substring(0, className.length() - classSuffix().length());
}
return elementUtils.getTypeElement(className) != null;
}
private String returnClassIfExistsOrNull(String className) {
if (classOrModelClassExists(className)) {
return className;
} else {
return null;
}
}
private List<String> extractUsesPermissionNames(NodeList usesPermissionNodes) {
List<String> usesPermissionQualifiedNames = new ArrayList<>();
for (int i = 0; i < usesPermissionNodes.getLength(); i++) {
Node usesPermissionNode = usesPermissionNodes.item(i);
Node nameAttribute = usesPermissionNode.getAttributes().getNamedItem("android:name");
if (nameAttribute == null) {
return null;
}
usesPermissionQualifiedNames.add(nameAttribute.getNodeValue());
}
return usesPermissionQualifiedNames;
}
}