summaryrefslogtreecommitdiffstats
path: root/sandbox/rfeng/tuscany-provisioning/src/main/java/org/apache/tuscany/sca/provision/ExtensionIntrospector.java
blob: b44c0e30894ee44c36d58dd1fb987d5e6712e878 (plain)
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */

package org.apache.tuscany.sca.provision;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.xml.namespace.QName;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.embedder.MavenEmbedder;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.runtime.DefaultMavenRuntime;
import org.apache.maven.shared.runtime.MavenRuntime;
import org.apache.maven.shared.runtime.MavenRuntimeException;
import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry;
import org.apache.tuscany.sca.core.ExtensionPointRegistry;
import org.apache.tuscany.sca.extensibility.ServiceDeclaration;
import org.apache.tuscany.sca.extensibility.ServiceDeclarationParser;
import org.apache.tuscany.sca.extensibility.ServiceDiscovery;
import org.codehaus.plexus.embed.Embedder;

/**
 * 
 */
public class ExtensionIntrospector {
    private ExtensionPointRegistry registry;
    private boolean loaded;
    private boolean offline;
    private MavenRuntime mavenRuntime = new DefaultMavenRuntime();

    private MavenEmbedder embedder;
    private ArtifactResolver resolver;
    private Embedder internalEmbedder;
    ArtifactMetadataSource artifactMetadataSource;
    private ArtifactRepository remoteRepo;

    // Key: java model type
    private Map<String, MavenProject> modules = new HashMap<String, MavenProject>();

    // Key: extension categories
    private Map<String, Collection<String>> types = new HashMap<String, Collection<String>>();

    // Key: java model type
    private Map<String, QName> qnames = new HashMap<String, QName>();

    /**
     * @param registry
     */
    public ExtensionIntrospector(ExtensionPointRegistry registry) {
        super();
        this.registry = (registry == null) ? new DefaultExtensionPointRegistry() : registry;
    }

    public MavenProject findModule(String extensionType) {
        return getModules().get(extensionType);
    }

    public Map<String, MavenProject> getModules() {
        loadProviderFactories();
        return modules;
    }

    public Map<String, QName> getExtensionTypes() {
        return qnames;
    }

    /**
     * Load provider factories declared under META-INF/services.
     * @param registry
     */
    private synchronized void loadProviderFactories() {
        if (loaded)
            return;

        this.qnames.putAll(mapJavaTypeToQName());

        addExtensions("Bindings", "org.apache.tuscany.sca.provider.BindingProviderFactory");
        addExtensions("Implementations", "org.apache.tuscany.sca.provider.ImplementationProviderFactory");
        addExtensions("Policies", "org.apache.tuscany.sca.provider.PolicyProviderFactory");
        addExtensions("Wire Formats", "org.apache.tuscany.sca.provider.WireFormatProviderFactory");
        addExtensions("Operation Selectors", "org.apache.tuscany.sca.provider.OperationSelectorProviderFactory");

        loaded = true;
    }

    private void addExtensions(String label, String name) {
        Set<String> models = new HashSet<String>();
        for (ServiceDeclaration sd : discover(name)) {
            MavenProject project = null;
            try {
                project = mavenRuntime.getProject(sd.getLocation());
            } catch (MavenRuntimeException e) {
                e.printStackTrace();
            }
            if (project != null) {
                String model = sd.getAttributes().get("model");
                models.add(model);
                modules.put(model, project);
            }
        }
        types.put(label, models);
    }

    public Map<String, QName> mapJavaTypeToQName() {
        Collection<ServiceDeclaration> processors =
            discover("org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor");
        Map<String, QName> qnames = new HashMap<String, QName>();
        for (ServiceDeclaration sd : processors) {
            String qname = sd.getAttributes().get("qname");
            String model = sd.getAttributes().get("model");
            qnames.put(model, ServiceDeclarationParser.getQName(qname));
        }
        return qnames;
    }

    /**
     * Load provider factories declared under META-INF/services.
     * @param registry
     * @param factoryClass
     * @return
     */
    private Collection<ServiceDeclaration> discover(String name) {

        // Get the provider factory service declarations
        Collection<ServiceDeclaration> factoryDeclarations;
        ServiceDiscovery serviceDiscovery = registry.getServiceDiscovery();
        try {
            factoryDeclarations = serviceDiscovery.getServiceDeclarations(name, false);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }

        return factoryDeclarations;
    }

    public void start() {
        try {
            embedder = new MavenEmbedder();
            embedder.setOffline(offline);
            embedder.setClassLoader(Thread.currentThread().getContextClassLoader());
            embedder.start();

            resolver = getField(embedder, "artifactResolver");
            internalEmbedder = getField(embedder, "embedder");

            artifactMetadataSource =
                (ArtifactMetadataSource)internalEmbedder
                    .lookup("org.apache.maven.artifact.metadata.ArtifactMetadataSource");

            remoteRepo = embedder.createRepository("http://repo2.maven.org/maven2/", "maven");
        } catch (Throwable e) {
            throw new IllegalStateException(e);
        }
    }

