JMadModelDefinitionExporterImpl.java

  1. // @formatter:off
  2. /*******************************************************************************
  3.  *
  4.  * This file is part of JMad.
  5.  *
  6.  * Copyright (c) 2008-2011, CERN. All rights reserved.
  7.  *
  8.  * Licensed under the Apache License, Version 2.0 (the "License");
  9.  * you may not use this file except in compliance with the License.
  10.  * You may obtain a copy of the License at
  11.  *
  12.  *     http://www.apache.org/licenses/LICENSE-2.0
  13.  *
  14.  * Unless required by applicable law or agreed to in writing, software
  15.  * distributed under the License is distributed on an "AS IS" BASIS,
  16.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17.  * See the License for the specific language governing permissions and
  18.  * limitations under the License.
  19.  *
  20.  ******************************************************************************/
  21. // @formatter:on

  22. /**
  23.  *
  24.  */
  25. package cern.accsoft.steering.jmad.modeldefs.io.impl;

  26. import java.io.File;
  27. import java.io.FileOutputStream;
  28. import java.io.IOException;
  29. import java.io.InputStream;
  30. import java.util.ArrayList;
  31. import java.util.Collection;
  32. import java.util.HashMap;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.zip.ZipEntry;
  36. import java.util.zip.ZipOutputStream;

  37. import org.slf4j.Logger;
  38. import org.slf4j.LoggerFactory;

  39. import cern.accsoft.steering.jmad.domain.file.ModelFile;
  40. import cern.accsoft.steering.jmad.domain.machine.SequenceDefinition;
  41. import cern.accsoft.steering.jmad.domain.machine.SequenceDefinitionImpl;
  42. import cern.accsoft.steering.jmad.modeldefs.domain.JMadModelDefinition;
  43. import cern.accsoft.steering.jmad.modeldefs.domain.JMadModelDefinitionImpl;
  44. import cern.accsoft.steering.jmad.modeldefs.io.JMadModelDefinitionExportRequest;
  45. import cern.accsoft.steering.jmad.modeldefs.io.JMadModelDefinitionExporter;
  46. import cern.accsoft.steering.jmad.modeldefs.io.ModelDefinitionPersistenceService;
  47. import cern.accsoft.steering.jmad.modeldefs.io.ModelFileFinder;
  48. import cern.accsoft.steering.jmad.modeldefs.io.ModelFileFinderManager;
  49. import cern.accsoft.steering.jmad.util.FileUtil;
  50. import cern.accsoft.steering.jmad.util.StreamUtil;
  51. import cern.accsoft.steering.jmad.util.xml.PersistenceServiceException;

  52. /**
  53.  * This is the default implementation of the {@link JMadModelDefinitionExporter}
  54.  *
  55.  * @author Kajetan Fuchsberger (kajetan.fuchsberger at cern.ch)
  56.  */
  57. public class JMadModelDefinitionExporterImpl implements JMadModelDefinitionExporter {
  58.     /**
  59.      * The persistence service to use to write model definition to xml. (injected by
  60.      * spring)
  61.      */
  62.     private List<ModelDefinitionPersistenceService> persistenceServices = new ArrayList<ModelDefinitionPersistenceService>();

  63.     /**
  64.      * The class which keeps track of file finders for the model definitions.
  65.      */
  66.     private ModelFileFinderManager fileFinderManager;

  67.     /** The logger for the class */
  68.     private static final Logger LOGGER = LoggerFactory.getLogger(JMadModelDefinitionExporterImpl.class);

  69.     @Override
  70.     public File export(JMadModelDefinitionExportRequest exportRequest, File exportPath) {
  71.         if (exportRequest == null) {
  72.             LOGGER.error("No model definition given to export.");
  73.             return null;
  74.         }
  75.         if (exportPath == null) {
  76.             LOGGER.error("No file given. Cannot export model definition.");
  77.             return null;
  78.         }

  79.         ModelDefinitionPersistenceService persistenceService = findPersistenceService(exportPath.getName());

  80.         if (persistenceService != null || exportPath.isDirectory()) {
  81.             return exportAsFiles(exportRequest, exportPath);
  82.         } else {
  83.             /* per default we export as zip */
  84.             return exportAsZip(exportRequest, exportPath);
  85.         }
  86.     }

  87.     @Override
  88.     public File exportAsFiles(JMadModelDefinitionExportRequest exportRequest, File exportPath) {
  89.         if (exportRequest == null) {
  90.             LOGGER.error("No model definition given to export.");
  91.             return null;
  92.         }
  93.         if (exportPath == null) {
  94.             LOGGER.error("No destination dir given. Cannot export model definition.");
  95.             return null;
  96.         }
  97.         JMadModelDefinition modelDefinition = tailorModelDefinition(exportRequest);

  98.         File xmlFile;
  99.         File destDir;
  100.         if (exportPath.isDirectory()) {
  101.             destDir = exportPath;
  102.             /* per default we save as xml */
  103.             xmlFile = new File(destDir.getAbsolutePath() + File.separator + getFileName(modelDefinition));
  104.         } else {
  105.             destDir = exportPath.getAbsoluteFile().getParentFile();
  106.             xmlFile = exportPath;
  107.         }
  108.         FileUtil.createDir(destDir, false);

  109.         /*
  110.          * first we save the model-def file. If it matches one of the extensions of the
  111.          * persisters, then we use that one, otherwise we use the default.
  112.          */
  113.         ModelDefinitionPersistenceService persistenceService = findPersistenceService(xmlFile.getAbsolutePath());
  114.         if (persistenceService == null) {
  115.             xmlFile = new File(xmlFile.getAbsolutePath() + ModelDefinitionUtil.getDefaultFileExtension());
  116.             persistenceService = findPersistenceService(xmlFile.getAbsolutePath());
  117.         }
  118.         if (persistenceService == null) {
  119.             LOGGER.error("Cannot find appropriate persistence service for file '" + xmlFile.getAbsolutePath() + "'.");
  120.         }

  121.         try {

  122.             persistenceService.save(modelDefinition, xmlFile);

  123.             /*
  124.              * then we loop through all model files and copy all the files.
  125.              */
  126.             ModelFileFinder fileFinder = getFileFinderManager().getModelFileFinder(modelDefinition);
  127.             for (ModelFile modelFile : getRequiredFiles(modelDefinition)) {
  128.                 /*
  129.                  * We use the archive path here. So the file structure is the same as inside the
  130.                  * zip archive.
  131.                  */
  132.                 String archivePath = fileFinder.getArchivePath(modelFile);
  133.                 File file = new File(destDir.getAbsolutePath() + File.separator + archivePath);

  134.                 /*
  135.                  * ensure that the parent dir exists
  136.                  */
  137.                 FileUtil.createDir(file.getAbsoluteFile().getParentFile(), false);

  138.                 InputStream inStream = fileFinder.getStream(modelFile);
  139.                 if (!StreamUtil.toFile(inStream, file)) {
  140.                     LOGGER.error("Could not write file '" + file.getAbsolutePath() + "'");
  141.                     return null;
  142.                 }
  143.             }
  144.             return xmlFile;
  145.         } catch (PersistenceServiceException e) {
  146.             LOGGER.error("Could not save model definition to file '" + xmlFile.getAbsolutePath() + "'.", e);
  147.         }
  148.         return null;
  149.     }

  150.     private ModelDefinitionPersistenceService findPersistenceService(String fileName) {
  151.         for (ModelDefinitionPersistenceService persistenceService : getPersistenceServices()) {
  152.             if (persistenceService.isCorrectFileName(fileName)) {
  153.                 return persistenceService;
  154.             }
  155.         }
  156.         return null;
  157.     }

  158.     @Override
  159.     public File exportAsZip(JMadModelDefinitionExportRequest exportRequest, File file) {
  160.         if (exportRequest == null) {
  161.             LOGGER.error("No model definition given to export.");
  162.             return null;
  163.         }
  164.         if (file == null) {
  165.             LOGGER.error("No file given. Cannot export model definition.");
  166.             return null;
  167.         }
  168.         JMadModelDefinition modelDefinition = tailorModelDefinition(exportRequest);

  169.         File zipFile = ModelDefinitionUtil.ensureZipFileExtension(file);

  170.         try {
  171.             /* Create the output stream */
  172.             ZipOutputStream outStream;
  173.             outStream = new ZipOutputStream(new FileOutputStream(zipFile));

  174.             String baseName = ModelDefinitionUtil.getProposedIdStringFromName(modelDefinition);

  175.             /* Add a zip entry to the output stream each persister we have */
  176.             for (ModelDefinitionPersistenceService persistenceService : getPersistenceServices()) {
  177.                 outStream.putNextEntry(new ZipEntry(baseName + persistenceService.getFileExtension()));
  178.                 persistenceService.save(modelDefinition, outStream);
  179.                 outStream.closeEntry();
  180.             }

  181.             /*
  182.              * next we need the corresponding ModelFileFinder to find all the required files
  183.              * and put them in the archive.
  184.              */
  185.             ModelFileFinder fileFinder = getFileFinderManager().getModelFileFinder(modelDefinition);

  186.             /*
  187.              * now we are ready to copy all the files into the archive.
  188.              */
  189.             for (ModelFile modelFile : getRequiredFiles(modelDefinition)) {
  190.                 outStream.putNextEntry(new ZipEntry(fileFinder.getArchivePath(modelFile)));
  191.                 InputStream inStream = fileFinder.getStream(modelFile);
  192.                 StreamUtil.copy(inStream, outStream);
  193.                 outStream.closeEntry();
  194.                 inStream.close();
  195.             }

  196.             outStream.close();
  197.             return zipFile;
  198.         } catch (IOException e) {
  199.             LOGGER.error("Could not save model definition to zip file '" + zipFile.getAbsolutePath() + "'", e);
  200.         } catch (PersistenceServiceException e) {
  201.             LOGGER.error("Could not save model definition to zip file '" + zipFile.getAbsolutePath() + "'", e);
  202.         }
  203.         return null;
  204.     }

  205.     private JMadModelDefinition tailorModelDefinition(JMadModelDefinitionExportRequest request) {
  206.         JMadModelDefinition modelDefinitionForExport = cloneModel(request.getModelDefinition());

  207.         /* remove optics/sequences/ranges not selected */
  208.         modelDefinitionForExport.getOpticsDefinitions().removeIf(o -> !(request.getOpticsToExport().contains(o)));
  209.         modelDefinitionForExport.getSequenceDefinitions().removeIf(s -> !(request.getSequencesToExport().contains(s)));
  210.         modelDefinitionForExport.getSequenceDefinitions().forEach(//
  211.                 seq -> seq.getRangeDefinitions().removeIf(r -> !(request.getRangesToExport().contains(r))));

  212.         /* remove empty sequences (no ranges) */
  213.         modelDefinitionForExport.getSequenceDefinitions().removeIf(s -> s.getRangeDefinitions().isEmpty());

  214.         /* if we end up with an empty model, throw */
  215.         if (modelDefinitionForExport.getOpticsDefinitions().isEmpty()) {
  216.             throw new IllegalArgumentException("no optics definitions have been selected for export!");
  217.         }
  218.         if (modelDefinitionForExport.getSequenceDefinitions().isEmpty()) {
  219.             throw new IllegalArgumentException("no sequence definitions have been selected for export!");
  220.         }
  221.         if (modelDefinitionForExport.getRangeDefinitions().isEmpty()) {
  222.             throw new IllegalArgumentException("no ranges have been selected for export!");
  223.         }

  224.         /* fix defaults */
  225.         if (!modelDefinitionForExport.getOpticsDefinitions()
  226.                 .contains(modelDefinitionForExport.getDefaultOpticsDefinition())) {
  227.             ((JMadModelDefinitionImpl) modelDefinitionForExport)
  228.                     .setDefaultOpticsDefinition(modelDefinitionForExport.getOpticsDefinitions().get(0));
  229.         }

  230.         if (!modelDefinitionForExport.getSequenceDefinitions()
  231.                 .contains(modelDefinitionForExport.getDefaultSequenceDefinition())) {
  232.             ((JMadModelDefinitionImpl) modelDefinitionForExport)
  233.                     .setDefaultSequenceDefinition(modelDefinitionForExport.getSequenceDefinitions().get(0));
  234.         }

  235.         for (SequenceDefinition sequence : modelDefinitionForExport.getSequenceDefinitions()) {
  236.             if (!sequence.getRangeDefinitions().contains(sequence.getDefaultRangeDefinition())) {
  237.                 ((SequenceDefinitionImpl) sequence).setDefaultRangeDefinition(sequence.getRangeDefinitions().get(0));
  238.             }
  239.         }

  240.         return modelDefinitionForExport;
  241.     }

  242.     private JMadModelDefinition cloneModel(JMadModelDefinition model) {
  243.         for (ModelDefinitionPersistenceService cloneService : persistenceServices) {
  244.             try {
  245.                 return cloneService.clone(model);
  246.             } catch (Exception e) {
  247.                 /* try next service */
  248.             }
  249.         }
  250.         throw new IllegalStateException("no persistence service was able to clone the model definition");
  251.     }

  252.     private String getFileName(JMadModelDefinition modelDefinition) {
  253.         if ((modelDefinition.getSourceInformation() != null)
  254.                 && (modelDefinition.getSourceInformation().getFileName() != null)) {
  255.             return modelDefinition.getSourceInformation().getFileName();
  256.         }
  257.         return ModelDefinitionUtil.getProposedDefaultFileName(modelDefinition);
  258.     }

  259.     /**
  260.      * collects all the required files for a model definition. it returns a
  261.      * collection which will contain all the model files with the same archive path
  262.      * only once.
  263.      *
  264.      * @param modelDefinition
  265.      *            the model definition for which to collect the files
  266.      * @return all the files, with unique archive-path
  267.      */
  268.     private Collection<ModelFile> getRequiredFiles(JMadModelDefinition modelDefinition) {
  269.         ModelFileFinder fileFinder = getFileFinderManager().getModelFileFinder(modelDefinition);
  270.         Map<String, ModelFile> modelFiles = new HashMap<String, ModelFile>();
  271.         for (ModelFile modelFile : ModelDefinitionUtil.getRequiredModelFiles(modelDefinition)) {
  272.             String archivePath = fileFinder.getArchivePath(modelFile);
  273.             modelFiles.put(archivePath, modelFile);
  274.         }
  275.         return modelFiles.values();
  276.     }

  277.     public void setFileFinderManager(ModelFileFinderManager fileFinderManager) {
  278.         this.fileFinderManager = fileFinderManager;
  279.     }

  280.     private ModelFileFinderManager getFileFinderManager() {
  281.         return fileFinderManager;
  282.     }

  283.     public void setPersistenceServices(List<ModelDefinitionPersistenceService> persistenceServices) {
  284.         this.persistenceServices = persistenceServices;
  285.     }

  286.     private List<ModelDefinitionPersistenceService> getPersistenceServices() {
  287.         return persistenceServices;
  288.     }

  289. }