Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright 1&1 Internet AG, https://github.com/1and1/ 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 net.oneandone.jasmin.model;
 
 
 import java.net.URL;
 import java.util.List;
 import java.util.Map;

A list of modules. Plus load functionality (including linking and reload file handling)
 
 public class Repository {
    
simplified load method for testing
 
     public static Repository load(Resolver resolverthrows IOException {
         Repository repository;
 
         repository = new Repository();
         repository.loadClasspath(resolver);
         repository.link();
         return repository;
     }
 
     // where in the classes of a module or an application ...
     public static final String PROJECT_PROPERTIES = "META-INF/pominfo.properties";
     public static final String MODULE_DESCRIPTOR = "META-INF/jasmin.xml";
     public static final String APPLICATION_DESCRIPTOR = "WEB-INF/jasmin.xml";
 
     //--
 
    
For webservices; may be null
 
     private final Attributes attributes;
 
     private final List<Modulemodules;

    
using during loading, until() link is called
 
     private Map<ModuleList<String>> notLinked;
    
using during loading, until() link is called
 
     private List<NodereloadFiles;
 
     public Repository() {
         this(new Attributes() {
             @Override
             public Object get(String name) {
                 throw new IllegalArgumentException("no such attribute: " + name);
             }
         });
     }
 
     public Repository(Attributes attributes) {
         if (attributes == null) {
             throw new IllegalArgumentException();
         }
         this. = attributes;
         this. = new ArrayList<>();
         this. = new HashMap<>();
         this. = new ArrayList<>();
     }
 
     public List<Modulemodules() {
         return ;
     }
 
     public Module lookup(String name) {
         for (Module module : ) {
             if (name.equals(module.getName())) {
                 return module;
            }
        }
        return null;
    }

    

Returns:
never null
    public Module get(String name) {
        Module module;
        module = lookup(name);
        if (module == null) {
            throw new IllegalArgumentException("no such module: " + name);
        }
        return module;
    }
    public void add(Module module) {
        String name;
        name = module.getName();
        if (lookup(name) != null) {
            throw new IllegalArgumentException("duplicate module: " + name);
        }
        .add(module);
    }
    //--
    public List<Stringsequence(String... namesthrows CyclicDependency {
        List<ModulemoduleList;
        List<Stringresult;
        moduleList = new ArrayList<Module>();
        for (String name : names) {
            moduleList.add(get(name));
        }
        result = new ArrayList<String>();
        for (Module module : sequence(moduleList)) {
            result.add(module.getName());
        }
        return result;
    }
    // topological sort
    public List<Modulesequence(List<ModulemoduleListthrows CyclicDependency {
        List<Modulework;
        Graph<Modulegraph;
        Module left;
        Module right;
        graph = new Graph<Module>();
        for (int i = 0; i < moduleList.size(); i++) {
            right = moduleList.get(i);
            graph.addNode(right);
            if (i > 0) { // inject dependency to previous modules
                left = moduleList.get(i - 1);
                graph.addEdge(leftright);
            }
        }
        work = new ArrayList<Module>();
        work.addAll(moduleList);
        for (int i = 0; i < work.size(); i++) { // list grows!
            right = work.get(i);
            for (Module l : right.dependencies()) {
                graph.addEdge(lright);
                if (!work.contains(l)) {
                    work.add(l);
                }
            }
        }
        return graph.sort();
    }
    //--
    public References resolve(Request requestthrows IOExceptionCyclicDependency {
        List<Moduleincludes;
        List<Moduleexcludes;
        References references;
        List<ModulemoduleList;
        Node resolved;
        boolean minimize;
        boolean declarationOnly;
        includes = new ArrayList<>();
        excludes = new ArrayList<>();
        for (String name : ..split(request.modules)) {
            if (name.length() == 0) {
                throw new IllegalStateException();
            }
            if (name.charAt(0) == .) {
                excludes.add(get(name.substring(1)));
            } else {
                includes.add(get(name));
            }
        }
        moduleList = sequence(includes);
        excludes = sequence(excludes);
        references = new References(request.typerequest.minimize);
        for (Module module : moduleList) {
            if (excludes.contains(module)) {
                if (request.type == .) {
                    continue;
                }
                declarationOnly = true;
            } else {
                declarationOnly = false;
            }
            for (File file : module.resolve(request)) {
                resolved = file.get(request.minimize);
                minimize = request.minimize && file.getMinimized() == null;
                references.add(minimizedeclarationOnlyresolved);
            }
        }
        return references;
    }
    public List<StringgetVariants() {
        List<Stringresults;
        String variant;
        results = new ArrayList<>();
        for (Module module : ) {
            for (File file : module.files()) {
                variant = file.getVariant();
                if (variant != null && !results.contains(variant)) {
                    results.add(variant);
                }
            }
        }
        return results;
    }
    //--

    
Loads modules from classpath
    public void loadClasspath(Resolver resolverthrows IOException {
        Enumeration<URLe;
        while (e.hasMoreElements()) {
            loadModule(resolvere.nextElement());
        }
    }
    private void loadModule(Resolver resolverURL urlthrows IOException {
        FileNode classpathItem;
        Node descriptor;
        Node properties;
        Node base;
        classpathItem = resolver.getWorld().locateClasspathItem(url"/" + );
        base = classpathItem.isFile() ? classpathItem.openZip() : classpathItem;
        descriptor = resolver.resolve(base);
        properties = resolver.resolve(base);
        loadLibrary(resolverbasedescriptorproperties);
    }

    
An application is not a classpath item because jasmin.xml is from WEB-INF, it's not a resource. I don't want to make it a resource (by moving WEB-INF/jasmin.xml to META-INF/jasmin.xml) because all other config files reside in WEB-INF. Some webapps have no META-INF directory at all.
    public void loadApplication(Resolver resolverNode docrootNode descriptorthrows IOException {
        Node properties;
        // pws removes WEB-INF classes and uses target/classes instead ...
        properties = docroot.getParent().join("classes");
        if (!properties.isFile()) {
            properties = docroot.join("WEB-INF/classes");
        }
        loadLibrary(resolverdocrootdescriptorproperties);
    }

    
Core method for loading. A library is a module or an application

Parameters:
base jar file for module, docroot for application
    public void loadLibrary(Resolver resolverNode baseNode descriptorNode propertiesthrows IOException {
        Source source;
        Module module;
        Library library;
        File file;
        addReload(descriptor);
        source = Source.load(propertiesbase);
        library = (Library..loadXml(descriptor).get();
        autoFiles(resolverlibrarysource);
        for (net.oneandone.jasmin.descriptor.Module descriptorModule : library.modules()) {
            module = new Module(descriptorModule.getName(), source);
            .put(moduledescriptorModule.dependencies());
            for (Resource resource : descriptorModule.resources()) {
                file = resolver.resolve(source.classpathBaseresource);
                addReload(file);
                resolver.resolve(source.classpathBaseresource);
                module.files().add(file);
            }
            add(module);
        }
    }
    private void addReload(File file) {
        addReload(file.getNormal());
        addReload(file.get(true));
    }
    private void addReload(Node node) {
        if (node instanceof WebdavNode) {
            return;
        }
        if (node instanceof FileNode) {
            // done
        } else if (node instanceof ZipNode) {
            node = node.getWorld().file(((ZipNodenode).getRoot().getZip().getName());
        } else if (node instanceof MemoryNode) {
            // for tests
        } else {
            throw new IllegalStateException("unexpected node: " + node);
        }
        if (!.contains(node)) {
            .add(node);
        }
    }
    private void autoFiles(Resolver lifeLibrary librarySource sourcethrows IOException {
        autoFiles(lifesource.library.jss());
        autoFiles(lifesource.library.csss());
    }
    private void autoFiles(Resolver resolverSource sourceMimeType typeList<Stringincludesthrows IOException {
        Filter filter;
        Module module;
        Ref ref;
        File file;
        List<Stringdepends;
        List<Stringcalls;
        List<Refrefs;
        Map<StringList<Ref>> map;
        Ref normal;
        Ref companion;
        Ref minimized;
        filter =  new Filter();
        filter.include(includes);
        map = new HashMap<StringList<Ref>>();
        for (Node node : source.classpathBase.find(filter)) {
            ref = Ref.create(nodesource);
            refs = map.get(ref.module);
            if (refs == null) {
                refs = new ArrayList<Ref>();
                map.put(ref.modulerefs);
            }
            refs.add(ref);
        }
        for (Map.Entry<StringList<Ref>> entry : map.entrySet()) {
            module = lookup(entry.getKey());
            if (module == null) {
                module = new Module(entry.getKey(), source);
                .add(module);
            } else {
                if (module.getSource() != source) {
                    throw new IllegalStateException();
                }
            }
            refs = entry.getValue();
            while (!refs.isEmpty()) {
                normal = refs.remove(0);
                companion = removeCompanionOpt(refsnormal);
                if (companion == null) {
                    if (normal.minimized) {
                        minimized = normal;
                    } else {
                        minimized = null;
                    }
                } else {
                    if (normal.minimized) {
                        minimized = normal;
                        normal = companion;
                    } else {
                        minimized = companion;
                    }
                }
                file = resolver.resolve(source.classpathBasenew Resource(type.normal.path,
                        minimized != null ? minimized.path : nullnormal.variant));
                try {
                    depends = .get(module);
                    if (depends == null) {
                        depends = new ArrayList<>();
                        .put(moduledepends);
                    }
                    calls = new ArrayList<>();
                    Parser.parseComment(stripBom(file.getNormal().readString()), dependscalls);
                } catch (IOException e) {
                    throw new IOException(normal.node.getURI() + ": " + e.getMessage(), e);
                }
                if (calls.size() > 0) {
                    if (file.getMinimized() != null) {
                        throw new UnsupportedOperationException(file.getNormal().getURI().toString());
                    }
                    Node tmp = resolver.getWorld().memoryNode();
                    try (OutputStream dest = tmp.createOutputStream()) {
                        for (String webservice : calls) {
                            Call.call(webservicedest);
                            dest.write('\n');
                        }
                        try (InputStream orig = file.getNormal().createInputStream()) {
                            resolver.getWorld().getBuffer().copy(origdest);
                        }
                    }
                    file = new File(tmpnullfile.getType(), file.getVariant());
                }
                module.files().add(file);
                addReload(file);
            }
        }
    }
    // http://en.wikipedia.org/wiki/Byte_Order_Mark
    private static String stripBom(String str) {
        if (!str.isEmpty() && str.charAt(0) == 65279) {
            return str.substring(1);
        } else {
            return str;
        }
    }
    //--
    // companion: Ref with same module and variant, but different minimization
    private static Ref removeCompanionOpt(List<RefrefsRef cmp) {
        Iterator<Refiter;
        Ref ref;
        iter = refs.iterator();
        while (iter.hasNext()) {
            ref = iter.next();
            if (ref.module.equals(cmp.module) && Util.eq(ref.variantcmp.variant)) {
                iter.remove();
                return ref;
            }
        }
        return null;
    }
    private static class Ref {
        private static final String MIN = "-min";
        public static Ref create(Node nodeSource source) {
            String path;
            String module;
            int idx;
            boolean minimized;
            String variant;
            path = node.getRelative(source.classpathBase);
            module = path;
            module = Strings.removeLeftOpt(module"PUSTEFIX-INF/");
            module = Strings.removeLeftOpt(module"pustefix/");
            module = Strings.removeLeftOpt(module"htdocs/");
            module = Strings.removeLeftOpt(module"script/");
            module = Strings.removeLeftOpt(module"style/");
            idx = module.lastIndexOf('.');
            if (idx != -1) {
                module = module.substring(0, idx);
            }
            minimized = module.endsWith();
            if (minimized) {
                module = module.substring(0, module.length() - .length());
            }
            idx = module.indexOf(':');
            if (idx != -1) {
                variant = module.substring(idx + 1);
                module = module.substring(0, idx);
            } else {
                variant = null;
            }
            module = source.artifactId + "-" + module.replace('/''-');
            return new Ref(nodepathmodulevariantminimized);
        }
        public final Node node;
        public final String path;
        public final String module;
        public final String variant;
        public final boolean minimized;
        public Ref(Node nodeString pathString moduleString variantboolean minimized) {
            this. = node;
            this. = path;
            this. = module;
            this. = variant;
            this. = minimized;
        }
    }
    //--

    
Call this after you've loaded all libraries

Returns:
reload files
    public List<Nodelink() {
        List<Moduledependencies;
        Module module;
        Module resolved;
        StringBuilder problems;
        List<Noderesult;
        problems = new StringBuilder();
        for (Map.Entry<ModuleList<String>> entry : .entrySet()) {
            module = entry.getKey();
            dependencies = module.dependencies();
            for (String name : entry.getValue()) {
                resolved = lookup(name);
                if (resolved == null) {
                    problems.append("module '" + module.getName() + "': cannot resolve dependency '" + name + "'\n");
                } else {
                    dependencies.add(resolved);
                }
            }
        }
        if (problems.length() > 0) {
            throw new IllegalArgumentException(problems.toString());
        }
        result = ;
         = null;
         = null;
        return result;
    }
New to GrepCode? Check out our FAQ X