com.c4om.autoconf.ulysses.configanalyzer.guilauncher.TemporaryChangesetFilesSavingGUILauncher.java Source code

Java tutorial

Introduction

Here is the source code for com.c4om.autoconf.ulysses.configanalyzer.guilauncher.TemporaryChangesetFilesSavingGUILauncher.java

Source

/*
Copyright 2014 Universidad Politcnica de Madrid - Center for Open Middleware (http://www.centeropenmiddleware.com)
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.c4om.autoconf.ulysses.configanalyzer.guilauncher;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;

import net.sf.saxon.s9api.SaxonApiException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.XmlStreamWriter;
import org.jdom2.Document;

import com.c4om.autoconf.ulysses.configanalyzer.core.GUILauncher;
import com.c4om.autoconf.ulysses.configanalyzer.core.datastructures.Changeset;
import com.c4om.autoconf.ulysses.configanalyzer.core.datastructures.ConfigurationAnalysisContext;
import com.c4om.autoconf.ulysses.configanalyzer.core.datastructures.ExtractedConfiguration;
import com.c4om.autoconf.ulysses.configanalyzer.core.exceptions.GUILaunchException;
import com.c4om.autoconf.ulysses.configanalyzer.guilauncher.exceptions.CatalogGenerationException;
import com.c4om.autoconf.ulysses.configanalyzer.guilauncher.exceptions.TemporaryStorageException;
import com.c4om.autoconf.ulysses.interfaces.Target;
import com.google.common.collect.ImmutableMap;

import static com.c4om.utils.xmlutils.JDOMUtils.*;
import static com.c4om.utils.xmlutils.XMLLibsShortcuts.*;

/**
 * Class intended to those GUI launchers that need to store change sets as
 * temporary files before launching the GUI.
 * 
 * @author Pablo Alonso Rodrguez (Center for Open Middleware - UPM)
 * 
 */
public abstract class TemporaryChangesetFilesSavingGUILauncher implements GUILauncher {

    /**
     * Name of the generated XML catalog file.
     */
    private static final String CATALOG_XML_FILE_NAME = "catalog.xml";

    /**
     * Name of the external variable of the XQuery query pointed by {@link TemporaryChangesetFilesSavingGUILauncher#CATALOG_QUERY_PATH} 
     * that allows to choose the files to generate the catalog from. 
     */
    private static final String FILES_PARAMETER_NAME = "files";

    /**
     * Path to the XQuery query that generates the catalog
     */
    private static final String CATALOG_QUERY_PATH = "xquery/generateCatalog.xq";

    /**
     * The query to generate the catalog file
     */
    protected String generateCatalogQuery;

    /**
     * Constructor
     */
    public TemporaryChangesetFilesSavingGUILauncher() {
        InputStream input = getClass().getClassLoader().getResourceAsStream(CATALOG_QUERY_PATH);
        try {
            this.generateCatalogQuery = IOUtils.toString(input, "UTF-8");
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * This method generates the catalog file and stores it into the temporary folder
     * @param temporaryFolder the temporary folder
     * @param changesetPaths URIs poiting to changeset files
     * @throws CatalogGenerationException if there is any problem at catalog generation
     */
    private void generateCatalog(File temporaryFolder, List<URI> changesetPaths) throws CatalogGenerationException {
        try {
            Map<QName, List<URI>> variables = ImmutableMap.of(new QName(FILES_PARAMETER_NAME), changesetPaths);
            String catalogFileString = saxonQuery(generateCatalogQuery, variables);
            FileOutputStream fileOutputStream = new FileOutputStream(
                    new File(temporaryFolder, CATALOG_XML_FILE_NAME));
            Writer writer = new XmlStreamWriter(fileOutputStream, "UTF-8");
            writer.write(catalogFileString);
            writer.close();
        } catch (IOException | SaxonApiException e) {
            throw new CatalogGenerationException(e);
        }
    }

    /**
     * For each extracted configuration, this stores at its temporary folder all
     * the changesets asociated to it.
     * 
     * @param context
     *            the configuration context
     * @return a {@link List} the list of temporary folders with the extracted
     *         configurations and changesets.
     * @throws TemporaryStorageException If there is any problem storing the temporary files.
     * @throws GUILaunchException if there are other problems
     */
    protected List<File> getTemporaryStoredChangesetsAndConfigs(ConfigurationAnalysisContext context)
            throws TemporaryStorageException, GUILaunchException {
        return getTemporaryStoredChangesetsAndConfigs(context, null);
    }

    /**
     * For each extracted configuration, this stores at its temporary folder all
     * the changesets asociated to it.
     * 
     * @param context
     *            the configuration context
     * @param target the target to filter from. If null, no per-target filtering will be performed.
     * @return a {@link List} the list of temporary folders with the extracted
     *         configurations and changesets.
     * @throws TemporaryStorageException If there is any problem storing the temporary files.
     * @throws GUILaunchException if there are other problems
     */
    @SuppressWarnings("unchecked")
    protected List<File> getTemporaryStoredChangesetsAndConfigs(ConfigurationAnalysisContext context, Target target)
            throws TemporaryStorageException, GUILaunchException {
        try {
            List<File> results = new ArrayList<File>(context.getExtractedConfigurations().size());
            for (ExtractedConfiguration<?> extractedConfiguration : context.getExtractedConfigurations()) {
                if (!(extractedConfiguration.getConfigurationData().size() > 0)
                        || !(extractedConfiguration.getConfigurationData().get(0) instanceof File)) {
                    continue;
                }
                if (target != null && !extractedConfiguration.getTarget().equals(target)) {
                    continue;
                }
                // First, we get the temporary folder. It is the parent path of
                // all the URIs, so we get the parent path of the first one
                File temporaryFolder = ((File) extractedConfiguration.getConfigurationData().get(0))
                        .getParentFile();
                List<Changeset<Document>> changesetsToStore = new ArrayList<>();
                // Now, we look for all the change sets related to the
                // configuration.
                for (Changeset<?> changeset : context.getChangesets()) {
                    if (!(changeset.getChangesetData() instanceof Document)
                            || !changeset.getTarget().equals(extractedConfiguration.getTarget())) {
                        continue;
                    }
                    changesetsToStore.add((Changeset<Document>) changeset);
                }

                List<URI> changesetPathsForCatalog = new ArrayList<>(changesetsToStore.size());

                // Now, we store the change sets into the file system
                for (Changeset<Document> changesetToStore : changesetsToStore) {
                    File changesetFile = new File(temporaryFolder, changesetToStore.getId() + ".xml");
                    changesetPathsForCatalog.add(changesetFile.getAbsoluteFile().toURI());
                    String changesetString = convertJDOMDocumentToString(changesetToStore.getChangesetData());
                    BufferedWriter bw = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(changesetFile), StandardCharsets.UTF_8));
                    bw.write(changesetString);
                    bw.close();
                }

                //Now, we generate the catalog file from the changesets.
                generateCatalog(temporaryFolder, changesetPathsForCatalog);

                //Lastly, we add the temporary folder to the list of results.
                results.add(temporaryFolder);
            }
            return results;
        } catch (IOException e) {
            throw new TemporaryStorageException(e);
        }
    }
}