Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: a2bad8ddcb064c14c7f1e162ba78092c887cc21a (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
/*
 * Copyright (c) 2014-2017 Eike Stepper (Loehne, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v20.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.oomph.base.util;

import org.eclipse.oomph.base.BasePackage;
import org.eclipse.oomph.base.ModelElement;
import org.eclipse.oomph.util.ReflectUtil;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.BasicExtendedMetaData;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.XMLHelper;
import org.eclipse.emf.ecore.xmi.XMLLoad;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.XMLSave;
import org.eclipse.emf.ecore.xmi.impl.SAXXMIHandler;
import org.eclipse.emf.ecore.xmi.impl.XMIHelperImpl;
import org.eclipse.emf.ecore.xmi.impl.XMILoadImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
import org.eclipse.emf.ecore.xmi.impl.XMISaveImpl;
import org.eclipse.emf.ecore.xmi.impl.XMLString;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * <!-- begin-user-doc -->
 * The <b>Resource </b> associated with the package.
 * @implements org.eclipse.oomph.setup.util.SetupResource
 * <!-- end-user-doc -->
 * @see org.eclipse.oomph.base.util.BaseResourceFactoryImpl
 * @generated
 */
public class BaseResourceImpl extends XMIResourceImpl implements org.eclipse.oomph.base.util.BaseResource
{
  /**
   * Creates an instance of the resource.
   * <!-- begin-user-doc -->
   * <!-- end-user-doc -->
   * @param uri the URI of the new resource.
   * @generated
   */
  public BaseResourceImpl(URI uri)
  {
    super(uri);
  }

  @Override
  public void doLoad(InputStream inputStream, Map<?, ?> options) throws IOException
  {
    if (options.get(OPTION_EXTENDED_META_DATA) instanceof Boolean)
    {
      ResourceSet resourceSet = getResourceSet();
      Map<Object, Object> effectiveOptions = new HashMap<Object, Object>(options);
      effectiveOptions.put(OPTION_EXTENDED_META_DATA,
          new BasicExtendedMetaData(resourceSet == null ? EPackage.Registry.INSTANCE : resourceSet.getPackageRegistry())
          {
            @Override
            public EStructuralFeature getElement(EClass eClass, String namespace, String name)
            {
              EStructuralFeature eStructuralFeature = super.getElement(eClass, namespace, name);
              if (eStructuralFeature == null)
              {
                eStructuralFeature = super.getElement(eClass, namespace, name.substring(0, name.length() - 1));
              }

              if (eStructuralFeature == null)
              {
                eStructuralFeature = eClass.getEStructuralFeature(name);
              }

              return eStructuralFeature;
            }
          });
      options = effectiveOptions;
    }

    super.doLoad(inputStream, options);
  }

  @Override
  protected XMLLoad createXMLLoad()
  {
    return new XMILoadImpl(createXMLHelper())
    {
      @Override
      protected DefaultHandler makeDefaultHandler()
      {
        return new SAXXMIHandler(resource, helper, options)
        {
          @Override
          protected String getLocation()
          {
            String result = super.getLocation();
            URI uri = getURI();
            if (uri != null)
            {
              String normalizedURI = getURIConverter().normalize(uri).toString();
              if (!result.equals(normalizedURI))
              {
                result += " -> " + normalizedURI;
              }
            }

            return result;
          }

          @Override
          public InputSource resolveEntity(String publicId, String systemId) throws SAXException
          {
            URI uri = getURI();
            String message = "Unexpected entity: publicId=" + publicId + ", systemId=" + systemId + ", uri=" + uri;

            URI normalizedURI = getURIConverter().normalize(uri);
            if (!normalizedURI.equals(uri))
            {
              message += ", normalizedURI=" + normalizedURI;
            }

            throw new SAXException(message);
          }

          @Override
          protected void setFeatureValue(EObject object, EStructuralFeature feature, Object value)
          {
            if (value != null && feature.getEType() == BasePackage.Literals.TEXT)
            {
              // Split the string value into lines.
              String stringValue = value.toString();
              String[] lines = stringValue.split("\n", Integer.MAX_VALUE);
              if (lines.length > 1)
              {
                // Ignore the first line if it's only white space and the last line if it's only white space.
                int start = lines[0].trim().length() == 0 ? 1 : 0;
                String lastLine = lines[lines.length - 1];
                int end = lastLine.trim().length() == 0 ? lines.length - 1 : lines.length;

                if (start < end)
                {
                  // If the first line starts on the same line as the element start tag, ignore that line in terms of indentation computation.
                  // Compute the minimum indentation from the first non white space character of each line.
                  int minIndent = Integer.MAX_VALUE;
                  for (int i = start == 0 ? 1 : start; i < end; ++i)
                  {
                    String line = lines[i];
                    String trimmedLine = line.trim();
                    if (trimmedLine.length() > 0)
                    {
                      int indent = line.indexOf(trimmedLine);
                      if (minIndent > indent)
                      {
                        minIndent = indent;
                      }
                    }
                  }

                  // If there are only blank lines, we're a bit confused.
                  if (minIndent == Integer.MAX_VALUE)
                  {
                    minIndent = lastLine.length();

                    // Use the depth of the stack to determine how much of the whitespace in the last line can be attributed to nesting.
                    // Assume that the XML is consistently formatted/indented and that a consistent fraction of the indentation is attributable to each nesting
                    // level such that the current nesting level would need one more such fractional increment.
                    int depth = elements.size();
                    minIndent += minIndent / depth;
                  }

                  // If the first line starts on the same line as the element start tag, just add it as is.
                  StringBuilder s = new StringBuilder();
                  if (start == 0)
                  {
                    s.append(lines[0]);
                    if (++start < end)
                    {
                      s.append("\n");
                    }
                  }

                  // For all the other lines, trim off the leading indentation.
                  for (int i = start; i < end;)
                  {
                    String line = lines[i];
                    int length = line.length();
                    if (length > minIndent)
                    {
                      s.append(line, minIndent, length);
                    }

                    if (++i < end)
                    {
                      s.append("\n");
                    }
                  }

                  value = s.toString();
                }
              }
            }

            super.setFeatureValue(object, feature, value);
          }
        };
      }
    };
  }

  private static final Method GET_ELEMENT_INDENT_METHOD;

  static
  {
    GET_ELEMENT_INDENT_METHOD = ReflectUtil.getMethod(XMLString.class, "getElementIndent", int.class);
    GET_ELEMENT_INDENT_METHOD.setAccessible(true);
  }

  @Override
  protected XMLSave createXMLSave()
  {
    return new XMISaveImpl(createXMLHelper())
    {
      @Override
      protected String getDatatypeValue(Object value, EStructuralFeature f, boolean isAttribute)
      {
        // If we're serializing the a Text value as an element.
        if (value != null && !isAttribute && f.getEType() == BasePackage.Literals.TEXT)
        {
          // Split what we know is a String value into lines.
          String stringValue = value.toString();
          String[] lines = stringValue.split("\r?\n", Integer.MAX_VALUE);
          if (lines.length == 1)
          {
            // If there are no line separators, serialize just the string value.
            //
            return escape == null ? stringValue : escape.convertText(stringValue);
          }

          // Compute the target format that will serialize nested under the element start/end tabs by one indentation level.
          String elementIdent = getElementIndent(1);
          String contentIndent = getElementIndent(2);
          StringBuilder s = new StringBuilder("\n");
          for (int i = 0; i < lines.length; ++i)
          {
            // Only if the line isn't empty, serialize the indentation followed by the line content.
            String line = lines[i];
            if (line.length() != 0)
            {
              s.append(contentIndent);
              s.append(line);
            }

            // Always add the line separator.
            s.append("\n");
          }

          // Add enough indentation so the closing element is indented correctly too.
          s.append(elementIdent);

          return escape == null ? s.toString() : escape.convertText(s.toString());
        }

        return super.getDatatypeValue(value, f, isAttribute);
      }

      private String getElementIndent(int extraIndent)
      {
        try
        {
          return GET_ELEMENT_INDENT_METHOD.invoke(doc, extraIndent).toString();
        }
        catch (Exception ex)
        {
          return "";
        }
      }
    };
  }

  @Override
  protected XMLHelper createXMLHelper()
  {
    return new BaseHelperImpl(this);
  }

  /**
   * @author Ed Merks
   */
  public static class BaseHelperImpl extends XMIHelperImpl
  {
    public BaseHelperImpl(XMLResource resource)
    {
      super(resource);
    }

    @Override
    public URI getHREF(Resource otherResource, EObject obj)
    {
      // Walk up the containers.
      InternalEObject internalEObject = (InternalEObject)obj;

      EObject basisObject = null;
      boolean checkedID = false;
      String id = null;
      for (InternalEObject container = (InternalEObject)internalEObject.eContainer(); container != null; container = (InternalEObject)container.eContainer())
      {
        // If the object is contained by this helper's resource, we want a normal "downward" pointing href.
        Internal eDirectResource = container.eDirectResource();
        if (eDirectResource == resource)
        {
          return super.getHREF(otherResource, obj);
        }

        if (eDirectResource != null && basisObject == null)
        {
          if (!checkedID)
          {
            checkedID = true;
            id = EcoreUtil.getID(obj);
          }

          if (id != null && container instanceof ModelElement)
          {
            basisObject = container;
          }
        }

        internalEObject = container;
      }

      Resource rootContainerResource = internalEObject.eResource();
      if (rootContainerResource != otherResource && rootContainerResource != null)
      {
        String fragmentPath = EcoreUtil.getRelativeURIFragmentPath(internalEObject, basisObject == null ? obj : basisObject);
        URI proxyURI = super.getHREF(rootContainerResource, internalEObject);
        StringBuilder fragment = new StringBuilder(proxyURI.fragment());
        fragment.append('/');
        fragment.append(fragmentPath);
        if (basisObject != null)
        {
          fragment.append("/'");
          encode(fragment, id);
          fragment.append('\'');
        }

        return proxyURI.appendFragment(fragment.toString());
      }

      return super.getHREF(otherResource, obj);
    }

    @Override
    public URI deresolve(URI uri)
    {
      return super.deresolve(BaseUtil.resolveBogusURI(uri));
    }
  }

  private static final String[] ESCAPE = { "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07", "%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F",
      "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17", "%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F", "%20", null, "%22", "%23", null, "%25",
      "%26", "%27", null, null, null, null, "%2C", null, null, "%2F", null, null, null, null, null, null, null, null, null, null, "%3A", null, "%3C", null,
      "%3E", null, };

  private static void encode(StringBuilder result, String value)
  {
    int length = value.length();
    boolean encode = false;
    for (int i = 0; i < length; ++i)
    {
      char character = value.charAt(i);
      if (character < ESCAPE.length)
      {
        String escape = ESCAPE[character];
        if (escape != null)
        {
          if (!encode)
          {
            encode = true;
            result.append(value, 0, i);
          }

          result.append(escape);
          continue;
        }
      }

      if (encode)
      {
        result.append(character);
      }
    }

    if (!encode)
    {
      result.append(value);
    }
  }
} // SetupResourceImpl

Back to the top