📄 bobberarchetype.java
字号:
catch (IOException ioe) { throw new ArchetypeTemplateProcessingException("Error extracting archetype", ioe); } // ---------------------------------------------------------------------- // Process the templates // ---------------------------------------------------------------------- // use the out of the box codehaus velocity component that loads templates //from the class path ClassLoader old = Thread.currentThread().getContextClassLoader(); try { URL[] urls = new URL[1]; urls[0] = archetypeArtifact.getFile().toURI().toURL(); URLClassLoader archetypeJarLoader = new URLClassLoader(urls); Thread.currentThread().setContextClassLoader(archetypeJarLoader); for (Iterator i = archetype.getTemplates().iterator(); i.hasNext();) { final Template template = (Template) i.next(); // Check the optional 'condition' property on the template. // If present and the variable it points to is 'true', then // continue processing. If it's false, then skip. // If condition is not specified, assume the template should // be processed. boolean shouldProcess = true; String condition = template.getDependsOnVar(); String requiredValue = null; List options = new ArrayList(); if (StringUtils.isNotEmpty(condition)) { //Crappy logic processing -- for now boolean not = false; //Allow very simple matching logic to match templates against variable values int x = condition.indexOf("!="); getLogger().debug("Processing Condition : " + condition); if (x > -1) { not = true; requiredValue = condition.substring(x + 2).trim(); options = getListOfValues(requiredValue); condition = condition.substring(0, x).trim(); } else { x = condition.indexOf("="); if (x > -1) { requiredValue = condition.substring(x + 1); options = getListOfValues(requiredValue); condition = condition.substring(0, x); } } getLogger().debug("Not Expr: " + not); getLogger().debug("Condition Value: '" + condition + "'"); getLogger().debug("Required Value: '" + requiredValue + "'"); final Variable var = (Variable) findVariable(condition, variables); if (var != null) { final String strValue = (String) context.get(var.getName()); getLogger().debug("Variable Value is: '" + strValue + "'"); if (requiredValue == null) { if (!Boolean.valueOf(strValue).booleanValue()) { shouldProcess = false; } } else { if (!options.contains(strValue)) { shouldProcess = false; } } } else { getLogger().debug("Variable Value is: null"); shouldProcess = false; } if (not) { shouldProcess = !shouldProcess; } } if (shouldProcess) { processTemplate(template, outputDirectory, context); } else { getLogger().debug("Condition not met, skipping " + template.getOutput()); } } } catch (MalformedURLException mfe) { throw new ArchetypeTemplateProcessingException("Error loading archetype resources into the classpath", mfe); } finally { Thread.currentThread().setContextClassLoader(old); } // ---------------------------------------------------------------------- // Log message on Archetype creation // ---------------------------------------------------------------------- if (getLogger().isInfoEnabled()) { getLogger().info("Archetype created in dir: " + outputDirectory); } } protected void addParamToContext(String key, Object value, VelocityContext context) { getLogger().info("Adding Parameter to template Context: " + key + "=" + value); context.put(key, value); } protected void processVariables(Iterator variables, VelocityContext context, final boolean interactiveMode) throws ArchetypeTemplateProcessingException { while (variables.hasNext()) { Variable var = (Variable) variables.next(); String val = System.getProperty(var.getName(), var.getDefvalue()); if (interactiveMode) { StringBuffer message = new StringBuffer(); message.append(var.getName()).append(": ") .append(NEW_LINE) .append(StringUtils.repeat("*", MESSAGE_LINE_LENGTH)) .append(NEW_LINE) .append(NEW_LINE) .append(StringUtils.center(var.getDescription(), MESSAGE_LINE_LENGTH)) .append(NEW_LINE) .append(StringUtils.leftPad("[default: " + val + "]", MESSAGE_LINE_LENGTH)) .append(NEW_LINE) .append(StringUtils.repeat("*", MESSAGE_LINE_LENGTH)); getLogger().info(message.toString()); try { String answer = inputHandler.readLine(); if (!StringUtils.isEmpty(answer)) { val = answer; } } catch (IOException ie) { throw new ArchetypeTemplateProcessingException(ie); } context.put(var.getName(), val); } else { context.put(var.getName(), val); } if (val.toLowerCase().equals("false") || val.toLowerCase().equals("n")) { if (var.getVariables() != null) { //keep processing the variables picking up the default values processVariables(var.getVariables().iterator(), context, interactiveMode); } } else if (var.getVariables() != null) { //keep processing the variables picking up the default values processVariables(var.getVariables().iterator(), context, interactiveMode); } } } protected List getListOfValues(String s) { List options = new ArrayList(); for (StringTokenizer stringTokenizer = new StringTokenizer(s, "|"); stringTokenizer.hasMoreTokens();) { options.add(stringTokenizer.nextToken()); } return options; } protected void processTemplate(Template template, String outputDirectory, VelocityContext context) throws ArchetypeTemplateProcessingException { File outFile; try { StringWriter wout = new StringWriter(); velocity.getEngine().evaluate(context, wout, "output value", template.getOutput()); outFile = new File(outputDirectory, wout.toString()); getLogger().debug(outFile.getAbsolutePath()); FileUtils.forceMkdir(outFile.getParentFile()); getLogger().debug("Created directory: " + outFile.getParentFile() + ", Dir exists = " + outFile.getParentFile().exists()); } catch (Exception e) { e.printStackTrace(); throw new ArchetypeTemplateProcessingException("error evaluating output file name " + template.getOutput(), e); } Writer writer = null; try { getLogger().info("Processing Template: " + template.getFile()); String templateLocation = ARCHETYPE_RESOURCES + "/" + template.getFile(); writer = new FileWriter(outFile); velocity.getEngine().mergeTemplate(templateLocation, context, writer); writer.flush(); } catch (Exception e) { throw new ArchetypeTemplateProcessingException("Error merging velocity templates", e); } finally { IOUtil.close(writer); getLogger().info("Written Template to: " + outFile + ", file exists = " + outFile.exists()); } // Delete archetype-originated folders in case the output path is also templated. // Otherwise, there will be a processed folder AND the original folder. try { final File templateFile = new File(outputDirectory, template.getFile()); final String templateDir = FileUtils.dirname(templateFile.getCanonicalPath()); final String outputDir = FileUtils.dirname(outFile.getCanonicalPath()); if (getLogger().isDebugEnabled()) { getLogger().debug("TemplateDir=" + templateDir); getLogger().debug("OutputDir=" + outputDir); } if (!outputDir.startsWith(templateDir)) { getLogger().debug("Deleting Template Dir:" + templateDir); FileUtils.forceDelete(templateDir); } } catch (IOException e) { throw new ArchetypeTemplateProcessingException("Failed to cleanup the working dir.", e); } } /** * Find the variable. * * @param variableName name * @param variables all variables of the artifact * @return variable value or null of not found */ protected Object findVariable(String variableName, List variables) { for (int i = 0; i < variables.size(); i++) { Variable var = (Variable) variables.get(i); if (variableName.equals(var.getName())) { return var; } else if (var.getVariables() != null) { Object o = findVariable(variableName, var.getVariables()); if (o != null) { return o; } } } return null; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -