Search in sources :

Example 1 with TRUNCATE_EXISTING

use of java.nio.file.StandardOpenOption.TRUNCATE_EXISTING in project briefcase by opendatakit.

the class ExportToCsv method export.

/**
 * Export a form's submissions into some CSV files.
 * <p>
 * If the form has repeat groups, each repeat group will be exported into a separate CSV file.
 *
 * @param formDef       the {@link FormDefinition} form definition of the form to be exported
 * @param configuration the {@link ExportConfiguration} export configuration
 * @return an {@link ExportOutcome} with the export operation's outcome
 * @see ExportConfiguration
 */
private static ExportOutcome export(FormMetadataPort formMetadataPort, FormMetadata formMetadata, FormStatus formStatus, FormDefinition formDef, Path briefcaseDir, ExportConfiguration configuration, Optional<Analytics> analytics) {
    // Create an export tracker object with the total number of submissions we have to export
    ExportProcessTracker exportTracker = new ExportProcessTracker(formDef);
    exportTracker.start();
    SubmissionExportErrorCallback onParsingError = buildParsingErrorCallback(configuration.getErrorsDir(formDef.getFormName()));
    SubmissionExportErrorCallback onInvalidSubmission = buildParsingErrorCallback(configuration.getErrorsDir(formDef.getFormName())).andThen((path, message) -> analytics.ifPresent(ga -> ga.event("Export", "Export", "invalid submission", null)));
    List<Path> submissionFiles = getListOfSubmissionFiles(formMetadata, formDef, configuration.getDateRange(), configuration.resolveSmartAppend(), onParsingError);
    exportTracker.trackTotal(submissionFiles.size());
    createDirectories(configuration.getExportDir());
    List<Csv> csvs = Csv.getCsvs(formDef, configuration);
    csvs.forEach(Csv::prepareOutputFiles);
    if (formDef.getModel().hasAuditField()) {
        Path audit = configuration.getAuditPath(formDef.getFormName());
        if (!exists(audit) || configuration.resolveOverwriteExistingFiles())
            write(audit, "instance ID, event, node, start, end\n", CREATE, WRITE, TRUNCATE_EXISTING);
    }
    // Generate csv lines grouped by the fqdn of the model they belong to
    Map<String, CsvLines> csvLinesPerModel = ExportTools.getValidSubmissions(formDef, configuration, submissionFiles, onParsingError, onInvalidSubmission).peek(s -> exportTracker.incAndReport()).flatMap(submission -> csvs.stream().map(Csv::getMapper).map(mapper -> mapper.apply(submission))).collect(groupingByConcurrent(CsvLines::getModelFqn, reducing(CsvLines.empty(), CsvLines::merge)));
    // TODO We should have an extra step to produce the side effect of writing media files to disk to avoid having side-effects while generating the CSV output of binary fields
    // Write lines to each output Csv
    csvs.forEach(csv -> csv.appendLines(Optional.ofNullable(csvLinesPerModel.get(csv.getModelFqn())).orElse(CsvLines.empty())));
    exportTracker.end();
    Optional.ofNullable(csvLinesPerModel.get(formDef.getModel().fqn())).orElse(CsvLines.empty()).getLastLine().ifPresent(line -> {
        formMetadataPort.execute(updateLastExportedSubmission(formMetadata.getKey(), line.getInstanceId(), line.getSubmissionDate(), OffsetDateTime.now(), briefcaseDir, formStatus.getFormDir(briefcaseDir)));
    });
    ExportOutcome exportOutcome = exportTracker.computeOutcome();
    if (exportOutcome == ALL_EXPORTED)
        EventBus.publish(ExportEvent.successForm(formDef, (int) exportTracker.total));
    if (exportOutcome == SOME_SKIPPED)
        EventBus.publish(ExportEvent.partialSuccessForm(formDef, (int) exportTracker.exported, (int) exportTracker.total));
    if (exportOutcome == ALL_SKIPPED)
        EventBus.publish(ExportEvent.failure(formDef, "All submissions have been skipped"));
    return exportOutcome;
}
Also used : UncheckedFiles.deleteRecursive(org.opendatakit.briefcase.reused.UncheckedFiles.deleteRecursive) TRUNCATE_EXISTING(java.nio.file.StandardOpenOption.TRUNCATE_EXISTING) LoggerFactory(org.slf4j.LoggerFactory) UncheckedFiles.copy(org.opendatakit.briefcase.reused.UncheckedFiles.copy) FormMetadataCommands.updateLastExportedSubmission(org.opendatakit.briefcase.model.form.FormMetadataCommands.updateLastExportedSubmission) ALL_EXPORTED(org.opendatakit.briefcase.export.ExportOutcome.ALL_EXPORTED) FormMetadataPort(org.opendatakit.briefcase.model.form.FormMetadataPort) EventBus(org.bushe.swing.event.EventBus) Map(java.util.Map) FormMetadata(org.opendatakit.briefcase.model.form.FormMetadata) ALL_SKIPPED(org.opendatakit.briefcase.export.ExportOutcome.ALL_SKIPPED) Path(java.nio.file.Path) WRITE(java.nio.file.StandardOpenOption.WRITE) SOME_SKIPPED(org.opendatakit.briefcase.export.ExportOutcome.SOME_SKIPPED) Collectors.groupingByConcurrent(java.util.stream.Collectors.groupingByConcurrent) FormStatus(org.opendatakit.briefcase.model.FormStatus) Logger(org.slf4j.Logger) Collectors.reducing(java.util.stream.Collectors.reducing) UncheckedFiles.createDirectories(org.opendatakit.briefcase.reused.UncheckedFiles.createDirectories) UncheckedFiles.exists(org.opendatakit.briefcase.reused.UncheckedFiles.exists) List(java.util.List) UncheckedFiles.write(org.opendatakit.briefcase.reused.UncheckedFiles.write) OffsetDateTime(java.time.OffsetDateTime) CREATE(java.nio.file.StandardOpenOption.CREATE) Optional(java.util.Optional) Analytics(org.opendatakit.briefcase.ui.reused.Analytics) SubmissionParser.getListOfSubmissionFiles(org.opendatakit.briefcase.export.SubmissionParser.getListOfSubmissionFiles) Path(java.nio.file.Path)

Example 2 with TRUNCATE_EXISTING

use of java.nio.file.StandardOpenOption.TRUNCATE_EXISTING in project jreleaser by jreleaser.

the class JsonSchema method execute.

protected void execute() {
    Map<String, String> mappings = new LinkedHashMap<>();
    mappings.put("Map<String, Object>", "Properties");
    mappings.put("Map<String, String>", "StringProperties");
    mappings.put("Map<String, Webhook>", "WebhookMap");
    mappings.put("Map<String, Archive>", "ArchiveMap");
    mappings.put("Map<String, Jlink>", "JlinkMap");
    mappings.put("Map<String, Jpackage>", "JpackageMap");
    mappings.put("Map<String, NativeImage>", "NativeImageMap");
    mappings.put("Map<String, Distribution>", "DistributionMap");
    mappings.put("Map<String, DockerSpec>", "DockerSpecMap");
    mappings.put("Map<String, Artifactory>", "ArtifactoryMap");
    mappings.put("Map<String, Http>", "HttpMap");
    mappings.put("Map<String, S3>", "S3Map");
    try {
        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON);
        configBuilder.getObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
        configBuilder.with(Option.FORBIDDEN_ADDITIONAL_PROPERTIES_BY_DEFAULT);
        configBuilder.with(Option.DEFINITION_FOR_MAIN_SCHEMA);
        configBuilder.with(Option.DEFINITIONS_FOR_ALL_OBJECTS);
        JacksonModule jacksonModule = new JacksonModule();
        configBuilder.with(jacksonModule);
        configBuilder.forTypesInGeneral().withDescriptionResolver(scope -> scope.getType().getErasedType() == JReleaserModel.class ? String.format("JReleaser %s", JReleaserVersion.getPlainVersion()) : null).withPatternPropertiesResolver(scope -> {
            if (scope.getType().isInstanceOf(Map.class)) {
                ResolvedType type = scope.getTypeParameterFor(Map.class, 1);
                if (type.getErasedType() != String.class && type.getErasedType() != Object.class) {
                    return singletonMap("^[a-zA-Z-]+$", type);
                }
            }
            return null;
        }).withAdditionalPropertiesResolver(scope -> {
            if (scope.getType().isInstanceOf(Map.class)) {
                ResolvedType type = scope.getTypeParameterFor(Map.class, 1);
                if (type.getErasedType() == String.class || type.getErasedType() == Object.class) {
                    return scope.getTypeParameterFor(Map.class, 0);
                }
            }
            return null;
        }).withDefinitionNamingStrategy(new DefaultSchemaDefinitionNamingStrategy() {

            @Override
            public String getDefinitionNameForKey(DefinitionKey key, SchemaGenerationContext context) {
                String definitionNameForKey = super.getDefinitionNameForKey(key, context);
                return mappings.getOrDefault(definitionNameForKey, definitionNameForKey);
            }
        });
        SchemaGeneratorConfig config = configBuilder.build();
        SchemaGenerator generator = new SchemaGenerator(config);
        JsonNode jsonSchema = generator.generateSchema(JReleaserModel.class);
        String fileName = String.format("jreleaser-%s-schema.json", JReleaserVersion.getPlainVersion());
        Path schemaPath = Paths.get(fileName);
        String json = configBuilder.getObjectMapper().writeValueAsString(jsonSchema);
        Files.write(schemaPath, json.getBytes(), CREATE, WRITE, TRUNCATE_EXISTING);
        parent().out.println("Schema written to " + schemaPath.toAbsolutePath());
    } catch (Exception e) {
        throw new JReleaserException($("ERROR_unexpected_error"), e);
    }
}
Also used : Option(com.github.victools.jsonschema.generator.Option) TRUNCATE_EXISTING(java.nio.file.StandardOpenOption.TRUNCATE_EXISTING) SchemaGeneratorConfigBuilder(com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder) JReleaserModel(org.jreleaser.model.JReleaserModel) ResolvedType(com.fasterxml.classmate.ResolvedType) SchemaVersion(com.github.victools.jsonschema.generator.SchemaVersion) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) Collections.singletonMap(java.util.Collections.singletonMap) Path(java.nio.file.Path) CommandLine(picocli.CommandLine) WRITE(java.nio.file.StandardOpenOption.WRITE) Files(java.nio.file.Files) OptionPreset(com.github.victools.jsonschema.generator.OptionPreset) SchemaGenerationContext(com.github.victools.jsonschema.generator.SchemaGenerationContext) DefinitionKey(com.github.victools.jsonschema.generator.impl.DefinitionKey) SchemaGenerator(com.github.victools.jsonschema.generator.SchemaGenerator) DefaultSchemaDefinitionNamingStrategy(com.github.victools.jsonschema.generator.naming.DefaultSchemaDefinitionNamingStrategy) JReleaserVersion(org.jreleaser.model.JReleaserVersion) Paths(java.nio.file.Paths) SchemaGeneratorConfig(com.github.victools.jsonschema.generator.SchemaGeneratorConfig) CREATE(java.nio.file.StandardOpenOption.CREATE) JReleaserException(org.jreleaser.util.JReleaserException) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) JacksonModule(com.github.victools.jsonschema.module.jackson.JacksonModule) Path(java.nio.file.Path) SchemaGenerationContext(com.github.victools.jsonschema.generator.SchemaGenerationContext) SchemaGenerator(com.github.victools.jsonschema.generator.SchemaGenerator) JsonNode(com.fasterxml.jackson.databind.JsonNode) DefaultSchemaDefinitionNamingStrategy(com.github.victools.jsonschema.generator.naming.DefaultSchemaDefinitionNamingStrategy) JacksonModule(com.github.victools.jsonschema.module.jackson.JacksonModule) JReleaserException(org.jreleaser.util.JReleaserException) LinkedHashMap(java.util.LinkedHashMap) JReleaserException(org.jreleaser.util.JReleaserException) SchemaGeneratorConfig(com.github.victools.jsonschema.generator.SchemaGeneratorConfig) SchemaGeneratorConfigBuilder(com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder) JReleaserModel(org.jreleaser.model.JReleaserModel) DefinitionKey(com.github.victools.jsonschema.generator.impl.DefinitionKey) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) ResolvedType(com.fasterxml.classmate.ResolvedType)

Example 3 with TRUNCATE_EXISTING

use of java.nio.file.StandardOpenOption.TRUNCATE_EXISTING in project tcMenu by davetcc.

the class PluginRequiredFileProcessor method generatePluginsForCreator.

protected void generatePluginsForCreator(CodePluginItem item, Path directory) throws TcMenuConversionException {
    var expando = new CodeParameter(CodeParameter.NO_TYPE, null, true, "");
    var filteredSourceFiles = item.getRequiredSourceFiles().stream().filter(sf -> sf.getApplicability().isApplicable(context.getProperties())).collect(Collectors.toList());
    for (var srcFile : filteredSourceFiles) {
        try {
            var fileName = expando.expandExpression(context, srcFile.getFileName());
            // get the source (either from the plugin or from the tcMenu library)
            String fileNamePart;
            String fileData;
            Path location = item.getConfig().getPath().resolve(fileName);
            try (var sourceInputStream = new FileInputStream(location.toFile())) {
                fileData = new String(sourceInputStream.readAllBytes());
                fileNamePart = Paths.get(fileName).getFileName().toString();
            } catch (Exception e) {
                throw new TcMenuConversionException("Unable to locate file in plugin: " + srcFile, e);
            }
            Path resolvedOutputFile = directory.resolve(fileNamePart);
            if (!srcFile.isOverwritable() && Files.exists(resolvedOutputFile)) {
                uiLogger.accept(WARNING, "Source file " + srcFile.getFileName() + " already exists and overwrite is false, skipping");
            } else {
                uiLogger.accept(INFO, "Copy plugin file: " + srcFile.getFileName());
                for (var cr : srcFile.getReplacementList()) {
                    if (cr.getApplicability().isApplicable(context.getProperties())) {
                        uiLogger.accept(DEBUG, "Plugin file replacement: " + cr.getFind() + " to " + cr.getReplace());
                        var replacement = StringHelper.escapeRex(expando.expandExpression(context, cr.getReplace()));
                        fileData = fileData.replaceAll(cr.getFind(), replacement);
                    }
                }
                Files.write(resolvedOutputFile, fileData.getBytes(), TRUNCATE_EXISTING, CREATE);
            }
        // and copy into the destination
        } catch (Exception e) {
            throw new TcMenuConversionException("Unexpected exception processing " + srcFile, e);
        }
    }
}
Also used : StringHelper(com.thecoderscorner.menu.editorui.util.StringHelper) Files(java.nio.file.Files) TRUNCATE_EXISTING(java.nio.file.StandardOpenOption.TRUNCATE_EXISTING) CodeParameter(com.thecoderscorner.menu.editorui.generator.parameters.CodeParameter) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) List(java.util.List) CodePluginItem(com.thecoderscorner.menu.editorui.generator.plugin.CodePluginItem) Paths(java.nio.file.Paths) CREATE(java.nio.file.StandardOpenOption.CREATE) BiConsumer(java.util.function.BiConsumer) RequiredSourceFile(com.thecoderscorner.menu.editorui.generator.plugin.RequiredSourceFile) Path(java.nio.file.Path) Level(java.lang.System.Logger.Level) Path(java.nio.file.Path) CodeParameter(com.thecoderscorner.menu.editorui.generator.parameters.CodeParameter) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException)

