text:
package org.jruby.runtime.load;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import java.util.zip.ZipException;
import org.jruby.CompatVersion;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyFile;
import org.jruby.RubyHash;
import org.jruby.RubyString;
import org.jruby.ast.executable.Script;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.Constants;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.JRubyFile;

/**
 * How require works in JRuby
 * When requiring a name from Ruby, JRuby will first remove any file extension it knows about,
 * thereby making it possible to use this string to see if JRuby has already loaded
 * the name in question. If a .rb extension is specified, JRuby will only try
 * those extensions when searching. If a .so, .o, .dll, or .jar extension is specified, JRuby
 * will only try .so or .jar when searching. Otherwise, JRuby goes through the known suffixes
 * (.rb, .rb.ast.ser, .so, and .jar) and tries to find a library with this name. The process for finding a library follows this order
 * for all searchable extensions:
 *

 *
First, check if the name starts with 'jar:', then the path points to a jar-file resource which is returned.

 *
Second, try searching for the file in the current dir

 *
Then JRuby looks through the load path trying these variants:
 *

 *
See if the current load path entry starts with 'jar:', if so check if this jar-file contains the name

 *
Otherwise JRuby tries to construct a path by combining the entry and the current working directy, and then see if
 *         a file with the correct name can be reached from this point.

 *

 *

 *
If all these fail, try to load the name as a resource from classloader resources, using the bare name as
 *     well as the load path entries

 *
When we get to this state, the normal JRuby loading has failed. At this stage JRuby tries to load
 *     Java native extensions, by following this process:
 *

 *
First it checks that we haven't already found a library. If we found a library of type JarredScript, the method continues.

 *
The first step is translating the name given into a valid Java Extension class name. First it splits the string into
 *     each path segment, and then makes all but the last downcased. After this it takes the last entry, removes all underscores
 *     and capitalizes each part separated by underscores. It then joins everything together and tacks on a 'Service' at the end.
 *     Lastly, it removes all leading dots, to make it a valid Java FWCN.

 *
If the previous library was of type JarredScript, we try to add the jar-file to the classpath

 *
Now JRuby tries to instantiate the class with the name constructed. If this works, we return a ClassExtensionLibrary. Otherwise,
 *     the old library is put back in place, if there was one.
 *

 *

 *
When all separate methods have been tried and there was no result, a LoadError will be raised.

 *
Otherwise, the name will be added to the loaded features, and the library loaded

 *

 *
 * How to make a class that can get required by JRuby
 *
First, decide on what name should be used to require the extension.
 * In this purely hypothetical example, this name will be 'active_record/connection_adapters/jdbc_adapter'.
 * Then create the class name for this require-name, by looking at the guidelines above. Our class should
 * be named active_record.connection_adapters.JdbcAdapterService, and implement one of the library-interfaces.
 * The easiest one is BasicLibraryService, where you define the basicLoad-method, which will get called
 * when your library should be loaded.

 *
The next step is to either put your compiled class on JRuby's classpath, or package the class/es inside a
 * jar-file. To package into a jar-file, we first create the file, then rename it to jdbc_adapter.jar. Then
 * we put this jar-file in the directory active_record/connection_adapters somewhere in JRuby's load path. For
 * example, copying jdbc_adapter.jar into JRUBY_HOME/lib/ruby/site_ruby/1.8/active_record/connection_adapters
 * will make everything work. If you've packaged your extension inside a RubyGem, write a setub.rb-script that
 * copies the jar-file to this place.

 *
If you don't want to have the name of your extension-class to be prescribed, you can also put a file called
 * jruby-ext.properties in your jar-files META-INF directory, where you can use the key <full-extension-name>.impl
 * to make the extension library load the correct class. An example for the above would have a jruby-ext.properties
 * that contained a ruby like: "active_record/connection_adapters/jdbc_adapter=org.jruby.ar.JdbcAdapter". (NOTE: THIS
 * FEATURE IS NOT IMPLEMENTED YET.)

 *
 * @author jpetersen
 */
public class LoadService {
    private enum SuffixType {
        Source, Extension, Both, Neither;

        public static final String[] sourceSuffixes = { ".class", ".rb" };
        public static final String[] extensionSuffixes = { ".so", ".jar" };
        private static final String[] allSuffixes = { ".class", ".rb", ".so", ".jar" };
        private static final String[] emptySuffixes = { "" };

        public String[] getSuffixes() {
            switch (this) {
            case Source:
                return sourceSuffixes;
            case Extension:
                return extensionSuffixes;
            case Both:
                return allSuffixes;
            case Neither:
                return emptySuffixes;
            }
            throw new RuntimeException("Unknown SuffixType: " + this);
        }
    }
    protected static final Pattern sourcePattern = Pattern.compile("\\.(?:rb)$");
    protected static final Pattern extensionPattern = Pattern.compile("\\.(?:so|o|dll|jar)$");

    protected RubyArray loadPath;
    protected RubyArray loadedFeatures;
    protected List loadedFeaturesInternal;
//    protected final Set firstLineLoadedFeatures = Collections.synchronizedSet(new HashSet());
    protected final Map<String, Library> builtinLibraries = new HashMap<String, Library>();

    protected final Map<String, JarFile> jarFiles = new HashMap<String, JarFile>();

    protected final Map<String, IAutoloadMethod> autoloadMap = new HashMap<String, IAutoloadMethod>();

    protected final Ruby runtime;

    public LoadService(Ruby runtime) {
        this.runtime = runtime;
    }

    public void init(List additionalDirectories) {
        loadPath = RubyArray.newArray(runtime);
        loadedFeatures = RubyArray.newArray(runtime);
        loadedFeaturesInternal = Collections.synchronizedList(loadedFeatures);

        // add all startup load paths to the list first
        for (Iterator iter = additionalDirectories.iterator(); iter.hasNext();) {
            addPath((String) iter.next());
        }

        // add $RUBYLIB paths
       RubyHash env = (RubyHash) runtime.getObject().fastGetConstant("ENV");
       RubyString env_rubylib = runtime.newString("RUBYLIB");
       if (env.has_key_p(env_rubylib).isTrue()) {
           String rubylib = env.op_aref(runtime.getCurrentContext(), env_rubylib).toString();
           String[] paths = rubylib.split(File.pathSeparator);
           for (int i = 0; i < paths.length; i++) {
               addPath(paths[i]);
           }
       }

        // wrap in try/catch for security exceptions in an applet
        if (!Ruby.isSecurityRestricted()) {
          String jrubyHome = runtime.getJRubyHome();
          if (jrubyHome != null) {
              char sep = '/';
              String rubyDir = jrubyHome + sep + "lib" + sep + "ruby" + sep;

              // If we're running in 1.9 compat mode, add Ruby 1.9 libs to path before 1.8 libs
              if (runtime.is1_9()) {
                  addPath(rubyDir + "site_ruby" + sep + Constants.RUBY1_9_MAJOR_VERSION);
                  addPath(rubyDir + "site_ruby");
                  addPath(rubyDir + Constants.RUBY1_9_MAJOR_VERSION);
                  addPath(rubyDir + Constants.RUBY1_9_MAJOR_VERSION + sep + "java");
              }

              // Add 1.8 libs
              addPath(rubyDir + "site_ruby" + sep + Constants.RUBY_MAJOR_VERSION);
              addPath(rubyDir + "site_ruby");
              addPath(rubyDir + Constants.RUBY_MAJOR_VERSION);
              addPath(rubyDir + Constants.RUBY_MAJOR_VERSION + sep + "java");

              // Added to make sure we find default distribution files within jar file.
              // TODO: Either make jrubyHome become the jar file or allow "classpath-only" paths
              addPath("lib" + sep + "ruby" + sep + Constants.RUBY_MAJOR_VERSION);
          }
        }

        // "." dir is used for relative path loads from a given file, as in require '../foo/bar'
        if (runtime.getSafeLevel() == 0) {
            addPath(".");
        }
    }

    private void addLoadedFeature(RubyString loadNameRubyString) {
        loadedFeaturesInternal.add(loadNameRubyString);
    }

    private void addPath(String path) {
        // Empty paths do not need to be added
        if (path == null || path.length() == 0) return;

        synchronized(loadPath) {
            loadPath.append(runtime.newString(path.replace('\\', '/')));
        }
    }

    public void load(String file, boolean wrap) {
        if(!runtime.getProfile().allowLoad(file)) {
            throw runtime.newLoadError("No such file to load -- " + file);
        }

        SearchState state = new SearchState(file);
        state.prepareLoadSearch(file);

        Library library = findBuiltinLibrary(state, state.searchFile, state.suffixType);
        if (library == null) library = findLibraryWithoutCWD(state, state.searchFile, state.suffixType);

        if (library == null) {
            library = findLibraryWithClassloaders(state, state.searchFile, state.suffixType);
            if (library == null) {
                throw runtime.newLoadError("No such file to load -- " + file);
            }
        }
        try {
            library.load(runtime, wrap);
        } catch (IOException e) {
            if (runtime.getDebug().isTrue()) e.printStackTrace();
            throw runtime.newLoadError("IO error -- " + file);
        }
    }

