org.clinigrid.capillary.inspector.Inspector.java Source code

Java tutorial

Introduction

Here is the source code for org.clinigrid.capillary.inspector.Inspector.java

Source

/*******************************************************************************
 * Inspector.java
 * 
 * Copyright (c) 2011 Clinigrid.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * Contributors:
 *     Didier Villevalois - initial API and implementation
 ******************************************************************************/
package org.clinigrid.capillary.inspector;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarFile;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.clinigrid.capillary.inspector.hibernate.HibernateModelContributor;
import org.clinigrid.capillary.inspector.model.DefaultModelManager;
import org.clinigrid.capillary.inspector.model.IModelManager;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

/**
 * The Inspector class is the executable class.
 * 
 * @author <a href="mailto:dvillevalois@clinigrid.com">Didier Villevalois</a>
 */
public class Inspector {

    public Inspector() {
        modelContributors = new ArrayList<IModelContributor>();
        initResourceSet();
    }

    private boolean verbose;
    private String packagePrefix;
    private String uriPrefix;
    private String[] externalModelURIs;
    private String archiveFilePath;
    private String[] dependencyPaths;
    private List<IModelContributor> modelContributors;
    private String outputFilename;

    private ResourceSet resourceSet;

    private void initResourceSet() {
        resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore",
                new XMIResourceFactoryImpl());
    }

    /**
     * Tests whether this inspector is in verbose mode.
     * @return <code>true</code> if this inspector is in verbose mode, <code>false</code> otherwise
     */
    public boolean isVerbose() {
        return verbose;
    }

    /**
     * Sets the verbose mode of this inspector.
     * @param verbose <code>true</code> to set this inspector in verbose mode, <code>false</code> otherwise
     */
    public void setVerbose(boolean verbose) {
        this.verbose = verbose;
    }

    public String getPackagePrefix() {
        return packagePrefix;
    }

    public void setPackagePrefix(String packagePrefix) {
        this.packagePrefix = packagePrefix;
    }

    public String getUriPrefix() {
        return uriPrefix;
    }

    public void setUriPrefix(String uriPrefix) {
        this.uriPrefix = uriPrefix;
    }

    /**
     * Returns the external model URIs.
     * @return the external model URIs
     */
    public String[] getExternalModelURIs() {
        return externalModelURIs;
    }

    /**
     * Sets the external model URIs.
     * @param externalModelURIs the external model URIs to set
     */
    public void setExternalModelURIs(String[] externalModelURIs) {
        this.externalModelURIs = externalModelURIs;
    }

    /**
     * Returns the archive file path.
     * @return the archive file path
     */
    public String getArchiveFilePath() {
        return archiveFilePath;
    }

    /**
     * Sets the archive file path.
     * @param archiveFilePath the archive file path to set
     */
    public void setArchiveFilePath(String archiveFilePath) {
        this.archiveFilePath = archiveFilePath;
    }

    /**
     * Returns the dependency paths.
     * @return the dependency paths
     */
    public String[] getDependencyPaths() {
        return dependencyPaths;
    }

    /**
     * Sets the dependency paths.
     * @param dependencyPaths the dependency paths to set
     */
    public void setDependencyPaths(String[] dependencyPaths) {
        this.dependencyPaths = dependencyPaths;
    }

    /**
     * Adds a model contributor.
     * @param modelContributor the model contributor to add
     */
    public void addModelContributor(IModelContributor modelContributor) {
        modelContributors.add(modelContributor);
    }

    /**
     * Returns the output file name.
     * @return the output file name
     */
    public String getOutputFilename() {
        return outputFilename;
    }

    /**
     * Sets the output file name.
     * @param outputFilename the output file name to set
     */
    public void setOutputFilename(String outputFilename) {
        this.outputFilename = outputFilename;
    }

    /**
     * The main method.
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        CommandLine cl = parse(args);
        Inspector inspector = new Inspector();

        String[] externalModelURIs = cl.getOptionValues('i');
        inspector.setExternalModelURIs(externalModelURIs != null ? externalModelURIs : new String[0]);

        String[] dependencyPaths = cl.getOptionValues('d');
        inspector.setDependencyPaths(dependencyPaths != null ? dependencyPaths : new String[0]);

        inspector.setArchiveFilePath(cl.getOptionValue('j'));
        inspector.setOutputFilename(cl.getOptionValue('o'));

        inspector.addModelContributor(new HibernateModelContributor());

        inspector.setVerbose(cl.hasOption('v'));
        try {
            inspector.run();
        } catch (InspectorException e) {
            inspector.exit(e.getMessage(), e);
        }
    }

    public void run() throws InspectorException {
        URI outputURI = URI.createFileURI(outputFilename);
        Resource outputResource = resourceSet.createResource(outputURI);

        IModelManager modelManager = new DefaultModelManager(outputResource, packagePrefix, uriPrefix);

        for (String externalModelURIString : externalModelURIs) {
            URI externalModelURI = URI.createFileURI(externalModelURIString);
            Resource externalModelResource = resourceSet.createResource(externalModelURI);
            try {
                externalModelResource.load(Collections.emptyMap());
            } catch (IOException e) {
                throw new InspectorException("Failed to read external model '" + externalModelURIString + "'", e);
            }
            modelManager.importExternalResource(externalModelResource);
        }

        DefaultInputCrawler inputCrawler;
        try {
            File file = new File(archiveFilePath);
            if (!file.exists()) {
                throw new InspectorException("File doesn't exist '" + archiveFilePath + "'");
            }

            if (archiveFilePath.endsWith(".zip") | archiveFilePath.endsWith(".jar")
                    | archiveFilePath.endsWith(".war")) {
                JarFile jarFile = new JarFile(file);
                inputCrawler = new DefaultInputCrawler(jarFile);
            } else {
                throw new InspectorException("Unknown archive file format '" + archiveFilePath + "'");
            }
        } catch (IOException e) {
            throw new InspectorException("Failed to read JAR file '" + archiveFilePath + "'", e);
        }

        System.out.printf("[Inspector] Loaded archive '%s'\n", archiveFilePath);
        System.out.flush();

        for (String dependencyPath : dependencyPaths) {
            try {
                File file = new File(dependencyPath);
                if (!file.exists()) {
                    throw new InspectorException("File doesn't exist '" + dependencyPath + "'");
                }

                JarFile jarFile = new JarFile(file);
                inputCrawler.addDependency(jarFile);
            } catch (IOException e) {
                throw new InspectorException("Failed to read JAR file '" + dependencyPath + "'", e);
            }
        }

        DefaultContributionReporter reporter = new DefaultContributionReporter();
        reporter.setVerbose(verbose);

        for (IModelContributor modelContributor : modelContributors) {
            reporter.beginModelContributor(modelContributor);
            try {
                modelContributor.contributeToModel(modelManager, inputCrawler, reporter);
            } catch (ContributorException e) {
                throw new InspectorException("Contributor failed '" + modelContributor.getName() + "'", e);
            } catch (RuntimeException e) {
                throw new InspectorException("Contributor failed '" + modelContributor.getName() + "'", e);
            }
            reporter.endModelContributor(modelContributor);
        }

        ((DefaultModelManager) modelManager).truncateRoot(uriPrefix);

        try {
            outputResource.save(null);
        } catch (IOException e) {
            throw new InspectorException("Failed to save output file", e);
        }
    }

    private static final String USAGE = "capillary-inspector [Options]";
    private static final String DESCRIPTION = "Scans Hibernate Mapping files and produce an Ecore model.\n"
            + "Options:";
    private static final String EXAMPLE = "\nExample: capillary-inspector -s ./ -p com.example -o output.ecore";

    private static CommandLine parse(String[] args) {
        Options opts = new Options();

        OptionBuilder.withArgName("external-model-uris");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("set the paths of the external model URIs to import (semi-colon separated)");
        opts.addOption(OptionBuilder.create("i"));

        OptionBuilder.withArgName("jar-file-path");
        OptionBuilder.hasArg();
        OptionBuilder
                .withDescription("set the path of the archive file (jar or war) to scan (semi-colon separated)");
        opts.addOption(OptionBuilder.create("j"));

        OptionBuilder.withArgName("dependency-jar");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("set the paths of the dependency archives (semi-colon separated)");
        opts.addOption(OptionBuilder.create("d"));

        OptionBuilder.withArgName("output-file.ecore");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("set the output ecore file name");
        opts.addOption(OptionBuilder.create("o"));

        opts.addOption("v", "verbose", false, "set the verbose mode");

        opts.addOption("h", "help", false, "print this message");
        opts.addOption("V", "version", false, "print the version information and exit");
        CommandLine cl = null;
        try {
            cl = new GnuParser().parse(opts, args);
        } catch (ParseException e) {
            exit("dcmmwl: " + e.getMessage());
            throw new RuntimeException("unreachable");
        }
        if (cl.hasOption('V')) {
            Package p = Inspector.class.getPackage();
            System.out.println("Capillary v" + p.getImplementationVersion());
            System.exit(0);
        }
        if (cl.hasOption('h') /*|| cl.getArgList().size() != 1*/) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(USAGE, DESCRIPTION, opts, EXAMPLE);
            System.exit(0);
        }

        return cl;
    }

    private void exit(String message, Exception e) {
        e.printStackTrace();
        exit(message + ": " + e.getMessage());
    }

    private static void exit(String message) {
        System.err.println(message);
        System.err.println("Try 'capillary-inspector -h' for more information.");
        System.exit(1);
    }
}