Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 55214b98e33010bcb4b3d66b39ef7cddf83396e4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/**
 * Copyright (c) 2007 IBM Corporation and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   IBM - Initial API and implementation
 */
package org.eclipse.emf.ecore.resource.impl;


import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.ContentHandler;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.eclipse.emf.ecore.resource.URIHandler;


/**
 * An implementation of a {@link URIHandler URI handler}.
 *
 */
public class URIHandlerImpl implements URIHandler
{
  /**
   * Creates an instance.
   */
  public URIHandlerImpl()
  {
    super();
  }

  /**
   * This implementation always returns true; clients are generally expected to override this.
   */
  public boolean canHandle(URI uri)
  {
    return true;
  }

  /**
   * Returns the value of the {@link URIConverter#OPTION_URI_CONVERTER URI converter option}.
   * @param options the options in which to look for the URI converter.
   * @return the value of the URI converter option.
   */
  protected URIConverter getURIConverter(Map<?, ?> options)
  {
    return (URIConverter)options.get(URIConverter.OPTION_URI_CONVERTER);
  }

  /**
   * Returns the value of the {@link URIConverter#OPTION_RESPONSE response option}.
   * @param options the options in which to look for the response option.
   * @return the value of the response option.
   */
  @SuppressWarnings("unchecked")
  protected Map<Object, Object> getResponse(Map<?, ?> options)
  {
    return (Map<Object, Object>)options.get(URIConverter.OPTION_RESPONSE);
  }

  /**
   * Returns the value of the {@link URIConverter#OPTION_REQUESTED_ATTRIBUTES requested attributes option}.
   * @param options the options in which to look for the requested attributes option.
   * @return the value of the requested attributes option.
   */
  @SuppressWarnings("unchecked")
  protected Set<String> getRequestedAttributes(Map<?, ?> options)
  {
    return (Set<String>)options.get(URIConverter.OPTION_REQUESTED_ATTRIBUTES);
  }

  /**
   * Returns the value of the {@link URIConverter#OPTION_TIMEOUT timeout option}.
   * @param options the options in which to look for the timeout option.
   * @return the value of the timeout option, or <code>0</code> if not present.
   * @since 2.9
   */
  protected int getTimeout(Map<?, ?> options)
  {
    Integer timeout = (Integer)options.get(URIConverter.OPTION_TIMEOUT);
    return timeout == null ? 0 : timeout.intValue();
  }

  /**
   * Creates an output stream for the URI, assuming it's a URL, and returns it.
   * Specialized support is provided for HTTP URLs.
   * @return an open output stream.
   * @exception IOException if there is a problem obtaining an open output stream.
   */
  public OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException
  {
    try
    {
      URL url = new URL(uri.toString());
      final URLConnection urlConnection = url.openConnection();
      urlConnection.setDoOutput(true);
      int timeout = getTimeout(options);
      if (timeout != 0)
      {
        urlConnection.setConnectTimeout(timeout);
      }
      if (urlConnection instanceof HttpURLConnection)
      {
        final HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
        httpURLConnection.setRequestMethod("PUT");
        return
          new FilterOutputStream(urlConnection.getOutputStream())
          {
            @Override
            public void close() throws IOException
            {
              super.close();
              int responseCode = httpURLConnection.getResponseCode();
              switch (responseCode)
              {
                case HttpURLConnection.HTTP_OK:
                case HttpURLConnection.HTTP_CREATED:
                case HttpURLConnection.HTTP_NO_CONTENT:
                {
                  break;
                }
                default:
                {
                  throw new IOException("PUT failed with HTTP response code " + responseCode);
                }
              }
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException
            {
              out.write(b, off, len);
            }
          };
      }
      else
      {
        OutputStream result = urlConnection.getOutputStream();
        final Map<Object, Object> response = getResponse(options);
        if (response != null)
        {
          result = 
            new FilterOutputStream(result)
            {
              @Override
              public void close() throws IOException
              {
                try
                {
                  super.close();
                }
                finally
                {
                  response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified());
                }
              }

              @Override
              public void write(byte[] b, int off, int len) throws IOException
              {
                out.write(b, off, len);
              }
            };
        }
        return result;
      }
    }
    catch (RuntimeException exception)
    {
      throw new Resource.IOWrappedException(exception);
    }
  }

  /**
   * Creates an input stream for the URI, assuming it's a URL, and returns it.
   * @return an open input stream.
   * @exception IOException if there is a problem obtaining an open input stream.
   */
  public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException
  {
    try
    {
      URL url = new URL(uri.toString());
      final URLConnection urlConnection = url.openConnection();
      int timeout = getTimeout(options);
      if (timeout != 0)
      {
        urlConnection.setConnectTimeout(timeout);
        urlConnection.setReadTimeout(timeout);
      }
      InputStream result = urlConnection.getInputStream();
      Map<Object, Object> response = getResponse(options);
      if (response != null)
      {
        response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified());
      }
      return result;
    }
    catch (RuntimeException exception)
    {
      throw new Resource.IOWrappedException(exception);
    }
  }

  /**
   * Only HTTP connections support delete.
   */
  public void delete(URI uri, Map<?, ?> options) throws IOException
  {
    try
    {
      URL url = new URL(uri.toString());
      URLConnection urlConnection = url.openConnection();
      urlConnection.setDoOutput(true);
      int timeout = getTimeout(options);
      if (timeout != 0)
      {
        urlConnection.setConnectTimeout(timeout);
      }
      if (urlConnection instanceof HttpURLConnection)
      {
        final HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
        httpURLConnection.setRequestMethod("DELETE");
        int responseCode = httpURLConnection.getResponseCode();
        switch (responseCode)
        {
          case HttpURLConnection.HTTP_OK:
          case HttpURLConnection.HTTP_ACCEPTED:
          case HttpURLConnection.HTTP_NO_CONTENT:
          {
            break;
          }
          default:
          {
            throw new IOException("DELETE failed with HTTP response code " + responseCode);
          }
        }
      }
      else
      {
        throw new IOException("Delete is not supported for " + uri);
      }
    }
    catch (RuntimeException exception)
    {
      throw new Resource.IOWrappedException(exception);
    }
  }

  /**
   * This implementation delegates to the {@link #getURIConverter(Map) URI converter}'s {@link URIConverter#getContentHandlers() content handlers}.
   */
  public Map<String, ?> contentDescription(URI uri, Map<?, ?> options) throws IOException
  {
    URIConverter uriConverter = (URIConverter)options.get(URIConverter.OPTION_URI_CONVERTER);
    InputStream inputStream = null;
    Map<String, ?> result = null;
    Map<Object, Object> context = new HashMap<Object, Object>();
    try
    {
      for (ContentHandler contentHandler : uriConverter.getContentHandlers())
      {
        if (contentHandler.canHandle(uri))
        {
          if (inputStream == null)
          {
            try
            {
              inputStream = createInputStream(uri, options);
            }
            catch (IOException exception)
            {
              inputStream = new ByteArrayInputStream(new byte [0]);
            }
            if (!inputStream.markSupported())
            {
              inputStream = new BufferedInputStream(inputStream);
            }
            inputStream.mark(Integer.MAX_VALUE);
          }
          else
          {
            inputStream.reset();
          }
          Map<String, ?> contentDescription = contentHandler.contentDescription(uri, inputStream, options, context);
          switch ((ContentHandler.Validity)contentDescription.get(ContentHandler.VALIDITY_PROPERTY))
          {
            case VALID:
            {
              return contentDescription;
            }
            case INDETERMINATE:
            {
              if (result == null)
              {
                result = contentDescription;
              }
              break;
            }
            case INVALID:
            {
              break;
            }
          }
        }
      }
    }
    finally
    {
      if (inputStream != null)
      {
        inputStream.close();
      }
    }

    return result == null ? ContentHandler.INVALID_CONTENT_DESCRIPTION : result;
  }

  /**
   * If a stream can be created the file exists.
   * Specialized support is provided for HTTP connections to avoid fetching the whole stream in that case.
   */
  public boolean exists(URI uri, Map<?, ?> options)
  {
    try
    {
      URL url = new URL(uri.toString());
      URLConnection urlConnection = url.openConnection();
      int timeout = getTimeout(options);
      if (timeout != 0)
      {
        urlConnection.setConnectTimeout(timeout);
        urlConnection.setReadTimeout(timeout);
      }
      if (urlConnection instanceof HttpURLConnection)
      {
        HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
        httpURLConnection.setRequestMethod("HEAD");
        int responseCode = httpURLConnection.getResponseCode();
        // TODO
        // I'm concerned that folders will often return 401 or even 403.
        // So should we consider something to exist even though access if unauthorized or forbidden?
        //
        return responseCode == HttpURLConnection.HTTP_OK;
      }
      else
      {
        InputStream inputStream = urlConnection.getInputStream();
        inputStream.close();
        return true;
      }
    }
    catch (Throwable exception)
    {
      return false;
    }
  }

  public Map<String, ?> getAttributes(URI uri, Map<?, ?> options)
  {
    Map<String, Object> result = new HashMap<String, Object>();
    Set<String> requestedAttributes = getRequestedAttributes(options);
    try
    {
      URL url = new URL(uri.toString());
      URLConnection urlConnection = null;
      if (requestedAttributes == null || requestedAttributes.contains(URIConverter.ATTRIBUTE_READ_ONLY))
      {
        urlConnection = url.openConnection();
        int timeout = getTimeout(options);
        if (timeout != 0)
        {
          urlConnection.setConnectTimeout(timeout);
          urlConnection.setReadTimeout(timeout);
        }
        if (urlConnection instanceof HttpURLConnection)
        {
          HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
          httpURLConnection.setRequestMethod("OPTIONS");
          int responseCode = httpURLConnection.getResponseCode();
          if (responseCode == HttpURLConnection.HTTP_OK)
          {
            String allow = httpURLConnection.getHeaderField("Allow");
            result.put(URIConverter.ATTRIBUTE_READ_ONLY, allow == null || !allow.contains("PUT"));
          }
          urlConnection = null;
        }
        else
        {
          result.put(URIConverter.ATTRIBUTE_READ_ONLY, true);
        }
      }

      if (requestedAttributes == null || requestedAttributes.contains(URIConverter.ATTRIBUTE_TIME_STAMP))
      {
        if (urlConnection == null)
        {
          urlConnection = url.openConnection();
          int timeout = getTimeout(options);
          if (timeout != 0)
          {
            urlConnection.setConnectTimeout(timeout);
            urlConnection.setReadTimeout(timeout);
          }
          if (urlConnection instanceof HttpURLConnection)
          {
            HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
            httpURLConnection.setRequestMethod("HEAD");
            httpURLConnection.getResponseCode();
          }
        }
        if (urlConnection.getHeaderField("last-modified") != null)
        {
          result.put(URIConverter.ATTRIBUTE_TIME_STAMP, urlConnection.getLastModified());
        }
      }

      if (requestedAttributes == null || requestedAttributes.contains(URIConverter.ATTRIBUTE_LENGTH))
      {
        if (urlConnection == null)
        {
          urlConnection = url.openConnection();
          int timeout = getTimeout(options);
          if (timeout != 0)
          {
            urlConnection.setConnectTimeout(timeout);
            urlConnection.setReadTimeout(timeout);
          }
          if (urlConnection instanceof HttpURLConnection)
          {
            HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
            httpURLConnection.setRequestMethod("HEAD");
            httpURLConnection.getResponseCode();
          }
        }
        if (urlConnection.getHeaderField("content-length") != null)
        {
          result.put(URIConverter.ATTRIBUTE_LENGTH, urlConnection.getContentLength());
        }
      }
    }
    catch (IOException exception)
    {
      // Ignore exceptions.
    }
    return result;
  }

  public void setAttributes(URI uri, Map<String, ?> attributes, Map<?, ?> options) throws IOException
  {
    // We can't update any properties via just a URL connection.
  }
}

Back to the top