All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jboss.maven.plugins.deploy.JBossDeployMojo Maven / Gradle / Ivy

package org.jboss.maven.plugins.deploy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.License;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.xml.sax.SAXException;

/**
 * Maven plugin for deploying to jboss repository.  By default
 * it will bind to the deploy phase.
 * 
 * @phase deploy
 * @goal jboss-deploy
 * 
 */
public class JBossDeployMojo extends AbstractMojo
{

   private static String fileSep = System.getProperty("file.separator");

   /**
    * The Maven Project Object
    *
    * @parameter expression="${project}"
    * @required
    * @readonly
    */
   protected MavenProject project;

   /**
    * Source control information.
    * @parameter expression="${project.scm}"
    * @readonly
    */
   private org.apache.maven.model.Scm scm;

   /**
    * License information from the pom.xml.
    * @parameter expression="${project.licenses}"
    * @required
    * @readonly
    */
   private List pomLicenses;

   /**
    * Name of license to add to component-info.xml.  If no value is specified,
    * then the first license from the pom.xml will be used.
    * @parameter
    */
   private String license;

   /**
    * Boolean that determines if the artifact version should be included in the
    * deployed jar files.
    * @parameter default-value="false"
    */
   private boolean removeArtifactVersion;

   /**
    * Maven project properties.
    *
    * @parameter expression="${project.properties}"
    * @required
    * @readonly
    */
   protected Properties projectProperties;

   /**
    * This is the location that the jboss repository (non-maven) files will be copied to.
    * @parameter expression="${jbossDeployRoot}"
    * @required
    */
   private String jbossDeployRoot;

   /**
    * If set to true, this will tell the plugin to generate a listing of imports based on the
    * project dependencies.  Defaults to false;
    * @parameter
    */
   private boolean generateImports;

   /**
    * This is the map of components that this project depends on.  If generateImports is set
    * to true, the generated imports will be appended to the imports specified here.
    * @parameter
    */
   private Map imports;

   /**
    * This allows the maven groupId to be overridden.  For example, the pom groupId
    * might be "org.jboss", but the jboss repository groupId should just be "jboss".
    * @parameter
    */
   private String groupId;

   /**
    * This is the list of artifacts exported from this project.
    * By default the project artifact will be included in this list.
    * If there is no project artifact, this plugin will look for an attached
    * artifact that matches the project name, and attempt to attach it.
    * The list of exports can manually be set with the following configuration.
    * 
    *   file1.jar
    *   file2.jar
    * 
    * 
    * @parameter
    */
   private Set exports;

