Search in sources :

Example 1 with LocatableOutputSupplier

use of eu.esdihumboldt.hale.common.core.io.supplier.LocatableOutputSupplier in project hale by halestudio.

the class StreamGmlWriter method writeParts.

/**
 * Write the given {@link InstanceCollection}s to multiple files using the
 * configured target as a base file name.<br>
 * <br>
 * Parts can only be written if the configured target is a URI to a local
 * file. The output files will be named after the target file, amended by a
 * counter. If, for example, the configured target file name is
 * <code>output.gml</code>, the files created by this method will be called
 * <code>output.0001.gml</code>, <code>output.0002.gml</code>, etc.
 *
 * @param instanceCollections the parts to write
 * @param progress Progress indicator
 * @param reporter the reporter to use for the execution report
 * @throws IOException if an I/O operation fails
 * @see #setTarget(LocatableOutputSupplier)
 */
protected void writeParts(Iterator<InstanceCollection> instanceCollections, ProgressIndicator progress, IOReporter reporter) throws IOException {
    final URI location = getTarget().getLocation();
    if (location == null) {
        reporter.error("Cannot write multiple GML files: Output location unknown");
        return;
    }
    // Can only write multiple instance collection if target is a local file
    if (!"file".equals(location.getScheme())) {
        reporter.error("Cannot write multiple GML files: Target must be a local file");
        return;
    }
    Path origPath = Paths.get(location).normalize();
    String filename;
    String extension;
    Path targetFolder;
    if (origPath.toFile().isDirectory()) {
        reporter.error("Cannot write to a directory: Target must a file");
        return;
    // TODO Support writing to a directory; use parameter to specify
    // file name prefix.
    } else {
        targetFolder = origPath.getParent();
        filename = Files.getNameWithoutExtension(origPath.toString());
        extension = Files.getFileExtension(origPath.toString());
    }
    List<URI> filesWritten = new ArrayList<>();
    int i = 1;
    while (instanceCollections.hasNext()) {
        String targetFilename = String.format("%s%s%s.%04d.%s", targetFolder.toString(), File.separator, filename, i++, extension);
        File targetFile = new File(targetFilename);
        FileOutputStream out = new FileOutputStream(targetFile);
        InstanceCollection instances = instanceCollections.next();
        write(instances, out, progress, reporter);
        filesWritten.add(targetFile.toURI());
    }
    if (filesWritten.size() > 1) {
        setTarget(new MultiLocationOutputSupplier(filesWritten));
    } else if (!filesWritten.isEmpty()) {
        setTarget(new LocatableOutputSupplier<OutputStream>() {

            @Override
            public OutputStream getOutput() throws IOException {
                throw new UnsupportedOperationException();
            }

            @Override
            public URI getLocation() {
                return filesWritten.get(0);
            }
        });
    }
}
Also used : DefinitionPath(eu.esdihumboldt.hale.io.gml.writer.internal.geometry.DefinitionPath) Path(java.nio.file.Path) FileOutputStream(java.io.FileOutputStream) InstanceCollection(eu.esdihumboldt.hale.common.instance.model.InstanceCollection) ArrayList(java.util.ArrayList) MultiLocationOutputSupplier(eu.esdihumboldt.hale.common.core.io.supplier.MultiLocationOutputSupplier) URI(java.net.URI) File(java.io.File) LocatableOutputSupplier(eu.esdihumboldt.hale.common.core.io.supplier.LocatableOutputSupplier)

Example 2 with LocatableOutputSupplier

use of eu.esdihumboldt.hale.common.core.io.supplier.LocatableOutputSupplier in project hale by halestudio.

the class DefaultProjectWriter method execute.

/**
 * @see AbstractIOProvider#execute(ProgressIndicator, IOReporter)
 */
