You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by cz...@apache.org on 2017/08/16 08:37:33 UTC

svn commit: r1805151 - /sling/whiteboard/cziegeler/feature-modelconverter/src/main/java/org/apache/sling/feature/modelconverter/impl/Main.java

Author: cziegeler
Date: Wed Aug 16 08:37:33 2017
New Revision: 1805151

URL: http://svn.apache.org/viewvc?rev=1805151&view=rev
Log:
Remove repoinit workaround, add back conversion

Modified:
    sling/whiteboard/cziegeler/feature-modelconverter/src/main/java/org/apache/sling/feature/modelconverter/impl/Main.java

Modified: sling/whiteboard/cziegeler/feature-modelconverter/src/main/java/org/apache/sling/feature/modelconverter/impl/Main.java
URL: http://svn.apache.org/viewvc/sling/whiteboard/cziegeler/feature-modelconverter/src/main/java/org/apache/sling/feature/modelconverter/impl/Main.java?rev=1805151&r1=1805150&r2=1805151&view=diff
==============================================================================
--- sling/whiteboard/cziegeler/feature-modelconverter/src/main/java/org/apache/sling/feature/modelconverter/impl/Main.java (original)
+++ sling/whiteboard/cziegeler/feature-modelconverter/src/main/java/org/apache/sling/feature/modelconverter/impl/Main.java Wed Aug 16 08:37:33 2017
@@ -20,8 +20,6 @@ import java.io.File;
 import java.io.FileReader;
 import java.io.FileWriter;
 import java.io.IOException;
-import java.io.LineNumberReader;
-import java.io.StringReader;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Enumeration;
@@ -30,10 +28,11 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.stream.Collectors;
 
-import org.apache.commons.cli.BasicParser;
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.DefaultParser;
 import org.apache.commons.cli.Option;
 import org.apache.commons.cli.Options;
 import org.apache.commons.cli.ParseException;
@@ -49,6 +48,7 @@ import org.apache.sling.feature.support.
 import org.apache.sling.feature.support.ArtifactManager;
 import org.apache.sling.feature.support.ArtifactManagerConfig;
 import org.apache.sling.feature.support.FeatureUtil;
+import org.apache.sling.feature.support.json.ApplicationJSONReader;
 import org.apache.sling.feature.support.json.ApplicationJSONWriter;
 import org.apache.sling.feature.support.json.FeatureJSONWriter;
 import org.apache.sling.provisioning.model.Artifact;
@@ -65,6 +65,7 @@ import org.apache.sling.provisioning.mod
 import org.apache.sling.provisioning.model.Section;
 import org.apache.sling.provisioning.model.Traceable;
 import org.apache.sling.provisioning.model.io.ModelReader;
