Package org.jvnet.glassfish.comms.deployment.annotations.scanners

Source Code of org.jvnet.glassfish.comms.deployment.annotations.scanners.SarScanner

/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
* Copyright (c) Ericsson AB, 2004-2008. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License").  You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.  If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license."  If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above.  However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.jvnet.glassfish.comms.deployment.annotations.scanners;

import com.sun.enterprise.deployment.WebBundleDescriptor;
import com.sun.enterprise.deployment.annotation.impl.AnnotationUtils;
import com.sun.enterprise.deployment.annotation.impl.WarScanner;
import com.sun.enterprise.deployment.annotation.introspection.ByteScanner;
import com.sun.enterprise.deployment.deploy.shared.FileArchive;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.logging.Level;
import org.jvnet.glassfish.comms.extensions.Extension;


/**
*
* @author lmcpepe a.k.a. PellePedro
* @since 15-Nov-07
*
*/
public class SarScanner extends WarScanner implements ByteScanner {
    private final static String INSTALLATION_ERROR = "Error in installation. Application was assumed to be deployed under '/domains/<domain>/applications'.";

    public SarScanner() {
        setCustomScaner(new SipAnnotationScanner());
    }

    public void initScanRepository(File archiveFile,
        WebBundleDescriptor webBundleDesc) throws IOException {
        initScanRepository(archiveFile, webBundleDesc, null);
    }

    /**
     * This scanner will scan the archiveFile for annotation processing.
     * @param archiveFile
     * @param webBundleDesc
     * @param classLoader
     */
    public void initScanRepository(File archiveFile,
        WebBundleDescriptor webBundleDesc, ClassLoader classLoader)
        throws IOException {
        if (AnnotationUtils.getLogger().isLoggable(Level.FINE)) {
            AnnotationUtils.getLogger().fine("archiveFile is " + archiveFile);
            AnnotationUtils.getLogger().fine("webBundle is " + webBundleDesc);
            AnnotationUtils.getLogger().fine("classLoader is " + classLoader);
        }

        this.archiveFile = archiveFile;       

        if (!archiveFile.isDirectory()) {
            // on client side
            return;
        }

        ArrayList<URL> repositoryUrl = new ArrayList<URL>();

        File webinf = new File(archiveFile, "WEB-INF");
        File classes = new File(webinf, "classes");

        if (classes.exists()) {
            repositoryUrl.add(classes.toURI().toURL());
            addScanDirectory(classes);
        } else {
            repositoryUrl.add(archiveFile.toURI().toURL());
            addScanDirectory(archiveFile);
        }

        File lib = new File(webinf, "lib");

        if (lib.exists()) {
            File[] jarFiles = lib.listFiles(new FileFilter() {
                        public boolean accept(File pathname) {
                            return (pathname.isFile() &&
                            pathname.getAbsolutePath().endsWith(".jar"));
                        }
                    });

            if ((jarFiles != null) && (jarFiles.length > 0)) {
                for (File jarFile : jarFiles) {
                    addJarToClassPath(repositoryUrl, jarFile);
                }
            }
        }

        addManifestClassPath(archiveFile, repositoryUrl);

        URL[] classPath = new URL[repositoryUrl.size()];

        for (int i = 0; i < classPath.length; i++) {
            classPath[i] = repositoryUrl.get(i);
        }

        this.classLoader = new URLClassLoader(classPath,
                classLoader);
    }

    /**
   * Helper that adds the jarFile to the set of urls and adds it as a jar to scan.
   *
   * @param repositoryUrl List to which the jar URL should be added to.
   * @param jarFile The jar file to be added.
   * @throws MalformedURLException
   * @throws IOException
   */
  private void addJarToClassPath(ArrayList<URL> repositoryUrl, File jarFile)
      throws MalformedURLException, IOException {
      repositoryUrl.add(jarFile.toURI().toURL());
      addScanJar(jarFile);
  }

