001    package org.apache.maven.configuration;
002    
003    /*
004     * Licensed to the Apache Software Foundation (ASF) under one
005     * or more contributor license agreements.  See the NOTICE file
006     * distributed with this work for additional information
007     * regarding copyright ownership.  The ASF licenses this file
008     * to you under the Apache License, Version 2.0 (the
009     * "License"); you may not use this file except in compliance
010     * with the License.  You may obtain a copy of the License at
011     *
012     *   http://www.apache.org/licenses/LICENSE-2.0
013     *
014     * Unless required by applicable law or agreed to in writing,
015     * software distributed under the License is distributed on an
016     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017     * KIND, either express or implied.  See the License for the
018     * specific language governing permissions and limitations
019     * under the License.
020     */
021    
022    import java.io.File;
023    
024    /**
025     * A path translator that resolves relative paths against a specific base directory.
026     * 
027     * @author Benjamin Bentmann
028     */
029    public class BasedirBeanConfigurationPathTranslator
030        implements BeanConfigurationPathTranslator
031    {
032    
033        private final File basedir;
034    
035        /**
036         * Creates a new path translator using the specified base directory.
037         * 
038         * @param basedir The base directory to resolve relative paths against, may be {@code null} to disable path
039         *            translation.
040         */
041        public BasedirBeanConfigurationPathTranslator( File basedir )
042        {
043            this.basedir = basedir;
044        }
045    
046        public File translatePath( File path )
047        {
048            File result = path;
049    
050            if ( path != null && basedir != null )
051            {
052                if ( path.isAbsolute() )
053                {
054                    // path is already absolute, we're done
055                }
056                else if ( path.getPath().startsWith( File.separator ) )
057                {
058                    // drive-relative Windows path, don't align with base dir but with drive root
059                    result = path.getAbsoluteFile();
060                }
061                else
062                {
063                    // an ordinary relative path, align with base dir
064                    result = new File( new File( basedir, path.getPath() ).toURI().normalize() ).getAbsoluteFile();
065                }
066            }
067    
068            return result;
069        }
070    
071    }