Search in sources :

Example 1 with WalkModException

use of org.walkmod.exceptions.WalkModException in project walkmod-core by walkmod.

the class PrintPluginsCommand method execute.

public void execute() {
    if (help) {
        command.usage("init");
    } else {
        try {
            WalkModFacade facade = new WalkModFacade(OptionsBuilder.options());
            Configuration cfg = facade.getConfiguration();
            Collection<PluginConfig> installedPlugins = null;
            if (cfg != null) {
                installedPlugins = cfg.getPlugins();
            }
            URL searchURL = new URL(MVN_SEARCH_URL);
            InputStream is = null;
            Map<String, Boolean> installedList = new LinkedHashMap<String, Boolean>();
            Map<String, String> pluginsList = new LinkedHashMap<String, String>();
            Map<String, String> pluginsURLs = new LinkedHashMap<String, String>();
            try {
                is = searchURL.openStream();
                String content = readInputStreamAsString(is);
                DefaultJSONParser parser = new DefaultJSONParser(content);
                JSONObject object = parser.parseObject();
                parser.close();
                JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs");
                for (int i = 0; i < artifactList.size(); i++) {
                    JSONObject artifact = artifactList.getJSONObject(i);
                    String artifactId = artifact.getString("a");
                    if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) {
                        String groupId = artifact.getString("g");
                        if (!"org.walkmod.maven.plugins".equals(groupId)) {
                            String latestVersion = artifact.getString("latestVersion");
                            String pom = artifactId + "-" + latestVersion + ".pom";
                            String directory = groupId.replaceAll("\\.", "/");
                            URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/" + latestVersion + "/" + pom);
                            InputStream projectIs = null;
                            try {
                                projectIs = artifactDetailsURL.openStream();
                            } catch (Exception e) {
                            }
                            if (projectIs != null) {
                                try {
                                    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                                    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                                    Document doc = dBuilder.parse(projectIs);
                                    NodeList nList = doc.getElementsByTagName("description");
                                    String description = "unavailable description";
                                    if (nList.getLength() == 1) {
                                        description = nList.item(0).getTextContent();
                                    }
                                    String id = "";
                                    if (!groupId.equals("org.walkmod")) {
                                        id = groupId + ":";
                                    }
                                    id += artifactId.substring("walkmod-".length(), artifactId.length() - "-plugin".length());
                                    if (Character.isLowerCase(description.charAt(0))) {
                                        description = Character.toUpperCase(description.charAt(0)) + description.substring(1, description.length());
                                    }
                                    if (!description.endsWith(".")) {
                                        description = description + ".";
                                    }
                                    pluginsList.put(id, description);
                                    nList = doc.getChildNodes().item(0).getChildNodes();
                                    int max = nList.getLength();
                                    String url = "unavailable url";
                                    for (int j = 0; j < max; j++) {
                                        String name = nList.item(j).getNodeName();
                                        if (name.equals("url")) {
                                            url = nList.item(j).getTextContent();
                                            j = max;
                                        }
                                    }
                                    pluginsURLs.put(id, url);
                                    PluginConfig equivalentPluginCfg = new PluginConfigImpl();
                                    equivalentPluginCfg.setGroupId(groupId);
                                    equivalentPluginCfg.setArtifactId(artifactId);
                                    boolean isInstalled = (installedPlugins != null && installedPlugins.contains(equivalentPluginCfg));
                                    installedList.put(id, isInstalled);
                                } finally {
                                    projectIs.close();
                                }
                            }
                        }
                    }
                }
            } finally {
                is.close();
            }
            Set<String> keys = pluginsList.keySet();
            List<String> sortedKeys = new LinkedList<String>(keys);
            Collections.sort(sortedKeys);
            at = new V2_AsciiTable();
            at.addRule();
            at.addRow("PLUGIN NAME (ID)", "RDY", "DESCRIPTION");
            at.addStrongRule();
            for (String key : sortedKeys) {
                String installed = "";
                if (installedList.get(key)) {
                    installed = "*";
                }
                at.addRow(key, installed, pluginsList.get(key) + "\n\nURL:" + pluginsURLs.get(key));
                at.addRule();
            }
        } catch (Exception e) {
            throw new WalkModException("Invalid plugins URL", e);
        }
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Configuration(org.walkmod.conf.entities.Configuration) Document(org.w3c.dom.Document) PluginConfigImpl(org.walkmod.conf.entities.impl.PluginConfigImpl) URL(java.net.URL) LinkedHashMap(java.util.LinkedHashMap) V2_AsciiTable(de.vandermeer.asciitable.v2.V2_AsciiTable) WalkModException(org.walkmod.exceptions.WalkModException) InputStream(java.io.InputStream) NodeList(org.w3c.dom.NodeList) JSONArray(com.alibaba.fastjson.JSONArray) WalkModException(org.walkmod.exceptions.WalkModException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) PluginConfig(org.walkmod.conf.entities.PluginConfig) JSONObject(com.alibaba.fastjson.JSONObject) DocumentBuilder(javax.xml.parsers.DocumentBuilder) WalkModFacade(org.walkmod.WalkModFacade) DefaultJSONParser(com.alibaba.fastjson.parser.DefaultJSONParser)

Example 2 with WalkModException

use of org.walkmod.exceptions.WalkModException in project walkmod-core by walkmod.

the class ConfigurationImpl method getBean.

@Override
public Object getBean(String name, Map<?, ?> parameters) {
    Object result = null;
    if (name == null || "".equals(name)) {
        return result;
    }
    if (name.equals("script")) {
        name = "walkmod:commons:scripting";
    } else if (name.equals("template")) {
        name = "walkmod:commons:template";
    }
    if (beanFactory != null && beanFactory.containsBean(name)) {
        result = beanFactory.getBean(name);
    }
    if (result == null) {
        String fullName = "org.walkmod:walkmod-" + name + "-plugin:" + name;
        if (!name.contains(":") && beanFactory.containsBean(fullName)) {
            result = beanFactory.getBean(fullName);
        } else {
            String[] parts = name.split(":");
            if (parts.length == 2) {
                String pluginId = parts[0].trim();
                String beanId = parts[1].trim();
                String compositeName = "org.walkmod:walkmod-" + pluginId + "-plugin:" + beanId;
                if (pluginId.length() > 0 && beanId.length() > 0 && beanFactory.containsBean(compositeName)) {
                    result = beanFactory.getBean(compositeName);
                }
            }
        }
    }
    if (result == null) {
        try {
            Class<?> clazz = getClassLoader().loadClass(name);
            result = clazz.newInstance();
        } catch (Exception e) {
            throw new WalkModException("Sorry, it is impossible to load the bean " + name + ". Please, assure that it is a valid class name and the library which contains it is in the classpath", e);
        }
    }
    if (result != null) {
        BeanWrapper bw = new BeanWrapperImpl(result);
        if (this.parameters != null) {
            MutablePropertyValues pvs = new MutablePropertyValues(this.parameters);
            bw.setPropertyValues(pvs, true, true);
        }
        if (parameters != null) {
            MutablePropertyValues pvs = new MutablePropertyValues(parameters);
            bw.setPropertyValues(pvs, true, true);
        }
    }
    return result;
}
Also used : WalkModException(org.walkmod.exceptions.WalkModException) BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) WalkModException(org.walkmod.exceptions.WalkModException)

