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