    public SearchState findFileForLoad(String file) throws AlreadyLoaded {
        SearchState state = new SearchState(file);
        state.prepareRequireSearch(file);

        for (LoadSearcher searcher : searchers) {
            if (searcher.shouldTrySearch(state)) {
                searcher.trySearch(state);
            } else {
                continue;
            }
        }

        return state;
    }

    public boolean smartLoad(final String file) {
        checkEmptyLoad(file);

        try {
            SearchState state = findFileForLoad(file);
            return tryLoadingLibraryOrScript(runtime, state);
        } catch (AlreadyLoaded al) {
            // Library has already been loaded in some form, bail out
            return false;
        }
    }

    public boolean require(String file) {
        if(!runtime.getProfile().allowRequire(file)) {
            throw runtime.newLoadError("No such file to load -- " + file);
        }
        return smartLoad(file);
    }

    public IRubyObject getLoadPath() {
        return loadPath;
    }

    public IRubyObject getLoadedFeatures() {
        return loadedFeatures;
    }

    public IAutoloadMethod autoloadFor(String name) {
        return autoloadMap.get(name);
    }

    public void removeAutoLoadFor(String name) {
        autoloadMap.remove(name);
    }

    public IRubyObject autoload(String name) {
        IAutoloadMethod loadMethod = autoloadMap.remove(name);
        if (loadMethod != null) {
            return loadMethod.load(runtime, name);
        }
        return null;
    }

    public void addAutoload(String name, IAutoloadMethod loadMethod) {
        autoloadMap.put(name, loadMethod);
    }

    public void addBuiltinLibrary(String name, Library library) {
        builtinLibraries.put(name, library);
    }

    public void removeBuiltinLibrary(String name) {
        builtinLibraries.remove(name);
    }

    public void removeInternalLoadedFeature(String name) {
        loadedFeaturesInternal.remove(name);
    }

    private boolean featureAlreadyLoaded(RubyString loadNameRubyString) {
        return loadedFeaturesInternal.contains(loadNameRubyString);
    }

    private boolean isJarfileLibrary(SearchState state, final String file) {
        return state.library instanceof JarredScript && file.endsWith(".jar");
    }

    private void removeLoadedFeature(RubyString loadNameRubyString) {

        loadedFeaturesInternal.remove(loadNameRubyString);
    }

    private void reraiseRaiseExceptions(Throwable e) throws RaiseException {

        if (e instanceof RaiseException) {
            throw (RaiseException) e;
        }
    }

    public interface LoadSearcher {
        public boolean shouldTrySearch(SearchState state);
        public void trySearch(SearchState state) throws AlreadyLoaded;
    }

    public class AlreadyLoaded extends Exception {
        private RubyString searchNameString;

        public AlreadyLoaded(RubyString searchNameString) {
            this.searchNameString = searchNameString;
        }

        public RubyString getSearchNameString() {
            return searchNameString;
        }
    }

    public class BailoutSearcher implements LoadSearcher {
        public boolean shouldTrySearch(SearchState state) {
            return true;
        }

        public void trySearch(SearchState state) throws AlreadyLoaded {
            for (String suffix : state.suffixType.getSuffixes()) {
                String searchName = state.searchFile + suffix;
                RubyString searchNameString = RubyString.newString(runtime, searchName);
                if (featureAlreadyLoaded(searchNameString)) {
                    throw new AlreadyLoaded(searchNameString);
                }
            }
        }
    }

    public class NormalSearcher implements LoadSearcher {
        public boolean shouldTrySearch(SearchState state) {
            return state.library == null;
        }

        public void trySearch(SearchState state) {
            state.library = findLibraryWithoutCWD(state, state.searchFile, state.suffixType);
        }
    }

    public class ClassLoaderSearcher implements LoadSearcher {
        public boolean shouldTrySearch(SearchState state) {
            return state.library == null;
        }

        public void trySearch(SearchState state) {
            state.library = findLibraryWithClassloaders(state, state.searchFile, state.suffixType);
        }
    }

    public class ExtensionSearcher implements LoadSearcher {
        public boolean shouldTrySearch(SearchState state) {
            return (state.library == null || state.library instanceof JarredScript) && !state.searchFile.equalsIgnoreCase("");
        }

        public void trySearch(SearchState state) {
            // This code exploits the fact that all .jar files will be found for the JarredScript feature.
            // This is where the basic extension mechanism gets fixed
            Library oldLibrary = state.library;

            // Create package name, by splitting on / and joining all but the last elements with a ".", and downcasing them.
            String[] all = state.searchFile.split("/");

            StringBuilder finName = new StringBuilder();
            for(int i=0, j=(all.length-1); i<j; i++) {
                finName.append(all[i].toLowerCase()).append(".");
            }

            try {
                // Make the class name look nice, by splitting on _ and capitalize each segment, then joining
                // the, together without anything separating them, and last put on "Service" at the end.
                String[] last = all[all.length-1].split("_");
                for(int i=0, j=last.length; i<j; i++) {
                    finName.append(Character.toUpperCase(last[i].charAt(0))).append(last[i].substring(1));
                }
                finName.append("Service");

                // We don't want a package name beginning with dots, so we remove them
                String className = finName.toString().replaceAll("^\\.*","");

                // If there is a jar-file with the required name, we add this to the class path.
                if(state.library instanceof JarredScript) {
                    // It's _really_ expensive to check that the class actually exists in the Jar, so
                    // we don't do that now.
                    runtime.getJRubyClassLoader().addURL(((JarredScript)state.library).getResource().getURL());
                }

                // quietly try to load the class
                Class theClass = runtime.getJavaSupport().loadJavaClassQuiet(className);
                state.library = new ClassExtensionLibrary(theClass);
            } catch (Exception ee) {
                state.library = null;
                runtime.getGlobalVariables().set("$!", runtime.getNil());
            }

            // If there was a good library before, we go back to that
            if(state.library == null && oldLibrary != null) {
                state.library = oldLibrary;
            }
        }
    }

    public class ScriptClassSearcher implements LoadSearcher {
        public class ScriptClassLibrary implements Library {
            private Script script;

            public ScriptClassLibrary(Script script) {
                this.script = script;
            }

            public void load(Ruby runtime, boolean wrap) {
                runtime.loadScript(script);
            }
        }

        public boolean shouldTrySearch(SearchState state) {
            return state.library == null;
        }

        public void trySearch(SearchState state) throws RaiseException {
            // no library or extension found, try to load directly as a class
            Script script;
            String className = buildClassName(state.searchFile);
            int lastSlashIndex = className.lastIndexOf('/');
            if (lastSlashIndex > -1 && lastSlashIndex < className.length() - 1 && !Character.isJavaIdentifierStart(className.charAt(lastSlashIndex + 1))) {
                if (lastSlashIndex == -1) {
                    className = "_" + className;
                } else {
                    className = className.substring(0, lastSlashIndex + 1) + "_" + className.substring(lastSlashIndex + 1);
                }
            }
            className = className.replace('/', '.');
            try {
                Class scriptClass = Class.forName(className);
                script = (Script) scriptClass.newInstance();
            } catch (Exception cnfe) {
                throw runtime.newLoadError("no such file to load -- " + state.searchFile);
            }
            state.library = new ScriptClassLibrary(script);
        }
    }

    public class SearchState {
        public Library library;
        public String loadName;
        public SuffixType suffixType;
        public String searchFile;

        public SearchState(String file) {
            loadName = file;
        }

        public void prepareRequireSearch(final String file) {
            // if an extension is specified, try more targetted searches
            if (file.lastIndexOf('.') > file.lastIndexOf('/')) {
                Matcher matcher = null;
                if ((matcher = sourcePattern.matcher(file)).find()) {
                    // source extensions
                    suffixType = SuffixType.Source;

                    // trim extension to try other options
                    searchFile = file.substring(0, matcher.start());
                } else if ((matcher = extensionPattern.matcher(file)).find()) {
                    // extension extensions
                    suffixType = SuffixType.Extension;

                    // trim extension to try other options
                    searchFile = file.substring(0, matcher.start());
                } else {
                    // unknown extension, fall back to search with extensions
                    suffixType = SuffixType.Both;
                    searchFile = file;
                }
            } else {
                // try all extensions
                suffixType = SuffixType.Both;
                searchFile = file;
            }
        }

        public void prepareLoadSearch(final String file) {
            // if a source extension is specified, try all source extensions
            if (file.lastIndexOf('.') > file.lastIndexOf('/')) {
                Matcher matcher = null;
                if ((matcher = sourcePattern.matcher(file)).find()) {
                    // source extensions
                    suffixType = SuffixType.Source;

                    // trim extension to try other options
                    searchFile = file.substring(0, matcher.start());
                } else {
                    // unknown extension, fall back to exact search
                    suffixType = SuffixType.Neither;
                    searchFile = file;
                }
            } else {
                // try only literal search
                suffixType = SuffixType.Neither;
                searchFile = file;
            }
        }
    }

