package org.robolectric.util;

import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import org.robolectric.RuntimeEnvironment;

public class ContentProviderController<T extends ContentProvider> {
  private T contentProvider;

  private ContentProviderController(T contentProvider) {
    this.contentProvider = contentProvider;
  }

  public static <T extends ContentProvider> ContentProviderController<T> of(T contentProvider) {
    return new ContentProviderController<>(contentProvider);
  }

  public ContentProviderController<T> create() {
    Context baseContext = RuntimeEnvironment.application.getBaseContext();
    ComponentName componentName = ComponentName.createRelative(baseContext, contentProvider.getClass().getName());

    ProviderInfo providerInfo;
    try {
      providerInfo = RuntimeEnvironment.getPackageManager().getProviderInfo(componentName, 0);
    } catch (PackageManager.NameNotFoundException e) {
      Logger.strict("Unable to find provider info for " + componentName, e);
      providerInfo = null;

    }
    contentProvider.attachInfo(baseContext, providerInfo);

    return this;
  }

  public T get() {
    return contentProvider;
  }

  public ContentProviderController<T> shutdown() {
    contentProvider.shutdown();
    return this;
  }
}

@@ -216,16 +216,47 @@
 erInfo;%0A
+import android.text.TextUtils;%0A
 import o
@@ -290,16 +290,16 @@
 onment;%0A
-
 %0Apublic 
@@ -820,22 +820,8 @@
 e = 
-ComponentName.
 crea
@@ -842,16 +842,33 @@
 eContext
+.getPackageName()
 , conten
@@ -1416,24 +1416,24 @@
 shutdown();%0A
-
     return t
@@ -1440,11 +1440,360 @@
 his;%0A  %7D
+%0A%0A  private static ComponentName createRelative(String pkg, String cls) %7B%0A    final String fullName;%0A    if (cls.charAt(0) == '.') %7B%0A      // Relative to the package. Prepend the package name.%0A      fullName = pkg + cls;%0A    %7D else %7B%0A      // Fully qualified package name.%0A      fullName = cls;%0A    %7D%0A    return new ComponentName(pkg, fullName);%0A  %7D
 %0A%7D%0A

Copy createRelative() from ComponentName since it is not available on older SDKs.