+import org.apache.sling.provisioning.model.io.ModelWriter;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -92,9 +93,9 @@ public class Main {
      * @return Configuration object.
      */
     private static void parseArgs(final String[] args) {
-        final Options options = new Options();
+        final Option repoOption =  Option.builder("u").hasArg().argName("Set repository url")
+                .desc("repository url").required().build();
 
-        final Option repoOption =  new Option("u", true, "Set repository url");
         final Option modelOption =  new Option("f", true, "Set feature files/directories");
         final Option propsOption =  new Option("p", true, "sling.properties file");
         final Option runModeOption =  new Option("r", true, "Set run modes (comma separated)");
@@ -102,7 +103,11 @@ public class Main {
         createAppOption.setArgs(0);
         final Option includeModelOption = new Option("i", false, "Include model filename as metadata for artifacts");
         includeModelOption.setArgs(0);
-        final Option outputOption = new Option("o", true, "Set output file");
+
+        final Option outputOption = Option.builder("o").hasArg().argName("Set output file")
+                .desc("output file").build();
+
+        final Options options = new Options();
         options.addOption(repoOption);
         options.addOption(modelOption);
         options.addOption(createAppOption);
@@ -110,9 +115,9 @@ public class Main {
         options.addOption(includeModelOption);
         options.addOption(propsOption);
 
-        final CommandLineParser clp = new BasicParser();
+        final CommandLineParser parser = new DefaultParser();
         try {
-            final CommandLine cl = clp.parse(options, args);
+            final CommandLine cl = parser.parse(options, args);
 
             if ( cl.hasOption(repoOption.getOpt()) ) {
                 repoUrls = cl.getOptionValue(repoOption.getOpt());
@@ -139,15 +144,27 @@ public class Main {
             LOGGER.error("Unable to parse command line: {}", pe.getMessage(), pe);
             System.exit(1);
         }
-        if ( output == null ) {
-            output = createApp ? "application.json" : "feature.json";
-        }
         if ( input == null ) {
             LOGGER.error("Required argument missing: model file or directory");
             System.exit(1);
         }
     }
 
+    private static ArtifactManager getArtifactManager() {
+        final ArtifactManagerConfig amConfig = new ArtifactManagerConfig();
+        if ( repoUrls != null ) {
+            amConfig.setRepositoryUrls(repoUrls.split(","));
+        }
+        try {
+            return ArtifactManager.getArtifactManager(amConfig);
+        } catch ( IOException ioe) {
+            LOGGER.error("Unable to create artifact manager " + ioe.getMessage(), ioe);
+            System.exit(1);
+        }
+        // we never reach this, but have to keep the compiler happy
+        return null;
+    }
+
     public static void main(final String[] args) {
         // setup logging
         System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");
@@ -162,36 +179,88 @@ public class Main {
 
         parseArgs(args);
 
+        final ArtifactManagerConfig amConfig = new ArtifactManagerConfig();
+        if ( repoUrls != null ) {
+            amConfig.setRepositoryUrls(repoUrls.split(","));
+        }
+        final ArtifactManager am = getArtifactManager();
+
         final File f = new File(input);
-        final File[] files;
+        final List<File> files = new ArrayList<>();
         if ( f.isDirectory() ) {
-            final List<File> list = new ArrayList<>();
             for(final File file : f.listFiles()) {
                 if ( file.isFile() && !file.getName().startsWith(".") ) {
-                    list.add(file);
+                    files.add(file);
                 }
             }
-            if ( list.isEmpty() ) {
+            if ( files.isEmpty() ) {
                 LOGGER.error("No files found in {}", f);
                 System.exit(1);
             }
-            Collections.sort(list);
-            files = list.toArray(new File[list.size()]);
+            Collections.sort(files);
         } else {
-            files = new File[] {f};
+            files.add(f);
+        }
+        boolean isJson = false;
+        boolean isTxt = false;
+        for(final File t : files) {
+            if ( t.getName().endsWith(".json") ) {
+                if ( isTxt ) {
+                    LOGGER.error("Input files are a mixture of JSON and txt");
+                    System.exit(1);
+                }
+                isJson = true;
+            } else {
+                if ( isJson ) {
+                    LOGGER.error("Input files are a mixture of JSON and txt");
+                    System.exit(1);
+                }
+                isTxt = true;
+            }
         }
-        final Model model = createModel(files, runModes);
 
-        if ( createApp ) {
-            final Application app = buildApplication(model);
+        if ( isTxt ) {
+            if ( output == null ) {
+                output = createApp ? "application.json" : "feature.json";
+            }
+            final Model model = createModel(files, runModes);
+
+            if ( createApp ) {
+                final Application app = buildApplication(model);
 
-            writeApplication(app, output);
+                writeApplication(app, output);
+            } else {
+                final List<org.apache.sling.feature.Feature> features = buildFeatures(model);
+                int index = 1;
+                for(final org.apache.sling.feature.Feature feature : features) {
+                    writeFeature(feature, output, features.size() > 1 ? index : 0);
+                    index++;
+                }
+            }
         } else {
-            final List<org.apache.sling.feature.Feature> features = buildFeatures(model);
-            int index = 1;
-            for(final org.apache.sling.feature.Feature feature : features) {
-                writeFeature(feature, output, index);
-                index++;
+            if ( output == null ) {
+                output = createApp ? "application.txt" : "feature.txt";
+            }
+            try {
+                if ( createApp ) {
+                    // each file is an application
+                    int index = 1;
+                    for(final File appFile : files ) {
+                        try ( final FileReader r = new FileReader(appFile) ) {
+                            final Application app = ApplicationJSONReader.read(r);
+                            convert(app, files.size() > 1 ? index : 0);
+                        }
+                        index++;
+                    }
+                } else {
+                    final Application app = FeatureUtil.assembleApplication(null, files.stream()
+                            .map(File::getAbsolutePath)
+                            .collect(Collectors.toList()), am);
+                    convert(app, 0);
+                }
+            } catch ( final IOException ioe) {
+                LOGGER.error("Unable to read feature/application files " + ioe.getMessage(), ioe);
+                System.exit(1);
             }
         }
     }
@@ -305,30 +374,6 @@ public class Main {
                 repoExtension.setText(repoExtension.getText() + "\n\n" + text);
             }
         }
-        if ( repoExtension != null ) {
-            // remove trailing comments and empty lines
-            final List<String> lines = new ArrayList<>();
-            try ( final LineNumberReader lnr = new LineNumberReader(new StringReader(repoExtension.getText()))) {
-                String line = null;
-                while ( (line = lnr.readLine()) != null ) {
-                    lines.add(line);
-                }
-            } catch ( final IOException ioe ) {
-                LOGGER.error("Unable to read repoinit", ioe);
-                System.exit(1);
-            }
-            int index = lines.size() - 1;
-            while ( index >= 0 ) {
-                final String line = lines.get(index).trim();
-                if ( line.isEmpty() || line.startsWith("#") ) {
-                    lines.remove(index);
-                    index--;
-                } else {
-                    index = -1;
-                }
-            }
-            repoExtension.setText(String.join("\n", lines));
-        }
     }
 
     private static void writeApplication(final Application app, final String out) {
@@ -344,7 +389,7 @@ public class Main {
 
     private static void writeFeature(final org.apache.sling.feature.Feature f, String out, final int index) {
         LOGGER.info("Writing feature...");
-        if ( index > 1 ) {
+        if ( index > 0 ) {
             final int lastDot = out.lastIndexOf('.');
             if ( lastDot == -1 ) {
                 out = out + "_" + String.valueOf(index);
@@ -365,7 +410,7 @@ public class Main {
      * Read the models and prepare the model
      * @param files The model files
      */
-    private static Model createModel(final File[] files,
+    private static Model createModel(final List<File> files,
             final String runModes) {
         LOGGER.info("Assembling model...");
         Model model = null;
@@ -603,4 +648,81 @@ public class Main {
             }
         }
     }
+
+    private static void convert(final Application app, final int index) {
+        final Feature f = new Feature("application");
+
+        // bundles
+        for(final Map.Entry<Integer, org.apache.sling.feature.Artifact> bundle : app.getBundles()) {
+            final ArtifactId id = bundle.getValue().getId();
+            final Artifact newBundle = new Artifact(id.getGroupId(), id.getArtifactId(), id.getVersion(), id.getClassifier(), id.getType());
+            for(final Map.Entry<String, String> prop : bundle.getValue().getMetadata()) {
+                newBundle.getMetadata().put(prop.getKey(), prop.getValue());
+            }
+            f.getOrCreateRunMode(null).getOrCreateArtifactGroup(bundle.getKey()).add(newBundle);
+        }
+
+        // configurations
+        for(final org.apache.sling.feature.Configuration cfg : app.getConfigurations()) {
+            final Configuration c;
+            if ( cfg.isFactoryConfiguration() ) {
+                c = new Configuration(cfg.getName(), cfg.getFactoryPid());
+            } else {
+                c = new Configuration(cfg.getPid(), null);
+            }
+            final Enumeration<String> keys = cfg.getProperties().keys();
+            while ( keys.hasMoreElements() ) {
+                final String key = keys.nextElement();
+                c.getProperties().put(key, cfg.getProperties().get(key));
+            }
+            f.getOrCreateRunMode(null).getConfigurations().add(c);
+        }
+
+        // framework properties
+        for(final Map.Entry<String, String> prop : app.getFrameworkProperties()) {
+            f.getOrCreateRunMode(null).getSettings().put(prop.getKey(), prop.getValue());
+        }
+
+        // extensions: content packages and repoinit
+        for(final Extension ext : app.getExtensions()) {
+            if ( Extension.NAME_CONTENT_PACKAGES.equals(ext.getName()) ) {
+                for(final org.apache.sling.feature.Artifact cp : ext.getArtifacts() ) {
+                    final ArtifactId id = cp.getId();
+                    final Artifact newCP = new Artifact(id.getGroupId(), id.getArtifactId(), id.getVersion(), id.getClassifier(), id.getType());
+                    for(final Map.Entry<String, String> prop : cp.getMetadata()) {
+                        newCP.getMetadata().put(prop.getKey(), prop.getValue());
+                    }
+                    f.getOrCreateRunMode(null).getOrCreateArtifactGroup(0).add(newCP);
+                }
+
+            } else if ( Extension.NAME_REPOINIT.equals(ext.getName()) ) {
+                final Section section = new Section("repoinit");
+                section.setContents(ext.getText());
+                f.getAdditionalSections().add(section);
+            } else if ( ext.isRequired() ) {
+                LOGGER.error("Unable to convert required extension {}", ext.getName());
+                System.exit(1);
+            }
+        }
+
+        LOGGER.info("Writing feature...");
+        String out = output;
+        if ( index > 0 ) {
+            final int lastDot = out.lastIndexOf('.');
+            if ( lastDot == -1 ) {
+                out = out + "_" + String.valueOf(index);
+            } else {
+                out = out.substring(0, lastDot) + "_" + String.valueOf(index) + out.substring(lastDot);
+            }
+        }
+        final File file = new File(out);
+        final Model m = new Model();
+        m.getFeatures().add(f);
+        try ( final FileWriter writer = new FileWriter(file)) {
+            ModelWriter.write(writer, m);
+        } catch ( final IOException ioe) {
+            LOGGER.error("Unable to write feature to {} : {}", out, ioe.getMessage(), ioe);
+            System.exit(1);
+        }
+    }
 }