    private boolean tryLoadingLibraryOrScript(Ruby runtime, SearchState state) {
        // attempt to load the found library
        RubyString loadNameRubyString = RubyString.newString(runtime, state.loadName);
        try {
            synchronized (loadedFeaturesInternal) {
                if (loadedFeaturesInternal.contains(loadNameRubyString)) {
                    return false;
                } else {
                    addLoadedFeature(loadNameRubyString);
                }
            }

            // otherwise load the library we've found
            state.library.load(runtime, false);
            return true;
        } catch (Throwable e) {
            if(isJarfileLibrary(state, state.searchFile)) {
                return true;
            }

            removeLoadedFeature(loadNameRubyString);
            reraiseRaiseExceptions(e);

            if(runtime.getDebug().isTrue()) e.printStackTrace();

            RaiseException re = runtime.newLoadError("IO error -- " + state.searchFile);
            re.initCause(e);
            throw re;
        }
    }

    private final List<LoadSearcher> searchers = new ArrayList<LoadSearcher>();
    {
        searchers.add(new BailoutSearcher());
        searchers.add(new NormalSearcher());
        searchers.add(new ClassLoaderSearcher());
        searchers.add(new ExtensionSearcher());
        searchers.add(new ScriptClassSearcher());
    }

    private String buildClassName(String className) {
        // Remove any relative prefix, e.g. "./foo/bar" becomes "foo/bar".
        className = className.replaceFirst("^\\.\\/", "");
        if (className.lastIndexOf(".") != -1) {
            className = className.substring(0, className.lastIndexOf("."));
        }
        className = className.replace("-", "_minus_").replace('.', '_');
        return className;
    }

    private void checkEmptyLoad(String file) throws RaiseException {
        if (file.equals("")) {
            throw runtime.newLoadError("No such file to load -- " + file);
        }
    }

    private Library findBuiltinLibrary(SearchState state, String baseName, SuffixType suffixType) {
        for (String suffix : suffixType.getSuffixes()) {
            String namePlusSuffix = baseName + suffix;
            if (builtinLibraries.containsKey(namePlusSuffix)) {
                state.loadName = namePlusSuffix;
                return builtinLibraries.get(namePlusSuffix);
            }
        }
        return null;
    }

    private Library findLibraryWithoutCWD(SearchState state, String baseName, SuffixType suffixType) {
        Library library = null;

        switch (suffixType) {
        case Both:
            library = findBuiltinLibrary(state, baseName, SuffixType.Source);
            if (library == null) library = createLibrary(state, tryResourceFromJarURL(state, baseName, SuffixType.Source));
            if (library == null) library = createLibrary(state, tryResourceFromLoadPathOrURL(state, baseName, SuffixType.Source));
            // If we fail to find as a normal Ruby script, we try to find as an extension,
            // checking for a builtin first.
            if (library == null) library = findBuiltinLibrary(state, baseName, SuffixType.Extension);
            if (library == null) library = createLibrary(state, tryResourceFromJarURL(state, baseName, SuffixType.Extension));
            if (library == null) library = createLibrary(state, tryResourceFromLoadPathOrURL(state, baseName, SuffixType.Extension));
            break;
        case Source:
        case Extension:
            // Check for a builtin first.
            library = findBuiltinLibrary(state, baseName, suffixType);
            if (library == null) library = createLibrary(state, tryResourceFromJarURL(state, baseName, suffixType));
            if (library == null) library = createLibrary(state, tryResourceFromLoadPathOrURL(state, baseName, suffixType));
            break;
        case Neither:
            library = createLibrary(state, tryResourceFromJarURL(state, baseName, SuffixType.Neither));
            if (library == null) library = createLibrary(state, tryResourceFromLoadPathOrURL(state, baseName, SuffixType.Neither));
            break;
        }

        return library;
    }

    private Library findLibraryWithClassloaders(SearchState state, String baseName, SuffixType suffixType) {
        for (String suffix : suffixType.getSuffixes()) {
            String file = baseName + suffix;
            LoadServiceResource resource = findFileInClasspath(file);
            if (resource != null) {
                state.loadName = file;
                return createLibrary(state, resource);
            }
        }
        return null;
    }

    private Library createLibrary(SearchState state, LoadServiceResource resource) {
        if (resource == null) {
            return null;
        }
        String file = state.loadName;
        if (file.contains(".so")) {
            throw runtime.newLoadError("JRuby does not support .so libraries from filesystem");
        } else if (file.endsWith(".jar")) {
            return new JarredScript(resource);
        } else if (file.endsWith(".class")) {
            return new JavaCompiledScript(resource);
        } else {
            return new ExternalScript(resource, file);
        }
    }

