1 package com.xtremelabs.robolectric; 2 3 import android.app.Application; 4 import android.content.BroadcastReceiver; 5 import android.content.IntentFilter; 6 import com.xtremelabs.robolectric.internal.ClassNameResolver; 7 import com.xtremelabs.robolectric.res.RobolectricPackageManager; 8 import com.xtremelabs.robolectric.shadows.ShadowApplication; 9 import org.w3c.dom.Document; 10 11 import static com.xtremelabs.robolectric.Robolectric.shadowOf; 12 13 public class ApplicationResolver { 14 RobolectricConfig config; 15 16 public ApplicationResolver(RobolectricConfig config) { 17 this.config = config; 18 } 19 20 public Application resolveApplication() { 21 String applicationName = config.getApplicationName(); 22 String packageName = config.getPackageName(); 23 24 Application application; 25 if (applicationName != null) { 26 application = newApplicationInstance(packageName, applicationName); 27 } else { 28 application = new Application(); 29 } 30 31 ShadowApplication shadowApplication = shadowOf(application); 32 shadowApplication.setPackageName(packageName); 33 shadowApplication.setApplicationName(applicationName); 34 35 shadowApplication.setPackageManager(new RobolectricPackageManager(application, config)); 36 registerBroadcastReceivers(shadowApplication); 37 38 return application; 39 } 40 41 private void registerBroadcastReceivers(ShadowApplication shadowApplication) { 42 for (int i = 0; i < config.getReceiverCount(); i++) { 43 IntentFilter filter = new IntentFilter(); 44 for (String action : config.getReceiverIntentFilterActions(i)) { 45 filter.addAction(action); 46 } 47 String receiverClassName = replaceLastDotWith$IfInnerStaticClass(config.getReceiverClassName(i)); 48 shadowApplication.registerReceiver((BroadcastReceiver) Robolectric.newInstanceOf(receiverClassName), filter); 49 } 50 } 51 52 private String replaceLastDotWith$IfInnerStaticClass(String receiverClassName) { 53 String[] splits = receiverClassName.split("\\."); 54 String staticInnerClassRegex = "[A-Z][a-zA-Z]*"; 55 if (splits[splits.length - 1].matches(staticInnerClassRegex) && splits[splits.length - 2].matches(staticInnerClassRegex)) { 56 int lastDotIndex = receiverClassName.lastIndexOf("."); 57 StringBuffer buffer = new StringBuffer(receiverClassName); 58 buffer.setCharAt(lastDotIndex,'$'); 59 return buffer.toString(); 60 } 61 return receiverClassName; 62 } 63 64 private String getTagAttributeText(Document doc, String tag, String attribute) { 65 return doc.getElementsByTagName(tag).item(0).getAttributes().getNamedItem(attribute).getTextContent(); 66 } 67 68 private Application newApplicationInstance(String packageName, String applicationName) { 69 Application application; 70 try { 71 Class<? extends Application> applicationClass = 72 new ClassNameResolver<Application>(packageName, applicationName).resolve(); 73 application = applicationClass.newInstance(); 74 } catch (Exception e) { 75 throw new RuntimeException(e); 76 } 77 return application; 78 } 79 } 80