/*
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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 com.google.errorprone;

import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import java.net.URL;
import java.net.URLClassLoader;
import javax.tools.JavaFileManager;

/**
 * A classloader that allows plugins to access the Error Prone classes from the compiler classpath.
 */
// TODO(cushon): consolidate with Bazel's ClassLoaderMaskingPlugin
public class MaskedClassLoader extends ClassLoader {

  /**
   * An alternative to {@link JavacFileManager#preRegister(Context)} that installs a {@link
   * MaskedClassLoader}.
   */
  public static void preRegisterFileManager(Context context) {
    context.put(
        JavaFileManager.class,
        new Context.Factory<JavaFileManager>() {
          @Override
          public JavaFileManager make(Context c) {
            return new JavacFileManager(c, true, null) {
              @Override
              protected ClassLoader getClassLoader(URL[] urls) {
                return new URLClassLoader(
                    urls, new MaskedClassLoader(JavacFileManager.class.getClassLoader()));
              }
            };
          }
        });
  }

  public MaskedClassLoader(ClassLoader parent) {
    super(parent);
  }

  @Override
  protected Class<?> findClass(String name) throws ClassNotFoundException {
    int idx = name.lastIndexOf('.');
    if (idx == -1) {
      throw new ClassNotFoundException(name);
    }
    String packageName = name.substring(0, idx);
    switch (packageName) {
      case "com.google.errorprone":
      case "org.checkerframework.dataflow":
        return Class.forName(name);
      default:
        throw new ClassNotFoundException(name);
    }
  }
}

@@ -1922,200 +1922,27 @@
    i
-nt idx = name.lastIndexOf('.');%0A    if (idx == -1) %7B%0A      throw new ClassNotFoundException(name);%0A    %7D%0A    String packageName = name.substring(0, idx);%0A    switch (packageName) %7B%0A      case 
+f (name.startsWith(
 %22com
@@ -1963,22 +1963,39 @@
 rone
-%22:
+.%22)
 %0A      
-case 
+  %7C%7C name.startsWith(
 %22org
@@ -2024,13 +2024,15 @@
 flow
-%22:%0A  
+.%22)) %7B%0A
     
@@ -2069,21 +2069,17 @@
     
-  default:%0A  
+%7D else %7B%0A
     

Fix class loading issue with error prone plugins