1 package org.apache.archiva.common.utils;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.commons.lang3.StringUtils;
23
24 import java.net.MalformedURLException;
25 import java.net.URI;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28
29
30
31
32
33
34 public class PathUtil
35 {
36 public static String toUrl( String path )
37 {
38
39 if ( path.startsWith( "file:/" ) )
40 {
41 return path;
42 }
43
44 return toUrl( Paths.get( path ) );
45 }
46
47 public static String toUrl( Path file )
48 {
49 try
50 {
51 return file.toUri().toURL().toExternalForm();
52 }
53 catch ( MalformedURLException e )
54 {
55 String pathCorrected = StringUtils.replaceChars( file.toAbsolutePath().toString(), '\\', '/' );
56 if ( pathCorrected.startsWith( "file:/" ) )
57 {
58 return pathCorrected;
59 }
60
61 return "file://" + pathCorrected;
62 }
63 }
64
65
66
67
68
69
70
71
72 public static String getRelative( Path basedir, Path file )
73 {
74 if (basedir.isAbsolute() && !file.isAbsolute()) {
75 return basedir.normalize().relativize(file.toAbsolutePath()).toString();
76 } else if (!basedir.isAbsolute() && file.isAbsolute()) {
77 return basedir.toAbsolutePath().relativize(file.normalize()).toString();
78 } else {
79 return basedir.normalize().relativize(file.normalize()).toString();
80 }
81 }
82
83 public static String getRelative(String basedir, Path file) {
84 return getRelative(Paths.get(basedir), file);
85 }
86
87
88
89
90
91
92
93
94 public static String getRelative( String basedir, String child )
95 {
96
97 return getRelative(basedir, Paths.get(child));
98 }
99
100
101
102
103
104
105
106
107
108 public static Path getPathFromUri( URI uri) {
109 if (uri==null) {
110 return Paths.get("");
111 } else if (uri.getScheme()==null) {
112 return Paths.get(uri.getPath());
113 } else {
114 return Paths.get(uri);
115 }
116 }
117 }