View Javadoc
1   package org.djunits.generator;
2   
3   import java.io.File;
4   import java.io.IOException;
5   import java.io.InputStream;
6   import java.net.Authenticator;
7   import java.net.MalformedURLException;
8   import java.net.PasswordAuthentication;
9   import java.net.URL;
10  
11  /**
12   * The URLResource class helps to resolve a file location in a project, JAR, or folder. The static methods return a URL of the
13   * file location that was found, or null in case it was not found. This class originates from the DSOL simulation project.
14   * <p>
15   * Copyright (c) 2002-2022 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved.<br>
16   * BSD-style license. See <a href="https://djunits.org/docs/license.html">DJUNITS License</a>.
17   * </p>
18   * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a>
19   */
20  public final class URLResource
21  {
22      /**
23       * constructs a new URLResource.
24       */
25      private URLResource()
26      {
27          // unreachable code
28      }
29  
30      /**
31       * Resolves a resource for name.
32       * @param name String; the name to search for
33       * @return the resolved URL
34       */
35      public static URL getResource(final String name)
36      {
37          try
38          {
39              File file = new File(name);
40  
41              if (name.startsWith("/"))
42              {
43                  URL url = URLResource.class.getResource(name);
44                  if (url != null)
45                  {
46                      return url;
47                  }
48                  url = Thread.currentThread().getContextClassLoader().getResource(name.substring(1));
49                  if (url != null)
50                  {
51                      return url;
52                  }
53                  if (file.exists())
54                  {
55                      return new URL("file:" + name);
56                  }
57              }
58              else if (name.startsWith("\\") || name.contains("\\")) // added the second part
59              {
60                  if (file.exists())
61                  {
62                      return new URL("file:" + name);
63                  }
64              }
65              else if (file.exists())
66              {
67                  return new URL("file:" + name);
68              }
69              else
70              {
71                  if (name.indexOf("@") == -1)
72                  {
73                      return new URL(name);
74                  }
75                  // we need authentication
76                  String temp = name.substring(name.indexOf("//") + 2);
77                  String userName = temp.substring(0, temp.indexOf(":"));
78                  String password = temp.substring(temp.indexOf(":") + 1);
79                  password = password.substring(0, password.indexOf("@"));
80                  String url = name.substring(0, name.indexOf("//") + 2);
81                  url = url + name.substring(name.indexOf("@") + 1);
82                  Authenticator.setDefault(new PasswordAuthenticator(userName, password));
83                  return new URL(url);
84              }
85          }
86          catch (Exception exception)
87          {
88              exception = null;
89              // We neglect exceptions since we return null
90          }
91          return null;
92      }
93  
94      /**
95       * Resolves a resource for name. For relative names, base is used to resolve to an absolute name. If name is absolute, base
96       * is ignored.
97       * @param name String; the name to search for
98       * @param base String; the base for relative paths
99       * @return the resolved URL
100      */
101     public static URL getResource(final String name, final String base)
102     {
103         URL url = null;
104 
105         // case complete URL
106         try
107         {
108             url = new URL(name);
109         }
110         catch (MalformedURLException ex)
111         {
112             // neglect exception -- just trying
113         }
114 
115         // absolute or relative case
116         if (url == null)
117         {
118             String completeName = name;
119             if (!name.startsWith(File.separator) && !name.startsWith("/") && base != null)
120             {
121                 String baseDir = "";
122                 int i = base.lastIndexOf(File.separator);
123                 if (i == -1 && !File.separator.equals("/"))
124                 {
125                     i = base.lastIndexOf("/");
126                 }
127                 if (i != -1)
128                 {
129                     baseDir = base.substring(0, i + 1);
130                 }
131                 completeName = baseDir + name;
132             }
133 
134             // case base = URL
135             try
136             {
137                 url = new URL(completeName);
138                 if (url.getProtocol().equalsIgnoreCase("file"))
139                 {
140                     File file = new File(url.getPath());
141                     if (!file.exists())
142                     {
143                         url = null;
144                     }
145                 }
146             }
147             catch (MalformedURLException ex)
148             {
149                 url = getResourceOrFile(completeName);
150             }
151 
152             // just try plain name if that's still another option
153             if (url == null && !name.equalsIgnoreCase(completeName))
154             {
155                 url = getResourceOrFile(name);
156             }
157 
158         }
159 
160         // handle authentication
161         if (url != null && url.getUserInfo() != null)
162         {
163             String ui = url.getUserInfo();
164             String userName = ui.substring(0, ui.indexOf(":"));
165             String password = ui.substring(ui.indexOf(":") + 1);
166             Authenticator.setDefault(new PasswordAuthenticator(userName, password));
167         }
168 
169         return url;
170     }
171 
172     /**
173      * Resolves a resource for a path.
174      * @param path String; the path to search for
175      * @return the resolved URL to the path
176      */
177     private static URL getResourceOrFile(String path)
178     {
179         URL url = null;
180 
181         // resource
182         if (url == null)
183         {
184             url = URLResource.class.getResource(path);
185         }
186 
187         // thread context resource
188         if (url == null)
189         {
190             url = Thread.currentThread().getContextClassLoader().getResource(path.substring(1));
191         }
192 
193         // file
194         if (url == null)
195         {
196             File file = new File(path);
197             if (file.exists())
198             {
199                 try
200                 {
201                     url = new URL("file:" + file.getCanonicalPath());
202                 }
203                 catch (IOException ex)
204                 {
205                     // ignore -- if not found, we return null
206                 }
207             }
208         }
209 
210         return url;
211     }
212 
213     /**
214      * returns the resource as stream.
215      * @param name String; the name of the resource
216      * @return the inputStream
217      */
218     public static InputStream getResourceAsStream(final String name)
219     {
220         try
221         {
222             URL url = URLResource.getResource(name);
223             if (url == null)
224             {
225                 return null;
226             }
227             return url.openStream();
228         }
229         catch (Exception exception)
230         {
231             return null;
232         }
233     }
234 
235     /**
236      * A Private password authenticator.
237      */
238     private static class PasswordAuthenticator extends Authenticator
239     {
240         /** my user name. */
241         private String userName = null;
242 
243         /** my password. */
244         private String password = null;
245 
246         /**
247          * constructs a new PasswordAuthenticator.
248          * @param userName String; my userName
249          * @param password String; my passWord
250          */
251         public PasswordAuthenticator(final String userName, final String password)
252         {
253             this.userName = userName;
254             this.password = password;
255         }
256 
257         /** {@inheritDoc} */
258         @Override
259         protected PasswordAuthentication getPasswordAuthentication()
260         {
261             return new PasswordAuthentication(this.userName, this.password.toCharArray());
262         }
263     }
264 
265 }