Search in sources :

Example 11 with MergeException

use of com.devonfw.cobigen.api.exception.MergeException in project cobigen by devonfw.

the class JSONMergerTest method readJsonFile.

/**
 * Reads the JSON file given by parameter
 *
 * @param fileName the file to read
 * @return the string with the file contents
 */
private String readJsonFile(String fileName) {
    File jsonPatchFile = new File(testFileRootPath + fileName);
    String file = jsonPatchFile.getAbsolutePath();
    Reader reader = null;
    String returnString;
    try {
        reader = new FileReader(file);
        returnString = IOUtils.toString(reader);
        reader.close();
    } catch (FileNotFoundException e) {
        throw new MergeException(jsonPatchFile, "Can not read file " + jsonPatchFile.getAbsolutePath());
    } catch (IOException e) {
        throw new MergeException(jsonPatchFile, "Can not read the base file " + jsonPatchFile.getAbsolutePath());
    }
    return returnString;
}
Also used : MergeException(com.devonfw.cobigen.api.exception.MergeException) FileNotFoundException(java.io.FileNotFoundException) FileReader(java.io.FileReader) Reader(java.io.Reader) FileReader(java.io.FileReader) IOException(java.io.IOException) File(java.io.File)

Example 12 with MergeException

use of com.devonfw.cobigen.api.exception.MergeException in project cobigen by devonfw.

the class TypeScriptMergerTest method readTSFile.

/**
 * Reads a TS file
 *
 * @param fileName the ts file
 * @return the content of the file
 */
private String readTSFile(String fileName) {
    File patchFile = new File(testFileRootPath + fileName);
    String file = patchFile.getAbsolutePath();
    Reader reader = null;
    String returnString;
    try {
        reader = new FileReader(file);
        returnString = IOUtils.toString(reader);
        reader.close();
    } catch (FileNotFoundException e) {
        throw new MergeException(patchFile, "Can not read file " + patchFile.getAbsolutePath());
    } catch (IOException e) {
        throw new MergeException(patchFile, "Can not read the base file " + patchFile.getAbsolutePath());
    }
    return returnString;
}
Also used : MergeException(com.devonfw.cobigen.api.exception.MergeException) FileNotFoundException(java.io.FileNotFoundException) Reader(java.io.Reader) FileReader(java.io.FileReader) FileReader(java.io.FileReader) IOException(java.io.IOException) File(java.io.File)

Example 13 with MergeException

use of com.devonfw.cobigen.api.exception.MergeException in project cobigen by devonfw.

the class GenerationProcessorImpl method generate.

/**
 * Generates code for the given input with the given template and the given {@link TriggerInterpreter} to the
 * destination specified by the templates configuration.
 *
 * @param template to be processed for generation
 * @param triggerInterpreter {@link TriggerInterpreter} to be used for reading the input and creating the model
 * @param origToTmpFileTrace the mapping of temporary generated files to their original target destination to
 *        eventually finalizing the generation process
 * @param progressCallback to track progress
 * @throws InvalidConfigurationException if the inputs do not fit to the configuration or there are some configuration
 *         failures
 */