Example 3 with WalkModException

use of org.walkmod.exceptions.WalkModException in project walkmod-core by walkmod.

the class ConfigurationImpl method executeChain.

public void executeChain(String userDir, Options options, ChainAdapterFactory apf, String name) {
    if (options.getIncludes() != null || options.getExcludes() != null) {
        Collection<ChainConfig> chains = getChainConfigs();
        if (chains != null) {
            for (ChainConfig cc : chains) {
                if (options.getIncludes() != null) {
                    String[] includes = options.getIncludes().toArray(new String[options.getIncludes().size()]);
                    cc.getReaderConfig().setIncludes(includes);
                }
                if (options.getExcludes() != null) {
                    String[] excludes = options.getExcludes().toArray(new String[options.getExcludes().size()]);
                    cc.getReaderConfig().setExcludes(excludes);
                }
            }
        }
    }
    ChainAdapter ap = apf.createChainProxy(this, name);
    if (ap == null) {
        if (options.isVerbose()) {
            log.error("The chain " + name + " is not found");
            System.out.print("----------------------------------------");
            System.out.println("----------------------------------------");
        }
    } else {
        long startTime = System.currentTimeMillis();
        long endTime = startTime;
        DecimalFormat myFormatter = new DecimalFormat("###.###");
        DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", Locale.US);
        if (options.isVerbose()) {
            log.info("** THE TRANSFORMATION CHAIN " + name + " STARTS **");
            System.out.print("----------------------------------------");
            System.out.println("----------------------------------------");
        }
        int num = 0;
        try {
            int size = getChainConfigs().size();
            ap.execute();
            // we check if some other chain config has been added and execute them
            if (getChainConfigs().size() > size) {
                LinkedList<ChainConfig> aux = new LinkedList<ChainConfig>(getChainConfigs());
                Iterator<ChainConfig> it = aux.listIterator(size);
                while (it.hasNext()) {
                    ChainConfig tcfg = it.next();
                    ChainAdapter auxAp = apf.createChainProxy(this, tcfg.getName());
                    auxAp.execute();
                }
            }
            num = ap.getWalkerAdapter().getWalker().getNumModifications();
            if (options.isVerbose()) {
                endTime = System.currentTimeMillis();
                double time = 0;
                if (endTime > startTime) {
                    time = (double) (endTime - startTime) / (double) 1000;
                }
                String timeMsg = myFormatter.format(time);
                if (num != 0) {
                    System.out.print("----------------------------------------");
                    System.out.println("----------------------------------------");
                } else {
                    if (Summary.getInstance().getWrittenFiles().isEmpty()) {
                        log.info("**No sources changed**");
                    }
                }
                System.out.println();
                log.info("TRANSFORMATION CHAIN SUCCESS");
                System.out.print("----------------------------------------");
                System.out.println("----------------------------------------");
                log.info("Total time: " + timeMsg + " seconds");
                log.info("Finished at: " + df.format(new Date()));
                log.info("Final memory: " + (Runtime.getRuntime().freeMemory()) / 1048576 + " M/ " + (Runtime.getRuntime().totalMemory() / 1048576) + " M");
                if (ap.getWalkerAdapter().getWalker().reportChanges()) {
                    log.info("Total modified files: " + num);
                }
                System.out.print("----------------------------------------");
                System.out.println("----------------------------------------");
            }
        } catch (Throwable e) {
            System.setProperty("user.dir", userDir);
            if (options.isVerbose()) {
                endTime = System.currentTimeMillis();
                double time = 0;
                if (endTime > startTime) {
                    time = (double) (endTime - startTime) / (double) 1000;
                }
                String timeMsg = myFormatter.format(time);
                if (num != 0) {
                    System.out.print("----------------------------------------");
                    System.out.println("----------------------------------------");
                }
                log.info("TRANSFORMATION CHAIN FAILS");
                System.out.println();
                System.out.print("----------------------------------------");
                System.out.println("----------------------------------------");
                log.info("Total time: " + timeMsg + " seconds");
                log.info("Finished at: " + df.format(new Date()));
                log.info("Final memory: " + (Runtime.getRuntime().freeMemory()) / 1048576 + " M/ " + (Runtime.getRuntime().totalMemory() / 1048576) + " M");
                System.out.print("----------------------------------------");
                System.out.println("----------------------------------------");
                log.info("Please, see the walkmod log file for details");
                if (options.isPrintErrors()) {
                    log.error("TRANSFORMATION CHAIN (" + name + ") FAILS", e);
                } else {
                    log.error("TRANSFORMATION CHAIN (" + name + ") FAILS. Execute walkmod with -e to see the error details.");
                }
            } else {
                throw new WalkModException(e);
            }
            return;
        }
    }
}
Also used : WalkModException(org.walkmod.exceptions.WalkModException) DecimalFormat(java.text.DecimalFormat) LinkedList(java.util.LinkedList) Date(java.util.Date) ChainConfig(org.walkmod.conf.entities.ChainConfig) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) ChainAdapter(org.walkmod.ChainAdapter) SimpleDateFormat(java.text.SimpleDateFormat)

Example 4 with WalkModException

use of org.walkmod.exceptions.WalkModException in project walkmod-core by walkmod.

the class ScriptProcessor method visit.

public void visit(Object node, VisitorContext ctx) {
    initialize(ctx, node);
    Bindings bindings = engine.createBindings();
    bindings.put("node", node);
    bindings.put("context", ctx);
    bindings.put("query", getQueryEngine());
    if (content != null) {
        try {
            engine.eval(content, bindings);
        } catch (ScriptException e) {
            log.error("The file " + e.getFileName() + " has an error at line: " + e.getLineNumber() + ", column: " + e.getColumnNumber());
            throw new WalkModException(e);
        }
    } else {
        if (location != null) {
            Reader reader = null;
            File file = new File(location).getAbsoluteFile();
            if (file.exists()) {
                try {
                    reader = new FileReader(file);
                } catch (FileNotFoundException e) {
                    throw new WalkModException(e);
                }
            } else {
                URL uri = ctx.getClassLoader().getResource(location);
                if (uri != null) {
                    try {
                        reader = new FileReader(new File(uri.getFile()));
                    } catch (FileNotFoundException e) {
                        throw new WalkModException(e);
                    }
                }
            }
            if (reader != null) {
                try {
                    engine.eval(reader, bindings);
                } catch (ScriptException e) {
                    throw new WalkModException(e);
                }
            }
        }
    }
}
Also used : ScriptException(javax.script.ScriptException) WalkModException(org.walkmod.exceptions.WalkModException) FileNotFoundException(java.io.FileNotFoundException) Reader(java.io.Reader) FileReader(java.io.FileReader) FileReader(java.io.FileReader) Bindings(javax.script.Bindings) File(java.io.File) URL(java.net.URL)

Example 5 with WalkModException

use of org.walkmod.exceptions.WalkModException in project walkmod-core by walkmod.

the class DefaultTemplateVisitor method visit.

public synchronized void visit(Object node, VisitorContext context) throws Exception {
    if (rootLabel == null) {
        setRootLabel("cu");
    }
    if (propertiesFile == null) {
        setProperties("template.properties");
    }
    context.put(getRootLabel(), node);
    if (templateEngine == null) {
        Object bean = context.getBean("org.walkmod.templates.groovy.GroovyTemplateEngine", null);
        if (bean != null && bean instanceof TemplateEngine) {
            templateEngine = (TemplateEngine) bean;
            log.info("Applying [groovy] as a default template engine");
        } else {
            throw new WalkModException("Template engine not found");
        }
    }
    templateEngine.initialize(context, node);
    if (templateFiles != null && templates != null && templateFiles.size() == templates.size()) {
        for (File template : templateFiles) {
            String templateResult = templateEngine.applyTemplate(template, propertiesFile);
            Object producedNode = null;
            currentTemplate = template;
            if (parser != null) {
                try {
                    producedNode = parser.parse(templateResult, true);
                } catch (ParseException e) {
                    log.warn("Error parsing the template " + template.getAbsolutePath() + ". Dumping contents..");
                    doPlainOutput(templateResult, context);
                }
            } else {
                doPlainOutput(templateResult, context);
            }
            if (producedNode != null) {
                log.debug("Template successfuly parsed");
                context.addResultNode(producedNode);
            }
        }
    } else {
        if (!missingTemplates.isEmpty()) {
            for (String missing : missingTemplates) {
                log.error("The template " + missing + " is missing");
            }
        }
        throw new WalkModException("There are missing or unexitent templates.");
    }
}
Also used : GStringTemplateEngine(groovy.text.GStringTemplateEngine) WalkModException(org.walkmod.exceptions.WalkModException) ParseException(org.walkmod.walkers.ParseException) File(java.io.File)

Aggregations

WalkModException (org.walkmod.exceptions.WalkModException)14 LinkedList (java.util.LinkedList)4 File (java.io.File)3 DateFormat (java.text.DateFormat)3 DecimalFormat (java.text.DecimalFormat)3 SimpleDateFormat (java.text.SimpleDateFormat)3 Date (java.util.Date)3 ChainConfig (org.walkmod.conf.entities.ChainConfig)3 Configuration (org.walkmod.conf.entities.Configuration)3 IOException (java.io.IOException)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 ScriptException (javax.script.ScriptException)2 ChainAdapter (org.walkmod.ChainAdapter)2 ChainWalker (org.walkmod.ChainWalker)2 ChainWriter (org.walkmod.ChainWriter)2 ConfigurationProvider (org.walkmod.conf.ConfigurationProvider)2 JSONArray (com.alibaba.fastjson.JSONArray)1 JSONObject (com.alibaba.fastjson.JSONObject)1 DefaultJSONParser (com.alibaba.fastjson.parser.DefaultJSONParser)1