Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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 org.apache.felix.karaf.deployer.spring;
 
 import java.net.URL;
 import java.util.Set;
 
 
 
 
 public class SpringTransformer {
 
     static Transformer transformer;
     static DocumentBuilderFactory dbf;
     static TransformerFactory tf;
 
 
     public static void transform(URL urlOutputStream osthrows Exception {
         // Build dom document
         Document doc = parse(url);
         // Heuristicly retrieve name and version
         String name = url.getPath();
         int idx = name.lastIndexOf('/');
         if (idx >= 0) {
             name = name.substring(idx + 1);
         }
         String[] str = extractNameVersionType(name);
         // Create manifest
         Manifest m = new Manifest();
         m.getMainAttributes().putValue("Manifest-Version""2");
         m.getMainAttributes().putValue(.str[1]);
         m.getMainAttributes().putValue("Spring-Context""*;publish-context:=false;create-asynchronously:=true");
         String importPkgs = getImportPackages(analyze(new DOMSource(doc)));
         if (importPkgs != null && importPkgs.length() > 0) {
             m.getMainAttributes().putValue(.importPkgs);
         }
         // Extract manifest entries from the DOM
         NodeList l = doc.getElementsByTagName("manifest");
         if (l != null) {
             for (int i = 0; i < l.getLength(); i++) {
                 Element e = (Elementl.item(i);
                 String text = e.getTextContent();
                 Properties props = new Properties();
                 props.load(new ByteArrayInputStream(text.trim().getBytes()));
                 Enumeration en = props.propertyNames();
                 while (en.hasMoreElements()) {
                     String k = (Stringen.nextElement();
                     String v = props.getProperty(k);
                     m.getMainAttributes().putValue(kv);
                 }
                 e.getParentNode().removeChild(e);
             }
         }
        JarOutputStream out = new JarOutputStream(os);
        ZipEntry e = new ZipEntry(.);
        out.putNextEntry(e);
        m.write(out);
        out.closeEntry();
        e = new ZipEntry("META-INF/");
        out.putNextEntry(e);
        e = new ZipEntry("META-INF/spring/");
        out.putNextEntry(e);
        out.closeEntry();
        e = new ZipEntry("META-INF/spring/" + name);
        out.putNextEntry(e);
        // Copy the new DOM
        if ( == null) {
             = TransformerFactory.newInstance();
        }
        .newTransformer().transform(new DOMSource(doc), new StreamResult(out));
        out.closeEntry();
        out.close();
    }
    private static final String DEFAULT_VERSION = "0.0.0";
    private static final Pattern ARTIFACT_MATCHER = Pattern.compile("(.+)(?:-(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?(?:[^a-zA-Z0-9](.*))?)(?:\\.([^\\.]+))".);
    private static final Pattern FUZZY_MODIFIDER = Pattern.compile("(?:\\d+[.-])*(.*)".);
    public static String[] extractNameVersionType(String url) {
        Matcher m = .matcher(url);
        if (!m.matches()) {
            return new String[] { url };
        }
        else {
            //System.err.println(m.groupCount());
            //for (int i = 1; i <= m.groupCount(); i++) {
            //    System.err.println("Group " + i + ": " + m.group(i));
            //}
            StringBuffer v = new StringBuffer();
            String d1 = m.group(1);
            String d2 = m.group(2);
            String d3 = m.group(3);
            String d4 = m.group(4);
            String d5 = m.group(5);
            String d6 = m.group(6);
            if (d2 != null) {
                v.append(d2);
                if (d3 != null) {
                    v.append('.');
                    v.append(d3);
                    if (d4 != null) {
                        v.append('.');
                        v.append(d4);
                        if (d5 != null) {
                            v.append(".");
                            cleanupModifier(vd5);
                        }
                    } else if (d5 != null) {
                        v.append(".0.");
                        cleanupModifier(vd5);
                    }
                } else if (d5 != null) {
                    v.append(".0.0.");
                    cleanupModifier(vd5);
                }
            }
            return new String[] { d1v.toString(), d6 };
        }
    }
    private static void cleanupModifier(StringBuffer resultString modifier) {
        Matcher m = .matcher(modifier);
        if (m.matches()) {
            modifier = m.group(1);
        }
        for (int i = 0; i < modifier.length(); i++) {
            char c = modifier.charAt(i);
            if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-') {
                result.append(c);
            }
        }
    }
    public static Set<Stringanalyze(Source sourcethrows Exception {
        if ( == null) {
            if ( == null) {
                 = TransformerFactory.newInstance();
            }
            Source s = new StreamSource(SpringTransformer.class.getResourceAsStream("extract.xsl"));
             = .newTransformer(s);
        }
        Set<Stringrefers = new TreeSet<String>();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        Result r = new StreamResult(bout);
        .transform(sourcer);
        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        bout.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(bin));
        String line = br.readLine();
        while (line != null) {
            line = line.trim();
            if (line.length() > 0) {
                String parts[] = line.split("\\s*,\\s*");
                for (int i = 0; i < parts.lengthi++) {
                    int n = parts[i].lastIndexOf('.');
                    if (n > 0) {
                        String pkg = parts[i].substring(0, n);
                        if (!pkg.startsWith("java.")) {
                            refers.add(parts[i].substring(0, n));
                        }
                    }
                }
            }
            line = br.readLine();
        }
        br.close();
        return refers;
    }
    protected static String getImportPackages(Set<Stringpackages) {
        StringBuilder sb = new StringBuilder();
        for (String pkg : packages) {
            if (sb.length() > 0) {
                sb.append(",");
            }
            sb.append(pkg);
        }
        return sb.toString();
    }
    protected static Document parse(URL urlthrows Exception {
        if ( == null) {
             = DocumentBuilderFactory.newInstance();
            .setNamespaceAware(true);
        }
        DocumentBuilder db = .newDocumentBuilder();
        return db.parse(url.toString());
    }
    protected static void copyInputStream(InputStream inOutputStream outthrows Exception {
        byte[] buffer = new byte[4096];
        int len = in.read(buffer);
        while (len >= 0) {
            out.write(buffer, 0, len);
            len = in.read(buffer);
        }
    }
New to GrepCode? Check out our FAQ X