View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.util;
19  
20  import static org.junit.Assert.assertTrue;
21  
22  import java.io.BufferedWriter;
23  import java.io.File;
24  import java.io.FileInputStream;
25  import java.io.FileOutputStream;
26  import java.io.FileWriter;
27  import java.nio.charset.StandardCharsets;
28  import java.nio.file.Files;
29  import java.util.ArrayList;
30  import java.util.List;
31  import java.util.jar.JarEntry;
32  import java.util.jar.JarOutputStream;
33  import java.util.jar.Manifest;
34  
35  import javax.tools.JavaCompiler;
36  import javax.tools.JavaFileObject;
37  import javax.tools.StandardJavaFileManager;
38  import javax.tools.ToolProvider;
39  
40  import org.apache.commons.logging.Log;
41  import org.apache.commons.logging.LogFactory;
42  import org.apache.hadoop.conf.Configuration;
43  import org.apache.hadoop.fs.Path;
44  
45  /**
46   * Some utilities to help class loader testing
47   */
48  public class ClassLoaderTestHelper {
49    private static final Log LOG = LogFactory.getLog(ClassLoaderTestHelper.class);
50  
51    private static final int BUFFER_SIZE = 4096;
52  
53    /**
54     * Jar a list of files into a jar archive.
55     *
56     * @param archiveFile the target jar archive
57     * @param tobeJared a list of files to be jared
58     * @return true if a jar archive is build, false otherwise
59     */
60    private static boolean createJarArchive(File archiveFile, File[] tobeJared) {
61      try {
62        byte buffer[] = new byte[BUFFER_SIZE];
63        // Open archive file
64        FileOutputStream stream = new FileOutputStream(archiveFile);
65        JarOutputStream out = new JarOutputStream(stream, new Manifest());
66  
67        for (int i = 0; i < tobeJared.length; i++) {
68          if (tobeJared[i] == null || !tobeJared[i].exists()
69              || tobeJared[i].isDirectory()) {
70            continue;
71          }
72  
73          // Add archive entry
74          JarEntry jarAdd = new JarEntry(tobeJared[i].getName());
75          jarAdd.setTime(tobeJared[i].lastModified());
76          out.putNextEntry(jarAdd);
77  
78          // Write file to archive
79          FileInputStream in = new FileInputStream(tobeJared[i]);
80          while (true) {
81            int nRead = in.read(buffer, 0, buffer.length);
82            if (nRead <= 0)
83              break;
84            out.write(buffer, 0, nRead);
85          }
86          in.close();
87        }
88        out.close();
89        stream.close();
90        LOG.info("Adding classes to jar file completed");
91        return true;
92      } catch (Exception ex) {
93        LOG.error("Error: " + ex.getMessage());
94        return false;
95      }
96    }
97  
98    /**
99     * Create a test jar for testing purpose for a given class
100    * name with specified code string: save the class to a file,
101    * compile it, and jar it up. If the code string passed in is
102    * null, a bare empty class will be created and used.
103    *
104    * @param testDir the folder under which to store the test class and jar
105    * @param className the test class name
106    * @param code the optional test class code, which can be null.
107    * If null, a bare empty class will be used
108    * @return the test jar file generated
109    */
110   public static File buildJar(String testDir,
111       String className, String code) throws Exception {
112     return buildJar(testDir, className, code, testDir);
113   }
114 
115   /**
116    * Create a test jar for testing purpose for a given class
117    * name with specified code string.
118    *
119    * @param testDir the folder under which to store the test class
120    * @param className the test class name
121    * @param code the optional test class code, which can be null.
122    * If null, an empty class will be used
123    * @param folder the folder under which to store the generated jar
124    * @return the test jar file generated
125    */
126   public static File buildJar(String testDir,
127       String className, String code, String folder) throws Exception {
128     String javaCode = code != null ? code : "public class " + className + " {}";
129     Path srcDir = new Path(testDir, "src");
130     File srcDirPath = new File(srcDir.toString());
131     srcDirPath.mkdirs();
132     File sourceCodeFile = new File(srcDir.toString(), className + ".java");
133     BufferedWriter bw = Files.newBufferedWriter(sourceCodeFile.toPath(), StandardCharsets.UTF_8);
134     bw.write(javaCode);
135     bw.close();
136 
137     // compile it by JavaCompiler
138     JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
139     ArrayList<String> srcFileNames = new ArrayList<String>();
140     srcFileNames.add(sourceCodeFile.toString());
141     StandardJavaFileManager fm = compiler.getStandardFileManager(null, null,
142       null);
143     Iterable<? extends JavaFileObject> cu =
144       fm.getJavaFileObjects(sourceCodeFile);
145     List<String> options = new ArrayList<String>();
146     options.add("-classpath");
147     // only add hbase classes to classpath. This is a little bit tricky: assume
148     // the classpath is {hbaseSrc}/target/classes.
149     String currentDir = new File(".").getAbsolutePath();
150     String classpath = currentDir + File.separator + "target"+ File.separator
151       + "classes" + System.getProperty("path.separator")
152       + System.getProperty("java.class.path") + System.getProperty("path.separator")
153       + System.getProperty("surefire.test.class.path");
154 
155     options.add(classpath);
156     LOG.debug("Setting classpath to: " + classpath);
157 
158     JavaCompiler.CompilationTask task = compiler.getTask(null, fm, null,
159       options, null, cu);
160     assertTrue("Compile file " + sourceCodeFile + " failed.", task.call());
161 
162     // build a jar file by the classes files
163     String jarFileName = className + ".jar";
164     File jarFile = new File(folder, jarFileName);
165     jarFile.getParentFile().mkdirs();
166     if (!createJarArchive(jarFile,
167         new File[]{new File(srcDir.toString(), className + ".class")})){
168       assertTrue("Build jar file failed.", false);
169     }
170     return jarFile;
171   }
172 
173   /**
174    * Add a list of jar files to another jar file under a specific folder.
175    * It is used to generated coprocessor jar files which can be loaded by
176    * the coprocessor class loader.  It is for testing usage only so we
177    * don't be so careful about stream closing in case any exception.
178    *
179    * @param targetJar the target jar file
180    * @param libPrefix the folder where to put inner jar files
181    * @param srcJars the source inner jar files to be added
182    * @throws Exception if anything doesn't work as expected
183    */
184   public static void addJarFilesToJar(File targetJar,
185       String libPrefix, File... srcJars) throws Exception {
186     FileOutputStream stream = new FileOutputStream(targetJar);
187     JarOutputStream out = new JarOutputStream(stream, new Manifest());
188     byte buffer[] = new byte[BUFFER_SIZE];
189 
190     for (File jarFile: srcJars) {
191       // Add archive entry
192       JarEntry jarAdd = new JarEntry(libPrefix + jarFile.getName());
193       jarAdd.setTime(jarFile.lastModified());
194       out.putNextEntry(jarAdd);
195 
196       // Write file to archive
197       FileInputStream in = new FileInputStream(jarFile);
198       while (true) {
199         int nRead = in.read(buffer, 0, buffer.length);
200         if (nRead <= 0)
201           break;
202         out.write(buffer, 0, nRead);
203       }
204       in.close();
205     }
206     out.close();
207     stream.close();
208     LOG.info("Adding jar file to outer jar file completed");
209   }
210 
211   static String localDirPath(Configuration conf) {
212     return conf.get(ClassLoaderBase.LOCAL_DIR_KEY)
213       + File.separator + "jars" + File.separator;
214   }
215 
216 }