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 is copied from nl.tudelft.simulation.language.io.
14   * <p>
15   * Copyright (c) 2002-2019 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved.
16   * <p>
17   * See for project information <a href="http://www.simulation.tudelft.nl/">www.simulation.tudelft.nl</a>.
18   * <p>
19   * The DSOL project is distributed under the following BSD-style license:<br>
20   * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
21   * conditions are met:
22   * <ul>
23   * <li>Redistributions of source code must retain the above copyright notice, this list of conditions and the following
24   * disclaimer.</li>
25   * <li>Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
26   * disclaimer in the documentation and/or other materials provided with the distribution.</li>
27   * <li>Neither the name of Delft University of Technology, nor the names of its contributors may be used to endorse or promote
28   * products derived from this software without specific prior written permission.</li>
29   * </ul>
30   * This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including,
31   * but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no
32   * event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or
33   * consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or
34   * profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or
35   * tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the
36   * possibility of such damage.
37   * <p>
38   * @version May 2, 2014 <br>
39   * @author Peter Jacobs
40   * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a>
41   */
42  public final class URLResource
43  {
44      /**
45       * constructs a new URLResource.
46       */
47      private URLResource()
48      {
49          // unreachable code
50      }
51  
52      /**
53       * Resolves a resource for name.
54       * @param name String; the name to search for
55       * @return the resolved URL
56       */
57      public static URL getResource(final String name)
58      {
59          try
60          {
61              File file = new File(name);
62  
63              if (name.startsWith("/"))
64              {
65                  URL url = URLResource.class.getResource(name);
66                  if (url != null)
67                  {
68                      return url;
69                  }
70                  url = Thread.currentThread().getContextClassLoader().getResource(name.substring(1));
71                  if (url != null)
72                  {
73                      return url;
74                  }
75                  if (file.exists())
76                  {
77                      return new URL("file:" + name);
78                  }
79              }
80              else if (name.startsWith("\\") || name.contains("\\")) // added the second part
81              {
82                  if (file.exists())
83                  {
84                      return new URL("file:" + name);
85                  }
86              }
87              else if (file.exists())
88              {
89                  return new URL("file:" + name);
90              }
91              else
92              {
93                  if (name.indexOf("@") == -1)
94                  {
95                      return new URL(name);
96                  }
97                  // we need authentication
98                  String temp = name.substring(name.indexOf("//") + 2);
99                  String userName = temp.substring(0, temp.indexOf(":"));
100                 String password = temp.substring(temp.indexOf(":") + 1);
101                 password = password.substring(0, password.indexOf("@"));
102                 String url = name.substring(0, name.indexOf("//") + 2);
103                 url = url + name.substring(name.indexOf("@") + 1);
104                 Authenticator.setDefault(new PasswordAuthenticator(userName, password));
105                 return new URL(url);
106             }
107         }
108         catch (Exception exception)
109         {
110             exception = null;
111             // We neglect exceptions since we return null
112         }
113         return null;
114     }
115 
116     /**
117      * Resolves a resource for name. For relative names, base is used to resolve to an absolute name. If name is absolute, base
118      * is ignored.
119      * @param name String; the name to search for
120      * @param base String; the base for relative paths
121      * @return the resolved URL
122      */
123     public static URL getResource(final String name, final String base)
124     {
125         URL url = null;
126 
127         // case complete URL
128         try
129         {
130             url = new URL(name);
131         }
132         catch (MalformedURLException ex)
133         {
134             // neglect exception -- just trying
135         }
136 
137         // absolute or relative case
138         if (url == null)
139         {
140             String completeName = name;
141             if (!name.startsWith(File.separator) && !name.startsWith("/") && base != null)
142             {
143                 String baseDir = "";
144                 int i = base.lastIndexOf(File.separator);
145                 if (i == -1 && !File.separator.equals("/"))
146                 {
147                     i = base.lastIndexOf("/");
148                 }
149                 if (i != -1)
150                 {
151                     baseDir = base.substring(0, i + 1);
152                 }
153                 completeName = baseDir + name;
154             }
155 
156             // case base = URL
157             try
158             {
159                 url = new URL(completeName);
160                 if (url.getProtocol().equalsIgnoreCase("file"))
161                 {
162                     File file = new File(url.getPath());
163                     if (!file.exists())
164                     {
165                         url = null;
166                     }
167                 }
168             }
169             catch (MalformedURLException ex)
170             {
171                 url = getResourceOrFile(completeName);
172             }
173 
174             // just try plain name if that's still another option
175             if (url == null && !name.equalsIgnoreCase(completeName))
176             {
177                 url = getResourceOrFile(name);
178             }
179 
180         }
181 
182         // handle authentication
183         if (url != null && url.getUserInfo() != null)
184         {
185             String ui = url.getUserInfo();
186             String userName = ui.substring(0, ui.indexOf(":"));
187             String password = ui.substring(ui.indexOf(":") + 1);
188             Authenticator.setDefault(new PasswordAuthenticator(userName, password));
189         }
190 
191         return url;
192     }
193 
194     /**
195      * Resolves a resource for a path.
196      * @param path String; the path to search for
197      * @return the resolved URL to the path
198      */
199     private static URL getResourceOrFile(String path)
200     {
201         URL url = null;
202 
203         // resource
204         if (url == null)
205         {
206             url = URLResource.class.getResource(path);
207         }
208 
209         // thread context resource
210         if (url == null)
211         {
212             url = Thread.currentThread().getContextClassLoader().getResource(path.substring(1));
213         }
214 
215         // file
216         if (url == null)
217         {
218             File file = new File(path);
219             if (file.exists())
220             {
221                 try
222                 {
223                     url = new URL("file:" + file.getCanonicalPath());
224                 }
225                 catch (IOException ex)
226                 {
227                     // ignore -- if not found, we return null
228                 }
229             }
230         }
231 
232         return url;
233     }
234 
235     /**
236      * returns the resource as stream.
237      * @param name String; the name of the resource
238      * @return the inputStream
239      */
240     public static InputStream getResourceAsStream(final String name)
241     {
242         try
243         {
244             URL url = URLResource.getResource(name);
245             if (url == null)
246             {
247                 return null;
248             }
249             return url.openStream();
250         }
251         catch (Exception exception)
252         {
253             return null;
254         }
255     }
256 
257     /**
258      * A Private password authenticator.
259      */
260     private static class PasswordAuthenticator extends Authenticator
261     {
262         /** my user name. */
263         private String userName = null;
264 
265         /** my password. */
266         private String password = null;
267 
268         /**
269          * constructs a new PasswordAuthenticator.
270          * @param userName String; my userName
271          * @param password String; my passWord
272          */
273         public PasswordAuthenticator(final String userName, final String password)
274         {
275             this.userName = userName;
276             this.password = password;
277         }
278 
279         /** {@inheritDoc} */
280         @Override
281         protected PasswordAuthentication getPasswordAuthentication()
282         {
283             return new PasswordAuthentication(this.userName, this.password.toCharArray());
284         }
285     }
286 
287 }