Skip to main content
summaryrefslogtreecommitdiffstats
blob: 8015e6fada59aaec54c0fd1ea881e6855e92660f (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
/*******************************************************************************
 * Copyright (c) 2014 Boeing.
 * 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:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.template.engine.internal;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.ws.rs.core.MediaType;
import org.eclipse.osee.framework.jdk.core.type.IResourceRegistry;
import org.eclipse.osee.framework.jdk.core.type.ResourceToken;
import org.eclipse.osee.framework.jdk.core.util.ChecksumUtil;
import org.eclipse.osee.framework.jdk.core.util.HexUtil;
import org.eclipse.osee.framework.jdk.core.util.Strings;
import org.eclipse.osee.logger.Log;
import org.eclipse.osee.template.engine.OseeTemplateTokens;
import org.eclipse.osgi.util.ManifestElement;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleException;
import org.osgi.framework.BundleListener;

/**
 * @author Roberto E. Escobar
 */
public class TemplateRegistryImpl implements TemplateRegistry, IResourceRegistry, BundleListener {

   private static final String OSEE_TEMPLATE_HDR = "Osee-Template";
   private static final String OSEE_TEMPLATE_HDR__UUID_ATTRIBUTE = "uuid";

   private ConcurrentHashMap<String, TemplateResources> templates;
   private ConcurrentHashMap<Long, ResourceToken> tokenByUuid;
   private ConcurrentHashMap<String, ResourceToken> tokenByName;

   private Log logger;

   public void setLogger(Log logger) {
      this.logger = logger;
   }

   public void start(BundleContext context) {
      templates = new ConcurrentHashMap<String, TemplateResources>();
      tokenByName = new ConcurrentHashMap<String, ResourceToken>();
      tokenByUuid = new ConcurrentHashMap<Long, ResourceToken>();

      OseeTemplateTokens.register(this);

      context.addBundleListener(this);

      // Add bundles that have already started
      Bundle[] bundles = context.getBundles();
      if (bundles != null) {
         for (Bundle bundle : bundles) {
            int state = bundle.getState();
            processBundle(bundle, state);
         }
      }
   }

   public void stop(BundleContext context) {
      context.removeBundleListener(this);

      templates.clear();
      tokenByName.clear();
      tokenByUuid.clear();
   }

   private void cache(ResourceToken token) {
      tokenByUuid.put(token.getGuid(), token);
      ResourceToken oldToken = tokenByName.put(token.getName(), token);
      if (oldToken != null) {
         logger.error("Template conflict detected between - [%s] and [%s]", oldToken, token);
      }
   }

   private void decache(ResourceToken token) {
      tokenByUuid.remove(token.getGuid());
      tokenByName.remove(token.getName());
   }

   private String getTemplateHeader(Bundle bundle) {
      return bundle.getHeaders().get(OSEE_TEMPLATE_HDR);
   }

   private boolean hasTemplateHeader(Bundle bundle) {
      String headerValue = getTemplateHeader(bundle);
      return Strings.isValid(headerValue);
   }

   @Override
   public ResourceToken resolveTemplate(String viewId, MediaType mediaType) {
      ResourceToken resourceToken = null;
      if (Strings.isNumeric(viewId)) {
         Long uuid = Long.parseLong(viewId);
         resourceToken = getResourceToken(uuid);
      } else {
         String name = viewId;
         int index = name.lastIndexOf("/");
         if (index > -1) {
            name = name.substring(index + 1);
         }
         resourceToken = tokenByName.get(name);
      }
      return resourceToken;
   }

   @Override
   public IResourceRegistry getResourceRegistry() {
      return this;
   }

   @Override
   public ResourceToken registerResource(Long universalId, ResourceToken token) {
      throw new UnsupportedOperationException();
   }

   @Override
   public void registerAll(Iterable<ResourceToken> tokens) {
      for (ResourceToken token : tokens) {
         cache(token);
      }
   }

   @Override
   public ResourceToken getResourceToken(Long uuid) {
      return tokenByUuid.get(uuid);
   }

   @Override
   public InputStream getResource(Long uuid) {
      ResourceToken token = getResourceToken(uuid);
      InputStream toReturn = null;
      if (token != null) {
         toReturn = token.getInputStream();
      } else {
         logger.error("Unable to find template-resource [%s]", uuid);
      }
      return toReturn;
   }

   @Override
   public void bundleChanged(BundleEvent event) {
      Bundle bundle = event.getBundle();
      processBundle(bundle, event.getType());
   }

   private void processBundle(Bundle bundle, int state) {
      boolean isActive = true;
      boolean isStopping = false;
      if (state == Bundle.ACTIVE //
         || state == Bundle.STARTING //
         || state == Bundle.INSTALLED //
         || state == Bundle.RESOLVED) {
         isActive = true;
      } else if (state == Bundle.STOPPING) {
         isStopping = true;
      }

      if (isActive && hasTemplateHeader(bundle)) {
         addBundle(bundle);
      } else if (isStopping && hasTemplateHeader(bundle)) {
         removeBundle(bundle);
      }
   }

   private void removeBundle(Bundle bundle) {
      String bundleName = bundle.getSymbolicName();
      TemplateResources removed = templates.remove(bundleName);
      if (removed != null) {
         Iterable<ResourceToken> tokens = removed.getTokens();
         for (ResourceToken token : tokens) {
            decache(token);
         }
      }
   }

   private void addBundle(Bundle bundle) {
      String bundleName = bundle.getSymbolicName();
      String headerValue = getTemplateHeader(bundle);

      ManifestElement[] elements = null;
      try {
         elements = ManifestElement.parseHeader(OSEE_TEMPLATE_HDR, headerValue);
      } catch (BundleException ex) {
         logger.error(ex, "Error parsing manifest header [%s] for bundle [%s]", OSEE_TEMPLATE_HDR, bundleName);
      }

      if (elements != null && elements.length > 0) {
         TemplateResources tokens = new TemplateResources();
         for (ManifestElement element : elements) {
            String resource = element.getValue();
            String uuidAttribute = element.getAttribute(OSEE_TEMPLATE_HDR__UUID_ATTRIBUTE);
            List<URL> resourceUrls = findUrls(bundle, headerValue, false, resource);

            if (resourceUrls != null && !resourceUrls.isEmpty()) {
               if (Strings.isValid(uuidAttribute)) {
                  if (isValidUuid(uuidAttribute)) {
                     URL url = resourceUrls.iterator().next();
                     Long uuid = HexUtil.toLong(uuidAttribute);
                     addEntry(bundleName, headerValue, tokens, url, uuid);
                  } else {
                     logger.error("Invalid uuidAttribute [%s] for manifest element [%s] in bundle [%s]", uuidAttribute,
                        element, bundleName);
                  }
               } else {
                  for (URL url : resourceUrls) {
                     addEntry(bundleName, headerValue, tokens, url, null);
                  }
               }
            }
         }
         if (!tokens.isEmpty()) {
            templates.put(bundleName, tokens);
         }
      }
   }

   private boolean isValidUuid(String value) {
      return HexUtil.isHexString(value);
   }

   private void addEntry(String bundleName, String headerValue, TemplateResources tokens, URL url, Long uuidSpecified) {
      try {
         String name = urlAsName(url);
         Long uuid = uuidSpecified != null ? uuidSpecified : nameToUuid(name);
         ResourceToken token = newToken(bundleName, uuid, name, url);
         boolean wasAdded = tokens.addToken(token);
         if (!wasAdded) {
            logger.error("Invalid template uuid conflicts with previous definition - bundle [%s] header [%s]",
               bundleName, headerValue);
         }
         cache(token);
      } catch (Exception ex) {
         logger.error(ex, "Invalid uuidAttribute for bundle [%s] with header [%s]", bundleName, headerValue);
      }
   }

   private Long nameToUuid(String name) throws Exception {
      ByteArrayInputStream inputStream = new ByteArrayInputStream(name.getBytes("UTF-8"));
      byte[] checksum = ChecksumUtil.createChecksum(inputStream, ChecksumUtil.SHA);
      long value = 0;
      for (int i = 0; i < 8; i++) {
         value += (checksum[i] & 0xffL) << (8 * i);
      }
      return value;
   }

   private String urlAsName(URL url) {
      String name = url.toString();
      int index = name.lastIndexOf('/');
      if (index > -1) {
         name = name.substring(index + 1);
      }
      return name;
   }

   private List<URL> findUrls(Bundle bundle, String headerValue, boolean recurse, String... resources) {
      List<URL> resourceUrls = new ArrayList<URL>();
      for (String resource : resources) {
         int index = resource.lastIndexOf('/');
         String path = index != -1 ? resource.substring(0, index) : "/";
         String resourceName = index != -1 ? resource.substring(index + 1) : resource;
         Enumeration<URL> urls = bundle.findEntries(path, resourceName, recurse);
         if (urls != null && urls.hasMoreElements()) {
            while (urls.hasMoreElements()) {
               URL url = urls.nextElement();
               resourceUrls.add(url);
            }
         } else {
            logger.error("Unable to find template-resource[%s] for bundle [%s]. The component header value is [%s]",
               resource, bundle.getSymbolicName(), headerValue);
         }
      }
      return resourceUrls;
   }

   private static ResourceToken newToken(String bundleName, Long uuid, String name, URL url) {
      return new TemplateToken(bundleName, uuid, name, url);
   }

   private static class TemplateResources {
      private final Set<ResourceToken> tokens = new HashSet<ResourceToken>();

      public boolean addToken(ResourceToken token) {
         return tokens.add(token);
      }

      public Iterable<ResourceToken> getTokens() {
         return tokens;
      }

      public boolean isEmpty() {
         return tokens.isEmpty();
      }
   }

   private static class TemplateToken extends ResourceToken {
      private final String bundleName;
      private final Long uuid;
      private final String name;
      private final URL url;

      public TemplateToken(String bundleName, Long uuid, String name, URL url) {
         super(uuid, name);
         this.bundleName = bundleName;
         this.uuid = uuid;
         this.name = name;
         this.url = url;
      }

      @Override
      public URL getUrl() {
         return url;
      }

      @Override
      public int hashCode() {
         final int prime = 31;
         int result = super.hashCode();
         result = prime * result + ((url == null) ? 0 : url.hashCode());
         return result;
      }

      @Override
      public boolean equals(Object obj) {
         if (this == obj) {
            return true;
         }
         if (!super.equals(obj)) {
            return false;
         }
         if (getClass() != obj.getClass()) {
            return false;
         }
         ResourceToken other = (ResourceToken) obj;
         if (getUrl() == null) {
            if (other.getUrl() != null) {
               return false;
            }
         } else if (!getUrl().equals(other.getUrl())) {
            return false;
         }
         return true;
      }

      @Override
      public String toString() {
         return String.format("%s::%s::%s - [%s]", bundleName, uuid, name, url);
      }
   }

}

Back to the top