package org.apache.maven.jdeveloper;

/* ====================================================================
 *   Copyright 2001-2004 The Apache Software Foundation.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 * ====================================================================
 */
 
import java.io.File;
import java.io.IOException;

import jdepend.framework.JavaClass;
import jdepend.framework.JavaSourceFileParser;

/**
 * @author Ben Walding
 *
 */
public class JavaSourceTool {
    
    
    /**
     * Extracts the package name from the java source file and returns it as
     * a directory. For example if the file name is :
     * "e:\tmp\src\main\org\apache\maven\Code.java", and <code>Code.java</code>
     * is in the <code>org.apache.maven</code> package, this method will
     * return "org\apache\maven\Code.java" (or "org/apache/maven/Code.java" on
     * unix).
     *
     * @param absoluteFileName the absolute file name to transform
     * @return the shortened file name matching the class package name.
     * @throws IOException upon failure to read the java file
     */
    public static final String getPackagePath(String absoluteFileName) throws IOException {
        String shortenedPath;

        JavaSourceFileParser parser = new JavaSourceFileParser();
        JavaClass clazz = null;

        try {
            clazz = parser.parse(absoluteFileName);
        } catch (Exception e) {
            System.out.println("\nError parsing " + absoluteFileName + ": " + e + "\n");
            return null;
        }

        String packageName = clazz.getPackageName();

        // Handle default packages for which JDepend returns "default"
        if (packageName.equals("default")) {
            shortenedPath = clazz.getName() + ".java";
        } else {
            shortenedPath =
                packageName.replace('.', File.separatorChar) + File.separatorChar + clazz.getName() + ".java";
        }

        return shortenedPath;
    }
}
