View Javadoc

1   package org.apache.maven.jdeveloper;
2   
3   /* ====================================================================
4    *   Copyright 2001-2004 The Apache Software Foundation.
5    *
6    *   Licensed under the Apache License, Version 2.0 (the "License");
7    *   you may not use this file except in compliance with the License.
8    *   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   */
19   
20  import java.io.File;
21  import java.io.IOException;
22  
23  import jdepend.framework.JavaClass;
24  import jdepend.framework.JavaSourceFileParser;
25  
26  /**
27   * @author Ben Walding
28   *
29   */
30  public class JavaSourceTool {
31      
32      
33      /**
34       * Extracts the package name from the java source file and returns it as
35       * a directory. For example if the file name is :
36       * "e:\tmp\src\main\org\apache\maven\Code.java", and <code>Code.java</code>
37       * is in the <code>org.apache.maven</code> package, this method will
38       * return "org\apache\maven\Code.java" (or "org/apache/maven/Code.java" on
39       * unix).
40       *
41       * @param absoluteFileName the absolute file name to transform
42       * @return the shortened file name matching the class package name.
43       * @throws IOException upon failure to read the java file
44       */
45      public static final String getPackagePath(String absoluteFileName) throws IOException {
46          String shortenedPath;
47  
48          JavaSourceFileParser parser = new JavaSourceFileParser();
49          JavaClass clazz = null;
50  
51          try {
52              clazz = parser.parse(absoluteFileName);
53          } catch (Exception e) {
54              System.out.println("\nError parsing " + absoluteFileName + ": " + e + "\n");
55              return null;
56          }
57  
58          String packageName = clazz.getPackageName();
59  
60          // Handle default packages for which JDepend returns "default"
61          if (packageName.equals("default")) {
62              shortenedPath = clazz.getName() + ".java";
63          } else {
64              shortenedPath =
65                  packageName.replace('.', File.separatorChar) + File.separatorChar + clazz.getName() + ".java";
66          }
67  
68          return shortenedPath;
69      }
70  }