   /**
    * Main execution path of the plugin.  Generates component-info.xml, and copies jar files to repository location.
    */
   public void execute() throws MojoExecutionException
   {
      this.getLog().debug("Executing JBoss deploy plugin");

      // Check that there is at least one artifact to deploy
      if ((project.getArtifact() == null || project.getArtifact().getFile() == null)
            && project.getAttachedArtifacts().size() == 0)
      {
         this.getLog().info("No artifacts to deploy for project:" + project.getName());
         return;
      }

      if (exports == null) {
         exports = new HashSet();
      }
      if (groupId == null || groupId.equals(""))
      {
         groupId = project.getGroupId();
      }
      String groupIdPath = groupId.replace('.', '/');
      
      // Initialize some local variables
      File deployToDir = new File(jbossDeployRoot + fileSep + groupIdPath + fileSep
            + project.getArtifactId() + fileSep + project.getVersion() + fileSep);
      File deployToLibDir = new File(deployToDir.getAbsolutePath() + fileSep + "lib" + fileSep);

      // Load template file
      InputStream templateInputStream = this.getClass().getResourceAsStream("component-info-template.txt");

      if (templateInputStream == null)
      {
         this.getLog().error("Unable to load template file");
         return;
      }

      StringBuffer compInfoTemplate = new StringBuffer();

      try
      {
         compInfoTemplate.append(IOUtils.toString(templateInputStream));
      }
      catch (IOException ioe)
      {
         this.getLog().error("Unable to load component info template.");
         this.getLog().error(ioe.toString());
         throw new MojoExecutionException(ioe.getMessage());
      }

      // Evaluate the place holders in the template
      String componentId = groupIdPath + "/" + project.getArtifactId();
      evaluateVariable(compInfoTemplate, "project.name", componentId + "-component-info");
      evaluateVariable(compInfoTemplate, "component.id", componentId);
      evaluateVariable(compInfoTemplate, "project.version", project.getVersion());
      if (license != null && ( ! license.equals(""))) 
      {
         evaluateVariable(compInfoTemplate, "project.license", license);
      }
      else if (pomLicenses.size() == 0)
      {
         getLog().warn("No license specified.  Default lgpl license will be used.");
         evaluateVariable(compInfoTemplate, "project.license", "lgpl");
      }
      else
      {
         License firstLicense = (License) pomLicenses.get(0);
         evaluateVariable(compInfoTemplate, "project.license", firstLicense.getName());
      }
      
      if (project.getDescription() == null || project.getDescription().equals(""))
      {
         project.setDescription(project.getId());
      }
      evaluateVariable(compInfoTemplate, "project.description", project.getDescription());

      if (scm == null || scm.getConnection() == null)
      {
         evaluateVariable(compInfoTemplate, "project.scm", "");
      }
      else
      {
         String scmConnStr = scm.getConnection().replaceFirst("scm:", "");
         evaluateVariable(compInfoTemplate, "project.scm", "scm=\"" + scmConnStr + "\"");
      }

      // Build list of artifacts, copy them to the lib directory, and add them to component-info.xml
      HashSet artifactSet = new HashSet();
      Artifact projectArtifact = project.getArtifact();
      if (projectArtifact != null && projectArtifact.getFile() != null)
      {
         String deployFileName = generateOutputFileName(projectArtifact, removeArtifactVersion);
         artifactSet.add("    \n");
         try
         {
            this.getLog().debug("Deploying file://" + deployToLibDir + fileSep + deployFileName);
            FileUtils.copyFile(projectArtifact.getFile(), new File(deployToLibDir, deployFileName));
         }
         catch (IOException ioe)
         {
            throw new MojoExecutionException("Problem copying artifact: " + ioe.getMessage());
         }
      }

      // Add the attached (non-default) artifacts
      List list = project.getAttachedArtifacts();
      this.getLog().debug("Number of attached artifacts: " + list.size());
      
      for (Object artifactObj : list)
      {
         Artifact artifact = (Artifact) artifactObj;
         this.getLog().debug("Attaching artifact: " + artifact.getArtifactId());
         
         String classifierStr = artifact.getClassifier();
         if (classifierStr == null) {
            classifierStr = "";
            // If the classifier is null and the artifactId matches the project artifactId
            // it must be a composite project, so we add the artifact to the
            // list of exports.
            if (artifact.getArtifactId().equals(project.getArtifactId())) {
               exports.add(artifact.getArtifactId() + "." + artifact.getType());
            }
            if (project.getArtifact() != null) {
               getLog().warn("Attached artifact with same classifier as default artifact." + "\n"
                     + "Attached artifact: " + artifact.getFile() + "\n"
                     + "Project artifact: " + project.getArtifact().getFile() + "\n"
                     + "This could be caused by an assembly descriptor with no id.");
            }
         }
         String deployFileName = generateOutputFileName(artifact, removeArtifactVersion);
         String artifactLine = "    \n";
         
         // Check for duplicates
         if (artifactSet.contains(artifactLine)) {
            this.getLog().warn(
                  "Duplicate attached artifact found: " + artifact.getFile().getName()
                        + ".jar");
         }
         artifactSet.add(artifactLine);
         
         try
         {
            this.getLog().debug("Deploying file://" + deployToLibDir + fileSep + deployFileName);
            File deploytoFile = new File(deployToLibDir, deployFileName);
            FileUtils.copyFile(artifact.getFile(), deploytoFile);
         }
         catch (IOException ioe)
         {
            throw new MojoExecutionException("Problem copying artifact: " + ioe.getMessage());
         }
      }

      StringBuffer artifacts = new StringBuffer();
      for (String line : artifactSet)
      {
         artifacts.append(line);
      }
      evaluateVariable(compInfoTemplate, "artifacts", artifacts.toString());

      // Create and set list of includes for export
      StringBuffer exportsString = new StringBuffer();
      if (project.getArtifact().getFile() != null)
      {
         exports.add(generateOutputFileName(project.getArtifact(), removeArtifactVersion));
      }
      for (Object export : exports)
      {
         exportsString.append("      \n");
      }
      evaluateVariable(compInfoTemplate, "includes", exportsString.toString());

      // Generate the list of imports
      evaluateVariable(compInfoTemplate, "imports", generateImportsString());

      // Write the component info file
      File compInfoFile = new File(deployToDir + fileSep + "component-info.xml");
      try
      {
         if (!deployToDir.exists())
         {
            deployToDir.mkdirs();
         }
         FileWriter fw = new FileWriter(compInfoFile);
         this.getLog().info("Deploying file: " + compInfoFile.getCanonicalPath());
         fw.write(compInfoTemplate.toString());
         fw.close();
      }
      catch (IOException ioe)
      {
         this.getLog().error(ioe);
      }

      CompInfoVerifier verifier = new CompInfoVerifier();
      try
      {
         verifier.verifyCompInfo(new FileInputStream(compInfoFile));
      }
      catch (SAXException e)
      {
         this.getLog().warn(e);
      }
      catch (FileNotFoundException fnfe)
      {
         fnfe.printStackTrace();
      }
   }

   private String generateOutputFileName(Artifact artifact, boolean removeArtifactVersion)
   {
      String deployFileName = artifact.getFile().getName();
      if (removeArtifactVersion)
      {
         if ( deployFileName.contains( artifact.getBaseVersion() ) )
         {
            deployFileName = deployFileName.replace( ("-" + artifact.getBaseVersion()), "" );
         }
      }
      return deployFileName;
      
   }
   
   /** 
    * Creates the list of imports to include in the component-info.xml
    */
   private String generateImportsString()
   {
      StringBuffer importsString = new StringBuffer();
      if (imports != null)
      {
         Set componentNames = imports.keySet();
         for (Object component : componentNames)
         {
            importsString.append("    \n");
            String componentVersions = imports.get(component).toString();
            String [] versions = componentVersions.split(",");
            for(String version : versions)
            {
               importsString.append("      \n");
            }
            importsString.append("    \n");
         }
      }
      if (this.generateImports)
      {
         List dependencies = project.getDependencies();
         for (Object obj : dependencies)
         {
            Dependency dep = (Dependency) obj;
            if (dep.getScope() == null || !dep.getScope().equals("test")) {
               importsString.append("    \n");
               importsString.append("      \n");
               importsString.append("    \n");
            }
         }
      }
      return importsString.toString();
   }

   
   
   /**
    * Replace all instances of var with value in the given buffer.
    * For example if var is "project.name", this method will search
    * the buffer for "${project.name}" and replace it with the value
    * provided.
    * 
    * @param buffer The buffer to be modified
    * @param var The name of the variable to be evaluated.
    * @param value The replacement string.
    */
   public void evaluateVariable(StringBuffer buffer, String var, String value)
   {
      int start = 0;
      while ((start = buffer.indexOf("${" + var + "}")) != -1)
      {
         int end = start + ("${" + var + "}").length();
         buffer.replace(start, end, value);
      }
   }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy