1 package org.apache.archiva.common.utils;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.commons.lang.StringUtils;
25 import java.net.MalformedURLException;
28 * PathUtil - simple utility methods for path manipulation.
34 public static String toUrl( String path )
36 // Is our work already done for us?
37 if ( path.startsWith( "file:/" ) )
42 return toUrl( new File( path ) );
45 public static String toUrl( File file )
49 return file.toURL().toExternalForm();
51 catch ( MalformedURLException e )
53 String pathCorrected = StringUtils.replaceChars( file.getAbsolutePath(), '\\', '/' );
54 if ( pathCorrected.startsWith( "file:/" ) )
59 return "file://" + pathCorrected;
64 * Given a basedir and a child file, return the relative path to the child.
66 * @param basedir the basedir.
67 * @param file the file to get the relative path for.
68 * @return the relative path to the child. (NOTE: this path will NOT start with a {@link File#separator} character)
70 public static String getRelative( String basedir, File file )
72 return getRelative( basedir, file.getAbsolutePath() );
76 * Given a basedir and a child file, return the relative path to the child.
78 * @param basedir the basedir.
79 * @param child the child path (can be a full path)
80 * @return the relative path to the child. (NOTE: this path will NOT start with a {@link File#separator} character)
82 public static String getRelative( String basedir, String child )
84 if ( basedir.endsWith( "/" ) || basedir.endsWith( "\\" ) )
86 basedir = basedir.substring( 0, basedir.length() - 1 );
89 if ( child.startsWith( basedir ) )
92 return child.substring( basedir.length() + 1 );
95 String absoluteBasedir = new File( basedir ).getAbsolutePath();
96 if ( child.startsWith( absoluteBasedir ) )
98 // resolved basedir solution.
99 return child.substring( absoluteBasedir.length() + 1 );
102 // File is not within basedir.
103 throw new IllegalStateException(
104 "Unable to obtain relative path of file " + child + ", it is not within basedir " + basedir + "." );