    public void stop() {
        try {
            if (embedder != null) {
                internalEmbedder.release(resolver);
                internalEmbedder.release(artifactMetadataSource);
                embedder.stop();
                embedder = null;
            }
        } catch (Throwable e) {
            throw new IllegalStateException(e);
        }

    }

    public Map<String, Collection<Artifact>> getDependencies(String args[]) throws ArtifactResolutionException,
        ArtifactNotFoundException {
        Map<String, Collection<Artifact>> artifacts = new HashMap<String, Collection<Artifact>>();

        Artifact originatingArtifact = embedder.createArtifact("dummy", "dummy", "1.0", Artifact.SCOPE_RUNTIME, "jar");

        for (Map.Entry<String, MavenProject> e : getModules().entrySet()) {
            String type = e.getKey();
            type = getType(type);
            boolean matched = (args.length == 0);
            for (String arg : args) {
                if (type.contains(arg)) {
                    matched = true;
                    break;
                }
            }
            if (!matched) {
                continue;
            }
            // System.out.println(type + ": " + e.getValue());

            MavenProject project = e.getValue();
            Artifact artifact =
                embedder.createArtifact(project.getGroupId(),
                                        project.getArtifactId(),
                                        project.getVersion(),
                                        Artifact.SCOPE_COMPILE,
                                        project.getPackaging());

            ArtifactResolutionResult result =
                resolver.resolveTransitively(Collections.singleton(artifact), originatingArtifact, embedder
                    .getLocalRepository(), Arrays.asList(remoteRepo), artifactMetadataSource, null);

            // System.out.println("*** " + artifact);
            artifacts.put(type, result.getArtifacts());
        }
        return artifacts;
    }

    private String getType(String type) {
        QName qname = qnames.get(type);
        if (qname != null) {
            type = qname.toString();
        }
        return type;
    }

    private static <T> T getField(Object object, String name) throws Exception {
        Field field = object.getClass().getDeclaredField(name);
        field.setAccessible(true);
        return (T)field.get(object);
    }

    public String toJSON(Map<String, Collection<Artifact>> map) {
        StringBuffer json = new StringBuffer("{\n");
        json.append("  label: \"name\",\n");
        json.append("  items: [\n");
        int i = 0;
        for (Map.Entry<String, Collection<String>> category : types.entrySet()) {
            json.append("{"); // {
            json.append("name: ").append("\"").append(category.getKey()).append("\", \n"); // name: "category",

            json.append("  types: [\n");
            int j = 0;
            for (String model : category.getValue()) {
                String key = getType(model);
                Collection<Artifact> artifacts = map.get(key);
                json.append("    {"); // {
                json.append("name: ").append("\"").append(key).append("\", \n"); // type: "type",
                json.append("     artifacts: [\n");
                int k = 0;
                for (Artifact a : artifacts) {
                    json.append("      {");
                    json.append("name: \"").append(a.toString()).append("\", ");
                    json.append("groupId: \"").append(a.getGroupId()).append("\", ");
                    json.append("artifactId: \"").append(a.getArtifactId()).append("\", ");
                    json.append("version: \"").append(a.getVersion()).append("\", ");
                    json.append("scope: \"").append(a.getScope()).append("\"");
                    if (k == artifacts.size() - 1) {
                        json.append("}\n");
                    } else {
                        json.append("}, \n");
                    }
                    k++;
                }
                json.append("    ]\n"); // ]

                if (j == map.size() - 1) {
                    json.append("  }\n");
                } else {
                    json.append("  }, \n"); // },
                }
                j++;
            }
            json.append("]\n");
            if (i == types.size() - 1) {
                json.append("}");
            } else {
                json.append("},");
            }
            i++;
        }
        json.append("]\n");
        json.append("}\n");
        return json.toString();
    }

    public boolean isOffline() {
        return offline;
    }

    public void setOffline(boolean offline) {
        this.offline = offline;
    }

    public static void main(String args[]) throws Exception {
        String json = generateDojoData(args);
        System.out.println(json);
    }

    public static String generateDojoData(String[] args) throws Exception {
        ExtensionIntrospector introspector = new ExtensionIntrospector(null);
        introspector.setOffline("true".equalsIgnoreCase(System.getProperty("offline")));
        introspector.start();
        Map<String, Collection<Artifact>> map = introspector.getDependencies(args);
        /*
        for (Map.Entry<String, Collection<Artifact>> entry : map.entrySet()) {
            System.out.println("\n------------------------------------------------------------------------");
            System.out.println(entry.getKey());
            System.out.println("------------------------------------------------------------------------");
            for (Artifact a : entry.getValue()) {
                System.out.println(a);
            }
            System.out.println("------------------------------------------------------------------------");
        }
        */
        String json = introspector.toJSON(map);
        introspector.stop();
        return json;
    }

}