  /**
     * Adding the entries from the Class-Path manifest attribute to
     * the set of urls.
     *
     * @param archiveFile Archive in which the Manifest resides.
     * @param repositoryUrl The set of URLs to be added to.
     * @throws IOException
     */
    private void addManifestClassPath(File archiveFile,
        ArrayList<URL> repositoryUrl) throws IOException {
        String classPath = extractClassPathAttribute(archiveFile);

        if ((classPath != null) && !("".equals(classPath))) {
            File[] folders = findJarFilesFolders(archiveFile);

            if (folders == null) {
                return;
            }

            // Class-Path consists of space separated entries
            // of jars. Each jar is supposed to be relative to
            // the jar archive the Manifest refers to.
            // http://java.sun.com/developer/Books/javaprogramming/JAR/basics/manifest.html
            StringTokenizer tokens = new StringTokenizer(classPath, " ");

            while (tokens.hasMoreTokens()) {
                String jarFileRelative = tokens.nextToken();
                File jarFile = searchInFolders(folders, jarFileRelative);
                if(jarFile!=null){
                  addJarToClassPath(repositoryUrl, jarFile);
                }
                else {
                  warning("The archive '" + jarFileRelative +
                      "' refered by manifest Class-Path attribute in application '" +
                      archiveFile.getName() + "' could not be located");
                }
            }
        }
    }

    /**
   * Exctract Class-Path attribute from Manifest in archive file
   *
   * @param archiveFile
   * @return Class-Path attribute. Null if not present.
   * @throws IOException
   */
  private static String extractClassPathAttribute(File archiveFile) throws IOException {
      FileArchive archive = new FileArchive();
 
      try {
          archive.open(archiveFile.getAbsolutePath());
          Manifest m = archive.getManifest();
          if (m != null) {
              m.getMainAttributes();
              Attributes attrs = m.getMainAttributes();
              return attrs.getValue("Class-Path");
          }
          return null;
      } finally {
          archive.close();
      }
  }

  /**
   * Method that finds the folders, relative to archiveFile, where jar-files are looked for.
   *
   * @param archiveFile
   * @return Set of folders where jar files are searched. Null if an error occured.
   */
  private static File[] findJarFilesFolders(File archiveFile) {
      File[] jarFolders = new File[2];
 
      // We interpret "relative" as having the jar in either the /lib or /domains/<domain>/lib folder.
      File dir = archiveFile;
 
      // Travers up to "/domains/<domain1>/applications
      do {
          dir = dir.getParentFile();
      } while ((dir != null) && !"applications".equals(dir.getName()));
 
      if (dir == null) {
          // Error, never found applications folder
          severe(INSTALLATION_ERROR + " No 'applications' folder");
 
          return null;
      }
 
      // go up one step (/domains/<domain>)
      dir = dir.getParentFile();
 
      if (dir == null) {
          // Error, expected parent folder
          severe(INSTALLATION_ERROR + " No superfolder for 'applications'");
          return null;
      }
 
      // Select /domains/<domain>/lib folder
      jarFolders[0] = new File(dir, "lib");
      if (!jarFolders[0].exists()) {
          severe(INSTALLATION_ERROR + " No '/domains/<domain>/lib' folder");
          return null;
      }
 
      // go up one step (/domains)
      dir = dir.getParentFile();
      if (dir == null) {
          // Error, expected parent folder
          severe(INSTALLATION_ERROR + " No superfolder for '<domain>'");
          return null;
      }
 
      // go up one step (/)
      dir = dir.getParentFile();
 
      if (dir == null) {
          // Error, expected parent folder
          severe(INSTALLATION_ERROR + " No superfolder for 'domains'");
          return null;
      }
 
      // Select /lib folder
      jarFolders[1] = new File(dir, "lib");
      if (!jarFolders[1].exists()) {
          severe(INSTALLATION_ERROR +
              " No '/lib' folder");
          return null;
      }
 
      return jarFolders;
  }

  /**
     * Searches a set of folders for a file.
     *
     * @param folders Set of folders to search
     * @param fileRelative Relative file name.
     * @return File object for first match. Null if not found.
     */
  private static File searchInFolders(File[] folders, String fileRelative)  {
    for (File folder : folders) {
        File jarFile = new File(folder, fileRelative);

        if (jarFile.exists()) {
            return jarFile;
        }
    }
    return null;
  }

  /**
   * Shorthand for calling warning on logger.
   *
   * @param reason
   */
  private static void warning(String reason) {
      if (AnnotationUtils.getLogger().isLoggable(Level.WARNING)) {
          AnnotationUtils.getLogger().warning(reason);
      }
  }

  /**
   * Shorthand for calling severe on logger.
   *
   * @param reason
   */
  private static void severe(String reason) {
      if (AnnotationUtils.getLogger().isLoggable(Level.SEVERE)) {
          AnnotationUtils.getLogger().severe(reason);
      }
  }

    public boolean scan(byte[] arg0) {
        return Extension.getInstance().containsAnnotation(arg0);
    }
}
TOP

Related Classes of org.jvnet.glassfish.comms.deployment.annotations.scanners.SarScanner

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.