Example 4 with TRUNCATE_EXISTING

use of java.nio.file.StandardOpenOption.TRUNCATE_EXISTING in project briefcase by getodk.

the class ExportToCsv method export.

/**
 * Export a form's submissions into some CSV files.
 * <p>
 * If the form has repeat groups, each repeat group will be exported into a separate CSV file.
 *
 * @param formDef       the {@link FormDefinition} form definition of the form to be exported
 * @param configuration the {@link ExportConfiguration} export configuration
 * @return an {@link ExportOutcome} with the export operation's outcome
 * @see ExportConfiguration
 */
private static ExportOutcome export(FormMetadataPort formMetadataPort, FormMetadata formMetadata, FormStatus formStatus, FormDefinition formDef, Path briefcaseDir, ExportConfiguration configuration, Optional<Analytics> analytics) {
    // Create an export tracker object with the total number of submissions we have to export
    ExportProcessTracker exportTracker = new ExportProcessTracker(formDef);
    exportTracker.start();
    SubmissionExportErrorCallback onParsingError = buildParsingErrorCallback(configuration.getErrorsDir(formDef.getFormName()));
    SubmissionExportErrorCallback onInvalidSubmission = buildParsingErrorCallback(configuration.getErrorsDir(formDef.getFormName())).andThen((path, message) -> analytics.ifPresent(ga -> ga.event("Export", "Export", "invalid submission", null)));
    List<Path> submissionFiles = getListOfSubmissionFiles(formMetadata, formDef, configuration.getDateRange(), configuration.resolveSmartAppend(), onParsingError);
    exportTracker.trackTotal(submissionFiles.size());
    createDirectories(configuration.getExportDir());
    List<Csv> csvs = Csv.getCsvs(formDef, configuration);
    csvs.forEach(Csv::prepareOutputFiles);
    if (formDef.getModel().hasAuditField()) {
        Path audit = configuration.getAuditPath(formDef.getFormName());
        if (!exists(audit) || configuration.resolveOverwriteExistingFiles())
            write(audit, "instance ID, event, node, start, end\n", CREATE, WRITE, TRUNCATE_EXISTING);
    }
    // Generate csv lines grouped by the fqdn of the model they belong to
    Map<String, CsvLines> csvLinesPerModel = ExportTools.getValidSubmissions(formDef, configuration, submissionFiles, onParsingError, onInvalidSubmission).peek(s -> exportTracker.incAndReport()).flatMap(submission -> csvs.stream().map(Csv::getMapper).map(mapper -> mapper.apply(submission))).collect(groupingByConcurrent(CsvLines::getModelFqn, reducing(CsvLines.empty(), CsvLines::merge)));
    // TODO We should have an extra step to produce the side effect of writing media files to disk to avoid having side-effects while generating the CSV output of binary fields
    // Write lines to each output Csv
    csvs.forEach(csv -> csv.appendLines(Optional.ofNullable(csvLinesPerModel.get(csv.getModelFqn())).orElse(CsvLines.empty())));
    exportTracker.end();
    Optional.ofNullable(csvLinesPerModel.get(formDef.getModel().fqn())).orElse(CsvLines.empty()).getLastLine().ifPresent(line -> {
        formMetadataPort.execute(updateLastExportedSubmission(formMetadata.getKey(), line.getInstanceId(), line.getSubmissionDate(), OffsetDateTime.now(), briefcaseDir, formStatus.getFormDir(briefcaseDir)));
    });
    ExportOutcome exportOutcome = exportTracker.computeOutcome();
    if (exportOutcome == ALL_EXPORTED)
        EventBus.publish(ExportEvent.successForm(formDef, (int) exportTracker.total));
    if (exportOutcome == SOME_SKIPPED)
        EventBus.publish(ExportEvent.partialSuccessForm(formDef, (int) exportTracker.exported, (int) exportTracker.total));
    if (exportOutcome == ALL_SKIPPED)
        EventBus.publish(ExportEvent.failure(formDef, "All submissions have been skipped"));
    return exportOutcome;
}
Also used : UncheckedFiles.deleteRecursive(org.opendatakit.briefcase.reused.UncheckedFiles.deleteRecursive) TRUNCATE_EXISTING(java.nio.file.StandardOpenOption.TRUNCATE_EXISTING) LoggerFactory(org.slf4j.LoggerFactory) UncheckedFiles.copy(org.opendatakit.briefcase.reused.UncheckedFiles.copy) FormMetadataCommands.updateLastExportedSubmission(org.opendatakit.briefcase.model.form.FormMetadataCommands.updateLastExportedSubmission) ALL_EXPORTED(org.opendatakit.briefcase.export.ExportOutcome.ALL_EXPORTED) FormMetadataPort(org.opendatakit.briefcase.model.form.FormMetadataPort) EventBus(org.bushe.swing.event.EventBus) Map(java.util.Map) FormMetadata(org.opendatakit.briefcase.model.form.FormMetadata) ALL_SKIPPED(org.opendatakit.briefcase.export.ExportOutcome.ALL_SKIPPED) Path(java.nio.file.Path) WRITE(java.nio.file.StandardOpenOption.WRITE) SOME_SKIPPED(org.opendatakit.briefcase.export.ExportOutcome.SOME_SKIPPED) Collectors.groupingByConcurrent(java.util.stream.Collectors.groupingByConcurrent) FormStatus(org.opendatakit.briefcase.model.FormStatus) Logger(org.slf4j.Logger) Collectors.reducing(java.util.stream.Collectors.reducing) UncheckedFiles.createDirectories(org.opendatakit.briefcase.reused.UncheckedFiles.createDirectories) UncheckedFiles.exists(org.opendatakit.briefcase.reused.UncheckedFiles.exists) List(java.util.List) UncheckedFiles.write(org.opendatakit.briefcase.reused.UncheckedFiles.write) OffsetDateTime(java.time.OffsetDateTime) CREATE(java.nio.file.StandardOpenOption.CREATE) Optional(java.util.Optional) Analytics(org.opendatakit.briefcase.ui.reused.Analytics) SubmissionParser.getListOfSubmissionFiles(org.opendatakit.briefcase.export.SubmissionParser.getListOfSubmissionFiles) Path(java.nio.file.Path)

Aggregations

Path (java.nio.file.Path)4 CREATE (java.nio.file.StandardOpenOption.CREATE)4 TRUNCATE_EXISTING (java.nio.file.StandardOpenOption.TRUNCATE_EXISTING)4 WRITE (java.nio.file.StandardOpenOption.WRITE)3 List (java.util.List)3 Map (java.util.Map)3 Files (java.nio.file.Files)2 Paths (java.nio.file.Paths)2 OffsetDateTime (java.time.OffsetDateTime)2 Optional (java.util.Optional)2 Collectors.groupingByConcurrent (java.util.stream.Collectors.groupingByConcurrent)2 Collectors.reducing (java.util.stream.Collectors.reducing)2 EventBus (org.bushe.swing.event.EventBus)2 ResolvedType (com.fasterxml.classmate.ResolvedType)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 SerializationFeature (com.fasterxml.jackson.databind.SerializationFeature)1 Option (com.github.victools.jsonschema.generator.Option)1 OptionPreset (com.github.victools.jsonschema.generator.OptionPreset)1 SchemaGenerationContext (com.github.victools.jsonschema.generator.SchemaGenerationContext)1 SchemaGenerator (com.github.victools.jsonschema.generator.SchemaGenerator)1