    private LoadServiceResource tryResourceFromCWD(SearchState state, String baseName,SuffixType suffixType) throws RaiseException {
        LoadServiceResource foundResource = null;

        for (String suffix : suffixType.getSuffixes()) {
            String namePlusSuffix = baseName + suffix;
            // check current directory; if file exists, retrieve URL and return resource
            try {
                JRubyFile file = JRubyFile.create(runtime.getCurrentDirectory(), RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
                if (file.isFile() && file.isAbsolute()) {
                    try {
                        foundResource = new LoadServiceResource(file.toURI().toURL(), namePlusSuffix);
                        state.loadName = namePlusSuffix;
                        break;
                    } catch (MalformedURLException e) {
                        throw runtime.newIOErrorFromException(e);
                    }
                }
            } catch (IllegalArgumentException illArgEx) {
            } catch (SecurityException secEx) {
            }
        }

        return foundResource;
    }

    private LoadServiceResource tryResourceFromJarURL(SearchState state, String baseName, SuffixType suffixType) {
        // if a jar or file URL, return load service resource directly without further searching
        LoadServiceResource foundResource = null;
        if (baseName.startsWith("jar:")) {
            for (String suffix : suffixType.getSuffixes()) {
                String namePlusSuffix = baseName + suffix;
                try {
                    foundResource = new LoadServiceResource(new URL(namePlusSuffix), namePlusSuffix);
                } catch (MalformedURLException e) {
                    throw runtime.newIOErrorFromException(e);
                }
                if (foundResource != null) {
                    state.loadName = namePlusSuffix;
                    break; // end suffix iteration
                }
            }
        } else if(baseName.startsWith("file:") && baseName.indexOf("!/") != -1) {
            for (String suffix : suffixType.getSuffixes()) {
                String namePlusSuffix = baseName + suffix;
                try {
                    JarFile file = new JarFile(namePlusSuffix.substring(5, namePlusSuffix.indexOf("!/")));
                    String filename = namePlusSuffix.substring(namePlusSuffix.indexOf("!/") + 2);
                    if(file.getJarEntry(filename) != null) {
                        foundResource = new LoadServiceResource(new URL("jar:" + namePlusSuffix), namePlusSuffix);
                    }
                } catch(Exception e) {}
                if (foundResource != null) {
                    state.loadName = namePlusSuffix;
                    break; // end suffix iteration
                }
            }
        }

        return foundResource;
    }

    private LoadServiceResource tryResourceFromLoadPathOrURL(SearchState state, String baseName, SuffixType suffixType) {
        LoadServiceResource foundResource = null;

        // if it's a ./ baseName, use CWD logic
        if (baseName.startsWith("./")) {
            foundResource = tryResourceFromCWD(state, baseName, suffixType);

            if (foundResource != null) {
                state.loadName = foundResource.getName();
                return foundResource;
            }
        }

        // if given path is absolute, just try it as-is (with extensions) and no load path
        if (new File(baseName).isAbsolute()) {
            for (String suffix : suffixType.getSuffixes()) {
                String namePlusSuffix = baseName + suffix;
                foundResource = tryResourceAsIs(namePlusSuffix);

                if (foundResource != null) {
                    state.loadName = namePlusSuffix;
                    return foundResource;
                }
            }

            return null;
        }

        Outer: for (Iterator pathIter = loadPath.getList().iterator(); pathIter.hasNext();) {
            // TODO this is really ineffient, and potentially a problem everytime anyone require's something.
            // we should try to make LoadPath a special array object.
            String loadPathEntry = ((IRubyObject)pathIter.next()).toString();

            if (loadPathEntry.equals(".")) {
                foundResource = tryResourceFromCWD(state, baseName, suffixType);

                if (foundResource != null) {
                    state.loadName = foundResource.getName();
                    break Outer;
                }
            } else {
                for (String suffix : suffixType.getSuffixes()) {
                    String namePlusSuffix = baseName + suffix;

                    if (loadPathLooksLikeJarURL(loadPathEntry)) {
                        foundResource = tryResourceFromJarURLWithLoadPath(namePlusSuffix, loadPathEntry);
                    } else {
                        foundResource = tryResourceFromLoadPath(namePlusSuffix, loadPathEntry);
                    }

                    if (foundResource != null) {
                        state.loadName = namePlusSuffix;
                        break Outer; // end suffix iteration
                    }
                }
            }
        }

        return foundResource;
    }

    private LoadServiceResource tryResourceFromJarURLWithLoadPath(String namePlusSuffix, String loadPathEntry) {
        LoadServiceResource foundResource = null;

        JarFile current = jarFiles.get(loadPathEntry);
        boolean isFileJarUrl = loadPathEntry.startsWith("file:") && loadPathEntry.indexOf("!/") != -1;
        String after = isFileJarUrl ? loadPathEntry.substring(loadPathEntry.indexOf("!/") + 2) + "/" : "";
        String before = isFileJarUrl ? loadPathEntry.substring(0, loadPathEntry.indexOf("!/")) : loadPathEntry;

        if(null == current) {
            try {
                if(loadPathEntry.startsWith("jar:")) {
                    current = new JarFile(loadPathEntry.substring(4));
                } else if (loadPathEntry.endsWith(".jar")) {
                    current = new JarFile(loadPathEntry);
                } else {
                    current = new JarFile(loadPathEntry.substring(5,loadPathEntry.indexOf("!/")));
                }
                jarFiles.put(loadPathEntry,current);
            } catch (ZipException ignored) {
                if (runtime.getInstanceConfig().isVerbose()) {
                    runtime.getErr().println("ZipException trying to access " + loadPathEntry + ", stack trace follows:");
                    ignored.printStackTrace(runtime.getErr());
                }
            } catch (FileNotFoundException ignored) {
            } catch (IOException e) {
                throw runtime.newIOErrorFromException(e);
            }
        }
        String canonicalEntry = after+namePlusSuffix;
        if(after.length()>0) {
            try {
                canonicalEntry = new File(after+namePlusSuffix).getCanonicalPath().substring(new File(".")
                                                     .getCanonicalPath().length()+1).replaceAll("\\\\","/");
            } catch(Exception e) {}
        }
        if (current != null && current.getJarEntry(canonicalEntry) != null) {
            try {
                if (loadPathEntry.endsWith(".jar")) {
                    foundResource = new LoadServiceResource(new URL("jar:file:" + loadPathEntry + "!/" + canonicalEntry), "/" + namePlusSuffix);
                } else if (loadPathEntry.startsWith("file:")) {
                    foundResource = new LoadServiceResource(new URL("jar:" + before + "!/" + canonicalEntry), loadPathEntry + "/" + namePlusSuffix);
                } else {
                    foundResource =  new LoadServiceResource(new URL("jar:file:" + loadPathEntry.substring(4) + "!/" + namePlusSuffix), loadPathEntry + namePlusSuffix);
                }
            } catch (MalformedURLException e) {
                throw runtime.newIOErrorFromException(e);
            }
        }

        return foundResource;
    }

    private boolean loadPathLooksLikeJarURL(String loadPathEntry) {
        return loadPathEntry.startsWith("jar:") || loadPathEntry.endsWith(".jar") || (loadPathEntry.startsWith("file:") && loadPathEntry.indexOf("!/") != -1);
    }

    private LoadServiceResource tryResourceFromLoadPath( String namePlusSuffix,String loadPathEntry) throws RaiseException {
        LoadServiceResource foundResource = null;

        try {
            if (!Ruby.isSecurityRestricted()) {
                String reportedPath = loadPathEntry + "/" + namePlusSuffix;
                JRubyFile actualPath;
                // we check length == 0 for 'load', which does not use load path
                if (new File(reportedPath).isAbsolute()) {
                    // it's an absolute path, use it as-is
                    actualPath = JRubyFile.create(loadPathEntry, RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
                } else {
                    // prepend ./ if . is not already there, since we're loading based on CWD
                    if (reportedPath.charAt(0) != '.') {
                        reportedPath = "./" + reportedPath;
                    }
                    actualPath = JRubyFile.create(JRubyFile.create(runtime.getCurrentDirectory(), loadPathEntry).getAbsolutePath(), RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
                }
                if (actualPath.isFile()) {
                    try {
                        foundResource = new LoadServiceResource(actualPath.toURI().toURL(), reportedPath);
                    } catch (MalformedURLException e) {
                        throw runtime.newIOErrorFromException(e);
                    }
                }
            }
        } catch (SecurityException secEx) {
        }

        return foundResource;
    }

    private LoadServiceResource tryResourceAsIs(String namePlusSuffix) throws RaiseException {
        LoadServiceResource foundResource = null;

        try {
            if (!Ruby.isSecurityRestricted()) {
                String reportedPath = namePlusSuffix;
                File actualPath;
                // we check length == 0 for 'load', which does not use load path
                if (new File(reportedPath).isAbsolute()) {
                    // it's an absolute path, use it as-is
                    actualPath = new File(RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
                } else {
                    // prepend ./ if . is not already there, since we're loading based on CWD
                    if (reportedPath.charAt(0) == '.' && reportedPath.charAt(1) == '/') {
                        reportedPath = reportedPath.replaceFirst("\\./", runtime.getCurrentDirectory());
                    }
                    actualPath = new File(RubyFile.expandUserPath(runtime.getCurrentContext(), reportedPath));
                }
                if (actualPath.isFile()) {
                    try {
                        foundResource = new LoadServiceResource(actualPath.toURI().toURL(), reportedPath);
                    } catch (MalformedURLException e) {
                        throw runtime.newIOErrorFromException(e);
                    }
                }
            }
        } catch (SecurityException secEx) {
        }

        return foundResource;
    }

    /**
     * this method uses the appropriate lookup strategy to find a file.
     * It is used by Kernel#require.
     *
     * @mri rb_find_file
     * @param name the file to find, this is a path name
     * @return the correct file
     */
    private LoadServiceResource findFileInClasspath(String name) {
        // Look in classpath next (we do not use File as a test since UNC names will match)
        // Note: Jar resources must NEVER begin with an '/'. (previous code said "always begin with a /")
        ClassLoader classLoader = runtime.getJRubyClassLoader();

        // handle security-sensitive case
        if (Ruby.isSecurityRestricted() && classLoader == null) {
            classLoader = runtime.getInstanceConfig().getLoader();
        }

        for (Iterator pathIter = loadPath.getList().iterator(); pathIter.hasNext();) {
            String entry = pathIter.next().toString();

            // if entry starts with a slash, skip it since classloader resources never start with a /
            if (entry.charAt(0) == '/' || (entry.length() > 1 && entry.charAt(1) == ':')) continue;

            // otherwise, try to load from classpath (Note: Jar resources always uses '/')
            URL loc = classLoader.getResource(entry + "/" + name);

            // Make sure this is not a directory or unavailable in some way
            if (isRequireable(loc)) {
                return new LoadServiceResource(loc, loc.getPath());
            }
        }

        // if name starts with a / we're done (classloader resources won't load with an initial /)
        if (name.charAt(0) == '/' || (name.length() > 1 && name.charAt(1) == ':')) return null;

        // Try to load from classpath without prefix. "A/b.rb" will not load as
        // "./A/b.rb" in a jar file.
        URL loc = classLoader.getResource(name);

        return isRequireable(loc) ? new LoadServiceResource(loc, loc.getPath()) : null;
    }

    /* Directories and unavailable resources are not able to open a stream. */
    private boolean isRequireable(URL loc) {
        if (loc != null) {
        	if (loc.getProtocol().equals("file") && new java.io.File(loc.getFile()).isDirectory()) {
        		return false;
        	}

        	try {
                loc.openConnection();
                return true;
            } catch (Exception e) {}
        }
        return false;
    }
}


text:
<?php

namespace Oro\Bundle\ImapBundle\Tests\Unit\Stub;

use Oro\Bundle\ImapBundle\Entity\UserEmailOrigin;

class TestUserEmailOrigin extends UserEmailOrigin
{
    public function __construct($id = null)
    {
        parent::__construct();
        $this->id = $id;
    }
}

redpajama_set_name: RedPajamaGithub


Overcoming a fear such as Tapinophobia - fear of being contagious was not so easy, but your book Energy Therapy was very helpful.
I did overcome my fear in a short time with the useful information I read and understood in this book.
I like how easy it was to do this myself instead of spending hundreds of dollars trying to find someone else to help me.
It is nice to know that I helped myself and succeeded.
I would recommend this book to anyone that needs some help getting over a phobia. Thank you again for the book.


In 2018, the State Property Fund launched the Unified database of property valuation reports for the purposes of taxation, which aims to prevent the property from undervaluing.
The State Property Fund has an access to this database , as well as notaries and appraisers. The last ones have the ability to access the database only through authorized electronic platforms. From the beginning of 2019, the cost of such access amounts to 1400 UAH, which are paid to register 1 evaluation report. To put it mildly, the competitive foundations of the work of theese platforms called into question. And these doubts "dispelled" after the latest changes to the Tax Code of Ukraine (Law of Ukraine dated November 23, 2018 No. 2628-VIII), under which authorization of a new platform needs obtaining consent from already existing ones. Want to work - ask permission from a competitor. The same changes also removed the Antimonopoly Committee of Ukraine from this issue.
On January 23, the Verkhovna Rada of Ukraine registered the draft law No. 9502, which proposes to exclude these norms from the Tax Code and ensure automatic release of non-personalized information from the Unified Reporting Database on the official website of the State Property Fund of Ukraine in real time.
We hope for support of this law in the Verkhovna Rada. Appraisers' services should be as accessible as possible to citizens who want to exercise their legal right to private property. Unfortunately, due to the high cost of intermediary services of the platforms, the cost of such an assessment is unreasonably high.


We have recently celebrated again the liturgies of Holy Week and the Easter Triduum. The first of these was the celebration of Palm Sunday.
The full title of this day, as provided in the Missal, shows us exactly what we celebrate on this day. Palm Sunday of the Passion of the Lord invites us all to celebrate not only the triumphant entry of Christ into Jerusalem, but also the events of the days that followed; his passion and death.
It is in the Introductory Rites of the Mass for Palm Sunday that we celebrate the actual 'Palm Sunday'. This can take the form of a procession at the principal Mass of the Sunday (as it does here at 9:00 am), or with a simple or solemn entrance (as we celebrate from the narthex) at the other Masses of the Sunday. We begin with the antiphon that quotes directly from the gospel, "Hosanna to the Son of David…" (Mt 21:9). We bless the palms (or olive branches or other greenery) that we will use and take home with us. We listen to the account of Jesus' entry to Jerusalem from the gospels, and then proceed into the church "like the crowds that acclaimed Jesus in Jerusalem." Song is an important part of the entrance and procession.
Finally, I would like to echo Fr Paul's words of thanks to those who were involved in the celebrations of Holy Week and the Easter Triduum.


text:
/ Nancy Sinatra
These Boots Are Made For Walkin'
from Boots
2:45 From $1.19
from Nancy & Lee
Bang Bang (My Baby Shot Me Down)
from How Does That Grab You?
Bang Bang (My Baby Shot Me Down) (My Baby Shot Me Down)
from Kill Bill Vol. 1 Original Soundtrack (PA Version [Explicit])
Some Velvet Morning
Preview Nancy Sinatra and Friends
Nancy Sinatra and Friends Nancy Sinatra 2019 From $11.99
Preview Like I Do
Like I Do Nancy Sinatra 2015 From $5.96
Preview Shifting Gears
Shifting Gears Nancy Sinatra 2013
Preview Sugartown (Nancy Sinatra & Friends)
Sugartown (Nancy Sinatra & Friends) Nancy Sinatra 2013 From $10.49
Preview Nancy Sinatra
Nancy Sinatra Nancy Sinatra 2013
Preview Song of Love for Danny
Song of Love for Danny Nancy Sinatra 2016 From $1.19
20 Albums & 1 Singles & EPs
Lulu, Diana Ross, Britney Spears, Cher, Dusty Springfield, Peggy Lee
Pop, 1990s, 1950s, 1960s, 2000s

redpajama_set_name: RedPajamaCommonCrawl


text:
Q: Do Android controls/widgets have choice of styles? I have a column of Checkboxes and associated EditTexts and I want one pair of these to have a distinct appearance because it has a distinct significance.
Short of writing custom controls, or using custom drawables, does Android have any way to style or alter the appearance of basic controls like buttons, checkboxes, etc, in the XML where the control is declared?    Or is there just one native style or appearance for all Android Checkboxes, Buttons, EditTexts, etc?
Thanks in advance.

A: You can almost custom everything related to style:
http://developer.android.com/guide/topics/ui/themes.html
In fact, an Android Button is just a TextView with different style. In source code, the Button is just an extend to TextView with no overriding.

redpajama_set_name: RedPajamaStackExchange


text:
Tag Archives: chris grayling
really expensive legal researchers
Posted on February 16, 2015 by suesspiciousminds
Lindner v Rawlins 2015
http://www.familylaw.co.uk/news_and_comment/lindner-v-rawlins-2015-ewca-civ-51#.VNymu_msVic
In this case, the Court of Appeal were dealing with an appeal from a husband relating to divorce proceedings about a Judge's refusal to order the police to provide him with information / a statement. There had been a complaint from the wife (or the wife's new partner, hence the husband's interest) about an allegation of criminal damage to a Sky tv satellite dish.
The husband had done a lot of legal research, but was sadly relying on the Civil Procedure Rules and a case called Durham County Council v Dunn [2012] EWCA Civ 1654 which relates to the duties of disclosure and inspection owed by one party in litigation to the other. Neither were really relevant in this case, which was Family Procedure Rules and relating to an order for disclosure against a third party. I personally think that the husband had made a pretty decent fist of assembling his case, he'd just started from the wrong assumptions.
The Court of Appeal refused the appeal, but this is the relevant bit and why it is worth reporting.
The second observation is in no way a criticism of the husband who presented his case to us courteously and as comprehensively as he could. Nevertheless, the fact that he was not represented meant that he had approached it on a mistaken basis. The task that would normally have been fulfilled by the parties' legal representatives, of finding relevant documents amongst the material presented, and researching the law and its application to the facts of the case, had to be done by the judges of the Court of Appeal instead. This is not a satisfactory state of affairs as the time taken to attend to this is considerable and cannot be spared in what is already a very busy court.
I agree with the judgment of Black LJ. I also wish, wholeheartedly, to endorse her observation at [32]. The procedural issue with which this appeal is concerned is technical and unusual. The husband could not be expected to have mastered this area of the law in order to be able to present his appeal in a way that assisted the court. The wife was neither present nor represented. Yet again, the court was without any legal assistance and had to spend time researching the law for itself then attempting to apply it to the relevant facts in order to arrive at the correct legal answer. To do the latter exercise meant that the court itself had to trawl through a large amount of documents in the file. All this involves an expensive use of judicial time, which is in short supply as it is. Money may have been saved from the legal aid funds, but an equal amount of expense, if not more, has been incurred in terms of the costs of judges' and court time. The result is that there is, in fact, no economy at all. Worse, this way of dealing with cases runs the risk that a correct result will not be reached because the court does not have the legal assistance of counsel that it should have and the court has no other legal assistance available to it.
It is quite easy to read this as a kicking to Chris[tian] Gray-ling and the devillish torments he has assembled for justice in his Red Room (and there's an image you will be stuck with for the rest of the day, sorry), but I'm not quite sure that it is.
We don't specifically get told what the husband does for a living, but we do know that there is a matrimonial home of a size for a family of four (husband, wife, two kids) and that it is in the Bromley area (because that was the original Court), so one might hazard a guess that to obtain and sustain a mortgage both parties would probably fall outside of the income limits for legal aid, even before the reforms. The husband is clearly bright and capable – one might criticise him for focussing his intellect in the wrong direction rather than moving on, but that's by the by.
If I were staking money on it, it would be that this husband would not have qualified for free legal advice and representation even before Chris Grayling got his hands on the legal reins and made his changes of course.
If this was supposed to be an economy though, it isn't. The Legal Aid Agency might have saved a few thousand in legal fees for someone to research and advise the husband (and they'd have advised against an appeal) but the taxpayer overall has lost out because three very senior Judges had to spend valuable time researching and working out the proper basis for the appeal and whether or not it should be granted.
Posted in case law, costs and tagged chris grayling, Court of Appeal, court of appeal complaining that cost savings are no saving at all, laspo, legal aid, legal aid cuts, lindner v rawlins. Bookmark the permalink.
Pannick attack
I know some of my readers are not in the Chris Grayling fan club (which is a shame, because you get a lovely badge and a code book that allows you to translate what he's saying into something that resembles common sense – hint, you just say the opposite of what he's saying)
so you might enjoy Lord Pannick tearing him a new one, and giving everyone a route map to crush the new judicial review legislation into oblivion in the future
Lord Pannick (CB): My Lords, I am very pleased that the Government have given way on the issue of principle in Motion B and have indicated that the identity of those contributing up to £1,500 funding for a judicial review will not need to be disclosed. The Minister said that our earlier debates on these issues had been highly intelligent. Without, I hope, debasing the currency, I want to make some observations.
The issue of principle is that the courts will now retain a power to hear a judicial review even if it is said that the alleged defect would not have made a difference in the individual's case. I would have preferred the concession to be drafted in more generous language than an exceptional public interest, but concession it is. As the Lord Chancellor said in the House of Commons on 13 January at col. 811, and as the Minister confirmed this afternoon, it will be for the judges to decide how and when that test should apply. Indeed it will.
In applying the criterion, I am sure that the courts will have very much in mind Mr Grayling's explanation of the purpose of the clause. He said that it is designed to prevent judicial reviews being heard when they are,
"based on relatively minor procedural defects in a process of consultation … That is what these proposals are all about".—[
, Commons, 13/1/15; col. 812.]
I am confident that the courts will have careful regard to those explanations by the Lord Chancellor and that if the judicial review is not concerned with minor procedural defects but with allegations of systematic or deliberate wrongdoing, or errors of law in the interpretation of statutes which have a general effect, the discretion will be exercised so that the case is heard in the traditional way, as it should be.
21 Jan 2015 : Column 1345
In applying the clause, I would also expect the courts to pay close regard to what the noble and learned Lord, Lord Woolf, then Lord Chief Justice, who I am delighted to see in his place today, said in R v Offen, 2001, 1 Weekly Law Reports 253. In the Court of Appeal, the noble and learned Lord was considering Section 2 of the Crime (Sentences) Act 1997, which requires courts to impose an automatic life sentence on a person convicted of a second serious crime,
"unless the court is of the opinion that there are exceptional circumstances".
At paragraph 79 of his judgment, Lord Woolf said that the meaning of "exceptional" depended on the statutory purpose, and where the statutory mischief did not exist, the case was indeed exceptional.
Applying that approach, as I am sure that the courts will do in the present context, the judges will be able to say—and I hope that they will—that the statutory purpose here is the very limited one identified by Mr Grayling of striking out judicial reviews which raised what he describes as "relatively minor procedural defects".
Other cases, particularly those raising allegations of substantial errors of law or of systematic wrongdoing are outside the legislative aim and are therefore, on the approach of the noble and learned Lord, Lord Woolf, exceptional. They can be heard in the normal way. For those reasons, I am confident that we have arrived at a tolerable result at the end of this saga.
We have arrived at a sensible solution because, and only because, this House was prepared twice to disagree with the House of Commons. It should be noted that the concern about Mr Grayling's proposals was expressed across this House. My amendments were supported by a very large majority of Cross Benchers who voted; they were signed by the noble and learned Lord, Lord Woolf. The amendments were supported by the Labour Benches, led on this occasion by the noble Lord, Lord Beecham, with his customary wit and fire; he signed the original amendments. There was a very substantial rebellion in support of retaining judicial discretion from the Liberal Democrat Benches; the noble Lord, Lord Carlile of Berriew, also signed the original amendments. Also of importance on the Floor of the House and behind the scenes, there was substantial support from noble Lords on the Conservative Benches who are wise and experienced, and respectful of the value of the rule of law, with some forceful speeches in support of retaining judicial discretion, in particular from the noble Lord, Lord Deben. I am very grateful for all that support.
I express particular thanks to the Minister, the noble Lord, Lord Faulks, who has assisted the House by the force and clarity—indeed, the good humour—of his advocacy as the acceptable face of the Lord Chancellor's department at all stages of the Bill. I know that he has worked tirelessly and successfully behind the scenes to arrive at a compromise which can be agreed by the Lord Chancellor and by noble Lords concerned about this clause. That is a remarkable achievement.
I should add one further observation and I do so with regret, but it needs to be said. I regret that on 13 January, when the House of Commons considered this matter for the final time, a Lord Chancellor again expressed comments that display an astonishing lack of understanding about the role of judicial review—one of the cornerstones of the rule of law. Judicial review does not, as Mr Grayling complained at col. 819, involve public bodies being "blackmailed". He also suggested,
"severe doubts about whether secondary legislation should be subject to judicial review".
These doubts appear to have no basis whatever other than the fact that the courts have, on a number of occasions in the last year, held that regulations made by the Lord Chancellor were outside the scope of his statutory powers.
Furthermore, judicial review is not, as the Lord Chancellor again suggested,
"now overtly used by campaign groups and third parties to seek to disrupt the process of government".—[
, Commons, 13/1/15; cols. 819-20.]
Such comments make no sensible contribution to the debate. They demean the office of Lord Chancellor because they disrespect and undermine the vital role of judicial review in ensuring that the business of government is conducted lawfully.
However inconvenient and embarrassing it is to Mr Grayling to have his decisions repeatedly ruled to be unlawful by our courts, however much he may resent the delays and costs of government illegality being exposed in court and however much he may prefer to focus on the identity of the claimant rather than the substance of their legal complaint, it remains the vital role of judicial review in this country to hold Ministers and civil servants to account in public, not for the merits of their decisions but for their compliance with the law of the land as stated by Parliament. The discipline of the law plays a vital role in promoting the high standards of administration in this country that we are in danger of taking for granted. It helps to concentrate—and rightly so—the mind of a Minister or civil servant taking a decision whose legality he or she will be answerable for in public before an independent judge.
Your Lordships' Constitution Committee said recently, in its excellent report on the office of Lord Chancellor, that the Lord Chancellor should have,
"a clear understanding of his or her duties in relation to the rule of law and a willingness to speak up for that principle in dealings with ministerial colleagues, including the Prime Minister".
Every time this Lord Chancellor addresses judicial review, he contradicts that essential guidance. I am very pleased that this House has performed its role in requiring the House of Commons and the Lord Chancellor to think again, and in securing acceptable compromises that will enable judicial review to continue to perform its valuable and essential functions.
If you want to see the Hansard debate (the rest of it is not quite so amazing as this, which actually made me want to stand on my desk and say "captain, my captain") it is here
http://www.publications.parliament.uk/pa/ld201415/ldhansrd/text/150121-0001.htm#15012189000542
Judicial review is a thorn in my side, as it is for anyone who works for a public body – there is little that ruins your month more than getting a judicial review claim letter, it is a miserable and painful experience. But that pain is part of the price you pay for having a State that can be properly held to account for behaving unreasonable, irrationally or unfairly in its dealings with people. Many people like me learn to tolerate and even love the thorn, and its a shame that our Lord Chancellor can't see it that way.
But then, if you can't grasp that your actual role is to be a Check and Balance, you might not understand the importance of Checks and Balances.
Posted in Uncategorized and tagged chris grayling, judicial review, lord chancellor, lord pannick. Bookmark the permalink.
Q v Q – an impasse
Posted on June 9, 2014 by suesspiciousminds
You may not be aware (it depends if you spend too much time online), that on the internet QQ in effect means stop whining, or crying about something (the Q's looking like a pair of eyes with tears coming out of them) – if you say that someone is QQ-ing, it means that they are whining like a child about something. [ it comes up a lot]
In Q v Q 2014, the President tackles what's been a long-standing problem in family law proceedings, particularly family law. And brings tears to the eyes of the Legal Aid Agency, Her Majesty's Court Service and our beloved minister Chris Grayling. QQ indeed.
http://www.bailii.org/ew/cases/EWFC/HCJ/2014/7.html
For many years now, the Legal Aid Agency, under its various guises, has had a policy that they will withdraw public funding from someone who has legal aid (free legal representation) if there is an independent report which is heavily against them. Back when I was doing private law, this quite often used to be the CAFCASS report, and you'd end up in a position where your client's legal aid would be pulled two days before a final hearing because the CAFCASS report was very damning.
Of course, the report is at that point untested evidence – for the Legal Aid Agency to presume that just because on paper the CAFCASS officer is against your client, there would be no prospect of getting them to change their mind or getting the Court to disagree with their conclusions is presumptuous in the extreme. If all the Court did was agree with what the CAFCASS report said on paper, then we wouldn't need Judges at all, and CAFCASS could be the investigators and arbiters of final outcomes. [Indeed, on a few such cases I recommended my client for free, and got a favourable decision for them]
That's not a new thing, but in this case, the father was publicly funded and an expert was instructed (it was his expert) and the expert was heavily against him. His funding was pulled.
The father was therefore appearing in person, and requiring an interpreter. He wanted to be represented and he wanted to challenge the expert report. The mother, who was represented, invited the Court to dismiss his application and make a section 91(14) order prohibiting him from making further applications without leave of the Court.
The Court were unhappy about the impact of proceeding without representation for the father on his article 6 and article 8 rights, and mooted a series of possible solutions, before adjourning the case and inviting the Legal Aid Agency and Ministry to intervene to discuss those possible solutions.
In the circumstances, what I propose to do is this: I propose to adjourn this matter for, I emphasise, a short time, inviting the Ministry of Justice – or it may be the Secretary of State for Justice or it might be the Minister for the Courts and Legal Aid – to intervene in the proceedings to make such submissions as are appropriate in relation, in particular, to the argument that in a situation such as this the expenditure which is not available from the Legal Aid Agency but which, in the view of the court, if it be the view of the court, is necessary to be incurred to ensure proceedings which are just and fair, can be met either from the Legal Aid Agency by route of the other certificate, the mother's certificate, or directly at the expense of the court.
I appreciate that this is a case in which, as Miss Spooner points out, there have already been too many adjournments of supposedly final hearings. I appreciate it is a case which has been going on for the best part of four years, which is depressing to say the least. And I am very conscious of the fact that the mere existence of the proceedings, and they must seem to the mother and her son to drag on interminably, is having a significant impact both on the mother and also on the parties' son. Factoring that in as I do, it does seem to me that some further, but limited, delay is inescapable if I am to do justice not merely to the father but, as I have emphasised, also to the parents' son.
I shall accordingly, in terms which I will draft, adjourn this matter so that the relevant ministry can intervene if it wishes to and on the basis that if it does not I will have to decide the issues I have canvassed without that assistance. I will reserve the matter to myself. I will direct that the hearing takes place as soon as it possibly can after the forthcoming short vacation. I would hope that the hearing can take place in front of me in June.
This is about nine years too late for the general principle, and a year late for the LASPO position which left almost all parents in private law cases unrepresented (I suspect that the father's rights movements would also say that as a result of relative incomes, there were a huge number of cases in which fathers had to represent themselves because they had slightly too much money for legal aid representation but not nearly enough to pay privately, and I have some sympathy with that position)
It is welcome anyway, even if it is late.
The President helpfully gives people a valuable little crib-sheet in case they WERE asking the Legal Aid Agency to grant legal aid in the s10 LASPO exceptional circumstances
Putting it in the language of FPR 2010 1.1, the court is required to deal with this matter "justly" and by ensuring "so far as is practicable" that the case is dealt with "fairly" and also "that the parties are on an equal footing." That is the obligation of the court under domestic law. It is also the obligation of the court under Articles 6 and 8 of the European Convention. Despite what Miss Spooner says, I am left with the strong feeling that I cannot deal with the matter today justly and fairly by acceding to her submission.
As I have said, the domestic obligation on the court is to act justly and fairly and, to the extent that it is practicable, ensure that the parties are on an equal footing. In the well-known case of Airey v Ireland (Application no 6289/73) (1979) 2 EHRR 305, the European Court of Human Rights held as long ago as 1979 that there could be circumstances in which, without the assistance of a legally qualified representative, a litigant might be denied her Article 6 right to be able to present her case properly and satisfactorily. In that particular case, the court held that Ireland was in breach of Mrs. Airey's Article 6 rights because it was not realistic in the court's opinion to suppose that, in litigation of the type in which she was involved, she could effectively conduct her own case, despite the assistance which the judge affords to parties acting in person.
Mantovanelli v France (Application no 21497/93) (1997) 24 EHRR 370, a judgment given by the court in March 1997, indicates the significance of the right to an adversarial hearing guaranteed by Article 6 specifically in the context of an expert's report which was "likely to have a preponderant influence on the assessment of the facts by [the] court."
I mention those cases merely as illustrative of the kind of issues which arise in this kind of situation. I emphasise I do so without expressing any view at all as to whether, in the circumstances I am faced with, unless there is some resolution of the present financial impasse, there would be a breach of either Article 6 or Article 8.
You may have noticed that I haven't come on to the facts of the case yet, which is not my usual approach. You may be wondering what the facts of this case are that led to the President being so troubled about the father's human rights (especially given that there was no such intervention on the D v K case where a father was accused of rape by the mother in private law proceedings and not given legal aid, leaving him in the position of facing those very serious allegations without a lawyer and the mother in the position of being cross-examined by the father directly, something which would be illegal if it happened in a criminal trial http://www.bailii.org/ew/cases/EWHC/Fam/2014/700.html So it must be something worse than that?)
Well, this, I'm afraid is one that the Daily Mail would exhaust the entireity of the "Outrage" section of Roget's Thesaurus
The father is a convicted sex offender, having convictions for sexual offences with young male children, the second of which was committed during the currency of these proceedings.
That's right – the man who the President has gone to the wall for, to defend his human rights, to single out and say "This is the case where I must defend the father's rights" is a convicted paedophile seeking to have contact with his seven year old son.
[That, sadly, is the point of human rights, that they are universal and apply to the most deserving and those who the general public might regard as undeserving and beyond the pale. It isn't great PR for those who support human rights – including myself, when it is cases like this that stir our courts into upholding rights. It does seem from time to time that the more unsavoury you appear to be, the more thought the Court give to your rights. I hope it only seems that way.
If you were to hold a national referendum on whether this man, a convicted paedophile, should get to see his seven year old son, I don't imagine that it would be a finely balanced result. I don't think bookmakers would be giving very good odds on "No" ]
Back to the legal debate, the President felt that just because the report was against the father that would not determine the matter
Tempting though it is to think that the father's case is totally lacking in merit, it does seem to me, despite everything Miss Spooner has said, and recognising the constraints which may be imposed on cross-examination by the fact that, in part, challenge on behalf of the father would be to his own expert, I am unpersuaded that there are not matters in these reports which could properly be challenged, probed, by someone representing the father.
For example, a perfectly proper line of cross-examination of JD might be along these lines, "In part at least, your analysis of the risks that the father poses to his son, as opposed to other children, is based upon the account you have had from the mother of what went on in the family home." It would seem, bearing in mind the language of JD's report, that the answer could only be, "Yes." The next question then might be, "Suppose for the sake of argument that the true picture at home was not what the mother says but a very different picture presented by the father. Just suppose that. Would that affect your opinion?" I use that only by way of illustration of a wider point that could be made in relation to these reports. That seems to me to be a proper and appropriate line of cross-examination.
My problem and ultimately Miss Spooner's problem is that it is completely a matter of speculation as to what JD's answer would be to the last question I formulated. The answer might be, "It does not make the slightest difference at all because of X, Y, Z", in which case the father's case might evaporate. It might be, "Well, yes, that might make a difference." The point is we simply do not know
[If you are thinking at this point – well all of that seems like it could apply to ANY witness who was against you, and thus ANY case –mmmmm, yes, I agree. This could be a very critical case for the Government and LASPO. If they don't take it seriously, it could put a serious hole in their policy about legal aid]
What were the Court's possible options to resolve this unthinkable impasse?
Assuming that public funding in the form of legal aid is not going to be available to the father, because his public funding has been withdrawn and an appeal against that withdrawal has been dismissed, and on the footing that, although the father has recently gained employment, his income is not such as to enable him to fund the litigation, there is a pressing need to explore whether there is any other way in which the two problems I have identified can be overcome, the first problem being the funding of the attendance of the experts, the second being the funding of the father's representation
There may be a need in this kind of situation to explore whether there is some other pocket to which the court can have resort to avoid the problem, if it is necessary in the particular case – I emphasise the word "necessary" – in order to ensure a just and fair hearing. In a public law case where the proceedings are brought by a local authority, one can see a possible argument that failing all else the local authority should have to pay. In a case such as the present where one party is publicly funded, because the mother has public funding, but the father does not, it is, I suppose, arguable that, if this is the only way of achieving a just trial, the costs of the proceedings should be thrown on the party which is in receipt of public fundsThere may be a need in this kind of situation to explore whether there is some other pocket to which the court can have resort to avoid the problem, if it is necessary in the particular case – I emphasise the word "necessary" – in order to ensure a just and fair hearing. In a public law case where the proceedings are brought by a local authority, one can see a possible argument that failing all else the local authority should have to pay. In a case such as the present where one party is publicly funded, because the mother has public funding, but the father does not, it is, I suppose, arguable that, if this is the only way of achieving a just trial, the costs of the proceedings should be thrown on the party which is in receipt of public funds.
It is arguable that, failing all else, and bearing in mind that the court is itself a public authority subject to the duty to act in a Convention compliant way, if there is no other way of achieving a just and fair hearing, then the court must itself assume the financial burden, as for example the court does in certain circumstances in funding the cost of interpreters.
May I be very clear? I am merely identifying possible arguments. None of these arguments may in the event withstand scrutiny. Each may dissolve as a mirage. But it seems to me that these are matters which required to be investigated in justice not merely to the father but I emphasise equally importantly to the son, as well as in the wider public interest of other litigants in a similar situation to that of the father here. I emphasise the interests of the son because, under our procedure in private law case like this where the child is not independently represented, fairness to the child can only be achieved if there is fairness to those who are litigating. There is the risk that, if one has a process which is not fair to one of the parents, that unfairness may in the final analysis rebound to the disadvantage of the child
If you have ever watched a submarine movie (and if you haven't, you have wasted your life to date), you will be familiar with the sequence where disaster strikes, water breaches the hull and red lights go on and a siren blasts "Arooogah Aroogah" for the next twenty minutes of the film, where men in crewneck jumpers and/or bellbottoms use wrenches on pipes and doors burst open and water pours in.
That submarine disaster sequence is pretty much what the scene at Her Majesty's Court Service would be like when they read this line from the President
. It is arguable that, failing all else, and bearing in mind that the court is itself a public authority subject to the duty to act in a Convention compliant way, if there is no other way of achieving a just and fair hearing, then the court must itself assume the financial burden, as for example the court does in certain circumstances in funding the cost of interpreters
What the President is saying there is, if a situation arises in which a party's human rights would be breached by having to conduct litigation without a lawyer and the Legal Aid Agency won't pay, it might have to come out of the Court's budget, otherwise the Court would be breaching the party's human rights.
Aroogah! Aroogah!
In private law, if someone is going to have to pay for legal representation to prevent a breach of article 6 and article 8, the options are basically limited to the Legal Aid Agency or the Court (either way, it is coming out of Mr Grayling's budget)
Luckily, we know from Mr Grayling's comments about the completely opaque terrorism trial of AB and CD that "We must trust the Judges" and on that basis, I'm sure that Mr Grayling will stand by that, and not bring a Silk along to talk the President out of it, or appeal any decision that the President might make.
And also note that the President drags the poor old Local Authority into this, despite being a private law case that they aren't involved in.
In a public law case where the proceedings are brought by a local authority, one can see a possible argument that failing all else the local authority should have to pay
It is wrong, and probably a contempt of Court for me to refer to the President of the Family Division as Dude – so let's for a moment imagine that I am talking about someone entirely different (which I am, I am addressing a friend of mine who has just made this very suggestion, in coincidentally the same words that the President used), but
Dude !
Are you saying that if a child has a fractured skull, and the suspects are mother and mother's boyfriend, and mother's boyfriend can't get legal aid, the Local Authority should pay for the boyfriend's lawyers to fight the case against them? That it would be fine for those lawyers to be paid by the applicant in the proceedings, who is running a case directly in opposition to their client?
[I think in the light of Re T, we'd see what the Supreme Court thought about that. The answer it seems to me, is that we need our Courts to unlock s10 LASPO exceptions by saying that these cases would be an article 6 breach in accordance with the spirit of Airey v Ireland, and it would be Wednesbury unreasonable for the Legal Aid Agency to decide otherwise once a judge has ruled that there would be an article 6 breach. IF that is the path that the President goes down, it seems to me to have the potential to punch a big hole in the hull of HMS LASPO – it is lucky that Mr Grayling trusts the Judges]
Posted in case law, costs, private law and tagged airey v ireland, article 6, chris grayling, costs, legal aid, legal aid cases, legal representation, q v q 2014. Bookmark the permalink.


text:
City Car Manufacturer of the Year
City Cars are classified as cars with tailpipe CO₂ emissions of less than 120 g/km.
2019 Winner: Suzuki
Alongside 1.0-litre and 1.2-litre efficient petrol engines, this years' winner also produces a mild-hybrid version of its supermini. Its Smart Hybrid Vehicle system incorporates an Integrated Starter Generator (ISG) which acts as both a generator and starter motor, coupled with a small lithium-ion battery under the passenger seat that stores energy and has an idle stop function.
2018 Winner: Mini
Mini's first plug-in hybrid, the Countryman PHEV, was launched in 2017 and has seen huge demand from fleets. It comes with a 1.5-litre three-cylinder petrol and an electric motor to develop 221bhp overall and provide much improved fuel economy and emissions over the rest of the range. The electric only mode manages 26 miles and allows the Countryman to accelerate to 60mph in under seven seconds. Standard features include a 6.5-inch touchscreen, bluetooth, alloy wheels, air conditioning, multifunction steering wheel, chrome detailing and rear parking sensors.
Now fully owned by Daimler, the Smart brand has offered electric versions of each previous generation of Fortwo, but now offers electric drivetrains across its range. The third-generation has been developed in an industry-standard joint venture with Renault. Branded as Smart EQ, the Fortwo, Fortwo Cabrio and Forfour feature a high-performance on-board charger which allows all three to charge from empty in 3.5 hours for a range of up to 99 miles. A regenerative braking system harnesses kinetic energy to help charge the battery.
Roomier than most city cars, the Celerio provides an extra seatbelt, making it a five-seater in a segment where four is the norm. Powered by Suzuki's K10B 1.0-litre three-cylinder petrol engine (the diesel variant was discontinued in February 2017) it emits 99g/km with a Dualjet version featuring start-stop technology and emitting 84g/km of CO2. Manufactured for Europe at Suzuki Motor Thailand, six airbags and ESP fitted as standard safety equipment for all UK models with Auto Gear Shift now fitted as standard equipment on SZ4 model.
An integral part of the ŠKODA range since 2012, the CITIGO shares components with the Seat Mii and Volkswagen Up. Available in three and five-door versions, a 1.0-litre three cylinder petrol engine emits 96g/km of CO2. For safety as standard, the City Safe Drive brake assist system uses a laser sensor to automatically slow the car if it senses danger of a collision. One step up from the base model, the SE brings upgrades including air-conditioning, 60:40 split-folding rear seats and height-adjustment on the driver's seat. CITIGO is to be joined by a fully electric version, with production to begin in 2019 and offering an increased range over the VW e-Up.
The i10 has been a huge success for Hyundai. Its latest version benefits from technology to make it one of the safest vehicles in its class. It comes with a choice of two petrol engines, 1.0-litre and 1.2-litre, driving the front wheels through five-speed manual as standard or an optional four-speed automatic gearbox. The sleek design results in a drag coefficient of just 0.31, one of the best in its class. All models comply with the latest Euro 6d-TEMP emissions standards with the 1.0 litre variant achieving 50mpg in real-world driving tests. CO2 emissions come in at 117g/km.
Smart has been leading the way since 1998 with its conveniently small models perfect for driving in and around the city. Larger than the two-seat Fortwo, the Forfour Electric Drive is as compact as a Smart despite being a four-seater and offers a range of around 99 miles on a single charge. Zero emissions helps make cities cleaner and the Smart Electric Drive models are also exempt from the London Congestion Charge.
The fifth-generation supermini that is the all-new Nissan Micra was released earlier this year and has three responsive and efficient downsized engines available - two petrol and one diesel - all linked to a five-speed manual gearbox. It has a best-in-class drag coefficient of just 0.29 to maximise fuel efficiency. Perfect for short journeys and city driving, it is among the widest and lowest models in the B-hatchback segment.
The Renault Twingo first appeared in 1992 and the latest version was first open for sales in 2014. It has combined cycle fuel economy of 67.2mpg and CO2 emissions of 95g/km. Another desirable model is the new Zoe, which offers a 250-mile NEDC range on one charge, which equates to around 186 miles in real-world use. With new Z.E. 40 battery, it provides greater range and more flexibility with six variants to choose from.
The Celerio range is perfect for inner-city drivers, featuring three models - the SZ2, SZ3 and the Celerio City. With emissions on Dualjet versions as low as 84g/km, its as clean as city cars get. The Ignis combines funky design and go-anywhere ability, and features a mild hybrid Dualjet SHVS engine on some models for improved economy. The new 2017 Swift also offers hybrid and four-wheel drive options as well as 62.7mpg.
Described as an "innovative, bold and fun-looking urban city car", the new Kia Picanto, released earlier this year, boasts a range of updated technology and a more spacious and practical interior. It also has a fuel consumption of up to 64.2mpg and CO2 emissions of 101g/km with the '1' 1.0 66bhp five-speed manual model. Also new is the supermini-sized Rio, with a more spacious interior and start/stop technology.
Available in three-door and five-door versions, the small three-cylinder 1.0-litre petrol engines in Skoda's Citigo range are flexible and enable nimble driving around town or outside of the city. The more practical five-door is compact, yet roomy with CO2 emissions of 101g/km and a combined mpg of 64.2. The 1.0 60PS GreenTech meanwhile records 96g/km, making it an ideal option in the city car segment.
In spring 2017, MINI presented the first ever production plug-in hybrid model from the British premium brand in the form of the MINI Countryman Plug-in Hybrid. The new MINI Cooper S E Countryman ALL4 achieves CO2 emissions from 49g/km and a combined mpg of up to 134.5. It has impressed customers with its combination of versatility, handling and the option of zero local emissions.
Perhaps the most iconic of city cars, the Fiat 500 has received further tweaks to make it an even more attractive proposition for emissions-conscious fleets. Both versions of the 900cc TwinAir petrol engine are available with start/stop technology, while the 1.3 litre Multijet Diesel variant and a 1.2 litre eco petrol version both provide sub-90g/km emissions for zero road tax and reduce BIK from 17 per cent to 14 per cent. These significant additions to Fiat's range enhanced the marque's position as a city car leader.
Well suited to business drivers, the Mini 3-door Hatch achieves up to 83.1mpg (combined) and features intelligent sensors that take the guesswork out of tricky driving situations. Launched in 2014 and providing further options for the fleet market, the Mini 5-door Hatch, delivers the same distinctive styling with combined fuel economy of 80.7mpg and CO₂ emissions from 92g/km. Auto start/stop, an optional Green Driving Mode and a BIK rate of 18 per cent are also seen as an incentive for fleet drivers.
In 2016 Smart continued to be a highly popular choice. Perfectly suited to city driving, the now iconic design of the fortwo has been an everyday sight since its launch in 1998, decorated by the branding of businesses both large and small across the UK and Europe. The third generation fortwo, developed as a joint venture with Renault, features power steering as standard and a completely new design. The eagerly anticipated Smart electric drive is set for launch in early 2017.
Hyundai's second generation i10 is available in 1.0 and 1.2 litre engines, with modifications to the gearbox which are said to improve fuel consumption by one per cent. The Blue Drive variant features Intelligent Stop & Go, low rolling resistance tyres and an optimum gear change indicator which combine to reduce CO₂ to 98g/km. This helps push the i10 into the zero road tax bracket - an important consideration for fleet buyers.
The Skoda Citigo, available in 3 door and 5 door versions, features the same styling as the Seat Mii and VW Up, but has been brought to market at a much lower cost. The 59bhp and 74bhp engine variants report emissions of 103g/km and 105g/km respectively, with the GreenTech models making the most of eco-enhancements, including low-rolling resistance tyres and stop-start, to push CO₂ down to 95g/km. Attractive pricing and the sub-100g/km option make this a serious fleet player in the city car segment.
In 2015, Citroën re-introduced an electric supermini to its already impressive line-up that now offers a range of 61 cars that are sub- 100grams per kilometer. With an ever-expanding range of efficient three-cyclinder petrol engines helping make the shift away from diesel.