@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException {
    boolean separateProjectFiles = !archive || isUseSeparateFiles();
    URI targetLocation = getTarget().getLocation();
    File targetFile;
    try {
        targetFile = new File(targetLocation);
    } catch (Exception e) {
        if (!archive) {
            // cannot save as XML if it's not a file
            reporter.error(new IOMessageImpl("Could not determine project file path.", e));
            reporter.setSuccess(false);
            return reporter;
        }
        targetFile = null;
        // if it's not a file, we must save the project files inside the zip
        // stream
        separateProjectFiles = false;
    }
    int entries = 1;
    if (getProjectFiles() != null) {
        entries += getProjectFiles().size();
    }
    progress.begin("Save project", entries);
    // clear project file information that may already be contained in the
    // project
    getProject().getProjectFiles().clear();
    // files
    if (separateProjectFiles && targetFile != null) {
        for (Entry<String, ProjectFile> entry : getProjectFiles().entrySet()) {
            String name = entry.getKey();
            // determine target file for project file
            String projectFileName = targetFile.getName() + "." + name;
            final File pfile = new File(targetFile.getParentFile(), projectFileName);
            // the following line is basically
            // URI.create(escape(projectFileName))
            URI relativeProjectFile = targetFile.getParentFile().toURI().relativize(pfile.toURI());
            // add project file information to project
            getProject().getProjectFiles().add(new ProjectFileInfo(name, relativeProjectFile));
            // write entry
            ProjectFile file = entry.getValue();
            try {
                LocatableOutputSupplier<OutputStream> target = new LocatableOutputSupplier<OutputStream>() {

                    @Override
                    public OutputStream getOutput() throws IOException {
                        return new BufferedOutputStream(new FileOutputStream(pfile));
                    }

                    @Override
                    public URI getLocation() {
                        return pfile.toURI();
                    }
                };
                file.store(target);
            } catch (Exception e) {
                reporter.error(new IOMessageImpl("Error saving a project file.", e));
                reporter.setSuccess(false);
                return reporter;
            }
            progress.advance(1);
        }
    }
    updateRelativeResourcePaths(getProject().getResources(), getPreviousTarget(), targetLocation);
    if (archive) {
        // save to archive
        final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(getTarget().getOutput()));
        try {
            // write main entry
            zip.putNextEntry(new ZipEntry(ProjectIO.PROJECT_FILE));
            try {
                Project.save(getProject(), new EntryOutputStream(zip));
            } catch (Exception e) {
                reporter.error(new IOMessageImpl("Could not save main project configuration.", e));
                reporter.setSuccess(false);
                return reporter;
            }
            zip.closeEntry();
            progress.advance(1);
            // write additional project files to zip stream
            if (getProjectFiles() != null && !separateProjectFiles) {
                for (Entry<String, ProjectFile> entry : getProjectFiles().entrySet()) {
                    String name = entry.getKey();
                    if (name.equalsIgnoreCase(ProjectIO.PROJECT_FILE)) {
                        reporter.error(new IOMessageImpl("Invalid file name {0}. File name may not match the name of the main project configuration.", null, -1, -1, name));
                    } else {
                        // write entry
                        zip.putNextEntry(new ZipEntry(name));
                        ProjectFile file = entry.getValue();
                        try {
                            LocatableOutputSupplier<OutputStream> target = new LocatableOutputSupplier<OutputStream>() {

                                private boolean first = true;

                                @Override
                                public OutputStream getOutput() throws IOException {
                                    if (first) {
                                        first = false;
                                        return new EntryOutputStream(zip);
                                    }
                                    throw new IllegalStateException("Output stream only available once");
                                }

                                @Override
                                public URI getLocation() {
                                    return getTarget().getLocation();
                                }
                            };
                            file.store(target);
                        } catch (Exception e) {
                            reporter.error(new IOMessageImpl("Error saving a project file.", e));
                            reporter.setSuccess(false);
                            return reporter;
                        }
                        zip.closeEntry();
                    }
                    progress.advance(1);
                }
            }
        } finally {
            zip.close();
        }
    } else {
        // save project file to XML
        OutputStream out = getTarget().getOutput();
        try {
            Project.save(getProject(), out);
        } catch (Exception e) {
            reporter.error(new IOMessageImpl("Could not save main project file.", e));
            reporter.setSuccess(false);
            return reporter;
        } finally {
            out.close();
        }
        progress.advance(1);
    }
    reporter.setSuccess(true);
    return reporter;
}
Also used : ZipOutputStream(java.util.zip.ZipOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ZipEntry(java.util.zip.ZipEntry) IOMessageImpl(eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl) ProjectFile(eu.esdihumboldt.hale.common.core.io.project.model.ProjectFile) URI(java.net.URI) IOProviderConfigurationException(eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException) IOException(java.io.IOException) LocatableOutputSupplier(eu.esdihumboldt.hale.common.core.io.supplier.LocatableOutputSupplier) ZipOutputStream(java.util.zip.ZipOutputStream) ProjectFileInfo(eu.esdihumboldt.hale.common.core.io.project.model.ProjectFileInfo) FileOutputStream(java.io.FileOutputStream) ProjectFile(eu.esdihumboldt.hale.common.core.io.project.model.ProjectFile) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Aggregations

LocatableOutputSupplier (eu.esdihumboldt.hale.common.core.io.supplier.LocatableOutputSupplier)2 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 URI (java.net.URI)2 IOProviderConfigurationException (eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException)1 ProjectFile (eu.esdihumboldt.hale.common.core.io.project.model.ProjectFile)1 ProjectFileInfo (eu.esdihumboldt.hale.common.core.io.project.model.ProjectFileInfo)1 IOMessageImpl (eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl)1 MultiLocationOutputSupplier (eu.esdihumboldt.hale.common.core.io.supplier.MultiLocationOutputSupplier)1 InstanceCollection (eu.esdihumboldt.hale.common.instance.model.InstanceCollection)1 DefinitionPath (eu.esdihumboldt.hale.io.gml.writer.internal.geometry.DefinitionPath)1 BufferedOutputStream (java.io.BufferedOutputStream)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 Path (java.nio.file.Path)1 ArrayList (java.util.ArrayList)1 ZipEntry (java.util.zip.ZipEntry)1 ZipOutputStream (java.util.zip.ZipOutputStream)1