private void generate(TemplateTo template, TriggerInterpreter triggerInterpreter, Map<File, File> origToTmpFileTrace, BiConsumer<String, Integer> progressCallback) {
    Trigger trigger = this.configurationHolder.readContextConfiguration().getTrigger(template.getTriggerId());
    InputReader inputReader = triggerInterpreter.getInputReader();
    if (!inputReader.isValidInput(this.input)) {
        throw new CobiGenRuntimeException("An invalid input of type " + this.input.getClass() + " has been passed to " + inputReader.getClass() + " (derived from trigger '" + trigger.getId() + "')");
    }
    List<Object> inputObjects = this.inputResolver.resolveContainerElements(this.input, trigger);
    TemplatesConfiguration tConfig = this.configurationHolder.readTemplatesConfiguration(trigger);
    String templateEngineName = tConfig.getTemplateEngine();
    TextTemplateEngine templateEngine = TemplateEngineRegistry.getEngine(templateEngineName);
    templateEngine.setTemplateFolder(this.configurationHolder.readContextConfiguration().getConfigurationPath().resolve(trigger.getTemplateFolder()));
    Template templateEty = tConfig.getTemplate(template.getId());
    if (templateEty == null) {
        throw new UnknownTemplateException(template.getId());
    }
    for (Object generatorInput : inputObjects) {
        progressCallback.accept("Building template model for input " + generatorInput, 1);
        Map<String, Object> model = buildModel(triggerInterpreter, trigger, generatorInput, templateEty);
        String targetCharset = templateEty.getTargetCharset();
        // resolve temporary file paths
        @SuppressWarnings("unchecked") PathExpressionResolver pathExpressionResolver = new PathExpressionResolver(Variables.fromMap((Map<String, String>) model.get(ModelBuilderImpl.NS_VARIABLES)));
        String resolvedTargetDestinationPath = pathExpressionResolver.evaluateExpressions(templateEty.getUnresolvedTargetPath());
        String resolvedTmpDestinationPath = pathExpressionResolver.evaluateExpressions(templateEty.getUnresolvedTemplatePath());
        File originalFile = this.targetRootPath.resolve(resolvedTargetDestinationPath).toFile();
        File tmpOriginalFile;
        if (origToTmpFileTrace.containsKey(originalFile)) {
            // use the available temporary file
            tmpOriginalFile = origToTmpFileTrace.get(originalFile);
        } else {
            tmpOriginalFile = this.tmpTargetRootPath.resolve(resolvedTmpDestinationPath).toFile();
            // remember mapping to later on copy the generated resources to its target destinations
            origToTmpFileTrace.put(originalFile, tmpOriginalFile);
        }
        if (originalFile.exists() || tmpOriginalFile.exists()) {
            if (!tmpOriginalFile.exists()) {
                try {
                    FileUtils.copyFile(originalFile, tmpOriginalFile);
                } catch (IOException e) {
                    throw new CobiGenRuntimeException("Could not copy file " + originalFile.getPath() + " to tmp generation directory! Generation skipped.", e);
                }
            }
            if ((this.forceOverride || template.isForceOverride()) && templateEty.getMergeStrategy() == null || ConfigurationConstants.MERGE_STRATEGY_OVERRIDE.equals(templateEty.getMergeStrategy())) {
                try (Formatter formatter = new Formatter()) {
                    formatter.format("Overriding %1$-40s FROM %2$-50s TO %3$s ...", originalFile.getName(), templateEty.getName(), resolvedTargetDestinationPath);
                    LOG.info(formatter.out().toString());
                    progressCallback.accept(formatter.out().toString(), 1);
                }
                progressCallback.accept("Generating " + template.getId() + " for " + generatorInput, 1);
                generateTemplateAndWriteFile(tmpOriginalFile, templateEty, templateEngine, model, targetCharset);
            } else if (templateEty.getMergeStrategy() != null) {
                try (Formatter formatter = new Formatter()) {
                    formatter.format("Merging    %1$-40s FROM %2$-50s TO %3$s ...", originalFile.getName(), templateEty.getName(), resolvedTargetDestinationPath);
                    LOG.info(formatter.out().toString());
                    progressCallback.accept(formatter.out().toString(), 1);
                }
                String patch = null;
                try (Writer out = new StringWriter()) {
                    templateEngine.process(templateEty, model, out, targetCharset);
                    patch = out.toString();
                    String mergeResult = null;
                    Merger merger = PluginRegistry.getMerger(templateEty.getMergeStrategy());
                    if (merger != null) {
                        mergeResult = merger.merge(tmpOriginalFile, patch, targetCharset);
                    } else {
                        throw new PluginNotAvailableException("merge strategy '" + templateEty.getMergeStrategy() + "'", null);
                    }
                    if (mergeResult != null) {
                        LOG.debug("Merge {} with char set {}.", tmpOriginalFile.getName(), targetCharset);
                        FileUtils.writeStringToFile(tmpOriginalFile, mergeResult, targetCharset);
                    } else {
                        throw new PluginProcessingException("Merger " + merger.getType() + " returned null on merge(...), which is not allowed.");
                    }
                } catch (MergeException e) {
                    writeBrokenPatchFile(targetCharset, tmpOriginalFile, patch);
                    // enrich merge exception to provide template ID
                    throw new MergeException(e, templateEty.getAbsoluteTemplatePath());
                } catch (IOException e) {
                    throw new CobiGenRuntimeException("Could not write file " + tmpOriginalFile.toPath() + " after merge.", e);
                }
            }
        } else {
            try (Formatter formatter = new Formatter()) {
                formatter.format("Generating %1$-40s FROM %2$-50s TO %3$s ...", originalFile.getName(), templateEty.getName(), resolvedTargetDestinationPath);
                LOG.info(formatter.out().toString());
                progressCallback.accept(formatter.out().toString(), 1);
            }
            generateTemplateAndWriteFile(tmpOriginalFile, templateEty, templateEngine, model, targetCharset);
        }
    }
}
Also used : CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) Formatter(java.util.Formatter) IOException(java.io.IOException) PluginNotAvailableException(com.devonfw.cobigen.api.exception.PluginNotAvailableException) PluginProcessingException(com.devonfw.cobigen.impl.exceptions.PluginProcessingException) TemplatesConfiguration(com.devonfw.cobigen.impl.config.TemplatesConfiguration) Template(com.devonfw.cobigen.impl.config.entity.Template) InputReader(com.devonfw.cobigen.api.extension.InputReader) Trigger(com.devonfw.cobigen.impl.config.entity.Trigger) Merger(com.devonfw.cobigen.api.extension.Merger) StringWriter(java.io.StringWriter) TextTemplateEngine(com.devonfw.cobigen.api.extension.TextTemplateEngine) MergeException(com.devonfw.cobigen.api.exception.MergeException) UnknownTemplateException(com.devonfw.cobigen.impl.exceptions.UnknownTemplateException) Map(java.util.Map) File(java.io.File) PathExpressionResolver(com.devonfw.cobigen.impl.config.resolver.PathExpressionResolver) Writer(java.io.Writer) StringWriter(java.io.StringWriter)

