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="http://www.tbm.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          super();
50          // unreachable code
51      }
52  
53      /**
54       * Resolves a resource for name.
55       * @param name String; the name to search for
56       * @return the resolved URL
57       */
58      public static URL getResource(final String name)
59      {
60          try
61          {
62              File file = new File(name);
63  
64              if (name.startsWith("/"))
65              {
66                  URL url = URLResource.class.getResource(name);
67                  if (url != null)
68                  {
69                      return url;
70                  }
71                  url = Thread.currentThread().getContextClassLoader().getResource(name.substring(1));
72                  if (url != null)
73                  {
74                      return url;
75                  }
76                  if (file.exists())
77                  {
78                      return new URL("file:" + name);
79                  }
80              }
81              else if (name.startsWith("\\") || name.contains("\\")) // added the second part
82              {
83                  if (file.exists())
84                  {
85                      return new URL("file:" + name);
86                  }
87              }
88              else if (file.exists())
89              {
90                  return new URL("file:" + name);
91              }
92              else
93              {
94                  if (name.indexOf("@") == -1)
95                  {
96                      return new URL(name);
97                  }
98                  // we need authentication
99                  String temp = name.substring(name.indexOf("//") + 2);
100                 String userName = temp.substring(0, temp.indexOf(":"));
101                 String password = temp.substring(temp.indexOf(":") + 1);
102                 password = password.substring(0, password.indexOf("@"));
103                 String url = name.substring(0, name.indexOf("//") + 2);
104                 url = url + name.substring(name.indexOf("@") + 1);
105                 Authenticator.setDefault(new PasswordAuthenticator(userName, password));
106                 return new URL(url);
107             }
108         }
109         catch (Exception exception)
110         {
111             exception = null;
112             // We neglect exceptions since we return null
113         }
114         return null;
115     }
116 
117     /**
118      * Resolves a resource for name. For relative names, base is used to resolve to an absolute name. If name is absolute, base
119      * is ignored.
120      * @param name String; the name to search for
121      * @param base String; the base for relative paths
122      * @return the resolved URL
123      */
124     public static URL getResource(final String name, final String base)
125     {
126         URL url = null;
127 
128         // case complete URL
129         try
130         {
131             url = new URL(name);
132         }
133         catch (MalformedURLException ex)
134         {
135             // neglect exception -- just trying
136         }
137 
138         // absolute or relative case
139         if (url == null)
140         {
141             String completeName = name;
142             if (!name.startsWith(File.separator) && !name.startsWith("/") && base != null)
143             {
144                 String baseDir = "";
145                 int i = base.lastIndexOf(File.separator);
146                 if (i == -1 && !File.separator.equals("/"))
147                 {
148                     i = base.lastIndexOf("/");
149                 }
150                 if (i != -1)
151                 {
152                     baseDir = base.substring(0, i + 1);
153                 }
154                 completeName = baseDir + name;
155             }
156 
157             // case base = URL
158             try
159             {
160                 url = new URL(completeName);
161                 if (url.getProtocol().equalsIgnoreCase("file"))
162                 {
163                     File file = new File(url.getPath());
164                     if (!file.exists())
165                     {
166                         url = null;
167                     }
168                 }
169             }
170             catch (MalformedURLException ex)
171             {
172                 url = getResourceOrFile(completeName);
173             }
174 
175             // just try plain name if that's still another option
176             if (url == null && !name.equalsIgnoreCase(completeName))
177             {
178                 url = getResourceOrFile(name);
179             }
180 
181         }
182 
183         // handle authentication
184         if (url != null && url.getUserInfo() != null)
185         {
186             String ui = url.getUserInfo();
187             String userName = ui.substring(0, ui.indexOf(":"));
188             String password = ui.substring(ui.indexOf(":") + 1);
189             Authenticator.setDefault(new PasswordAuthenticator(userName, password));
190         }
191 
192         return url;
193     }
194 
195     /**
196      * Resolves a resource for a path.
197      * @param path String; the path to search for
198      * @return the resolved URL to the path
199      */
200     private static URL getResourceOrFile(String path)
201     {
202         URL url = null;
203 
204         // resource
205         if (url == null)
206         {
207             url = URLResource.class.getResource(path);
208         }
209 
210         // thread context resource
211         if (url == null)
212         {
213             url = Thread.currentThread().getContextClassLoader().getResource(path.substring(1));
214         }
215 
216         // file
217         if (url == null)
218         {
219             File file = new File(path);
220             if (file.exists())
221             {
222                 try
223                 {
224                     url = new URL("file:" + file.getCanonicalPath());
225                 }
226                 catch (IOException ex)
227                 {
228                     // ignore -- if not found, we return null
229                 }
230             }
231         }
232 
233         return url;
234     }
235 
236     /**
237      * returns the resource as stream.
238      * @param name String; the name of the resource
239      * @return the inputStream
240      */
241     public static InputStream getResourceAsStream(final String name)
242     {
243         try
244         {
245             URL url = URLResource.getResource(name);
246             if (url == null)
247             {
248                 return null;
249             }
250             return url.openStream();
251         }
252         catch (Exception exception)
253         {
254             return null;
255         }
256     }
257 
258     /**
259      * A Private password authenticator.
260      */
261     private static class PasswordAuthenticator extends Authenticator
262     {
263         /** my user name. */
264         private String userName = null;
265 
266         /** my password. */
267         private String password = null;
268 
269         /**
270          * constructs a new PasswordAuthenticator.
271          * @param userName String; my userName
272          * @param password String; my passWord
273          */
274         public PasswordAuthenticator(final String userName, final String password)
275         {
276             super();
277             this.userName = userName;
278             this.password = password;
279         }
280 
281         /** {@inheritDoc} */
282         @Override
283         protected PasswordAuthentication getPasswordAuthentication()
284         {
285             return new PasswordAuthentication(this.userName, this.password.toCharArray());
286         }
287     }
288 
289 }