Aggregations

MergeException (com.devonfw.cobigen.api.exception.MergeException)13 IOException (java.io.IOException)9 File (java.io.File)6 FileNotFoundException (java.io.FileNotFoundException)3 FileReader (java.io.FileReader)3 InputStreamReader (java.io.InputStreamReader)3 Reader (java.io.Reader)3 Test (org.junit.Test)3 FileInputStream (java.io.FileInputStream)2 Path (java.nio.file.Path)2 CobiGenRuntimeException (com.devonfw.cobigen.api.exception.CobiGenRuntimeException)1 InputReaderException (com.devonfw.cobigen.api.exception.InputReaderException)1 PluginNotAvailableException (com.devonfw.cobigen.api.exception.PluginNotAvailableException)1 InputReader (com.devonfw.cobigen.api.extension.InputReader)1 Merger (com.devonfw.cobigen.api.extension.Merger)1 TextTemplateEngine (com.devonfw.cobigen.api.extension.TextTemplateEngine)1 MergeTo (com.devonfw.cobigen.api.externalprocess.to.MergeTo)1 GeneratorCreationException (com.devonfw.cobigen.eclipse.common.exceptions.GeneratorCreationException)1 TemplatesConfiguration (com.devonfw.cobigen.impl.config.TemplatesConfiguration)1 Template (com.devonfw.cobigen.impl.config.entity.Template)1