summaryrefslogtreecommitdiffstats
path: root/sandbox/rfeng/eclipse-workspace/src/main/java/org/apache/tuscany/eclipse/workspace/WorkspaceConfigurator.java
blob: dd77fb14e5e0feb0552abe79bae53db55924b280 (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
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
/*
 * 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.eclipse.workspace;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.IJobChangeListener;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.pde.internal.core.PDECore;
import org.eclipse.pde.internal.core.target.TargetDefinitionPersistenceHelper;
import org.eclipse.pde.internal.core.target.provisional.ITargetHandle;
import org.eclipse.pde.internal.core.target.provisional.ITargetPlatformService;
import org.eclipse.pde.internal.core.target.provisional.LoadTargetDefinitionJob;
import org.xml.sax.SAXException;

@SuppressWarnings("restriction")
public class WorkspaceConfigurator implements IApplication {
    private static final String SOURCE_ROOT = "source.root";
    private static final String TARGET_DEFINITION = "target.definition";
    private static final String MAVEN_LOCAL_REPO = "maven.repo";
    private static final String M2_REPO = "M2_REPO";

    private IWorkspace workspace;
    private final Object lock = new Object();

    public Object start(final IApplicationContext appcontext) throws Exception {
        final String[] args = (String[])appcontext.getArguments().get(IApplicationContext.APPLICATION_ARGS);
        configure(args);
        return EXIT_OK;
    }

    private void configure(final String[] args) throws JavaModelException, InterruptedException, Exception,
        CoreException, FileNotFoundException, ParserConfigurationException, SAXException, IOException {
        print("Starting to configure the workspace...");
        IProgressMonitor monitor = createMonitor();

        // Configure JDT
        configureJDT();

        // Set M2_REPO classpath variable
        configureMavenClassPathVariable(args, monitor);

        // Schedule a job to set target platform
        setTargetPlatform(args, monitor);

        // Import/refresh projects
        configureWorkspace(args, monitor);

        // Start a clean/full build
        buildWorkspace(monitor);

        // Save the workspace
        workspace.save(true, monitor);
    }

    private void setTargetPlatform(String args[], IProgressMonitor monitor) throws Exception {
        String targetFile = getOptionValue(args, TARGET_DEFINITION);
        if (targetFile == null) {
            return;
        }
        File tf = new File(targetFile).getAbsoluteFile();
        print("Setting target platform: " + tf);
        ITargetPlatformService tps =
            (ITargetPlatformService)PDECore.getDefault().acquireService(ITargetPlatformService.class.getName());
        ITargetHandle th = tps.getTarget(tf.toURI());
        FileInputStream is = new FileInputStream(tf);
        try {
            TargetDefinitionPersistenceHelper.initFromXML(th.getTargetDefinition(), is);
        } finally {
            is.close();
        }
        LoadTargetDefinitionJob job = new LoadTargetDefinitionJob(th.getTargetDefinition());
        Job.getJobManager().cancel("LoadTargetDefinitionJob");
        job.setUser(true);
        job.addJobChangeListener(new IJobChangeListener() {

            @Override
            public void sleeping(IJobChangeEvent event) {
            }

            @Override
            public void scheduled(IJobChangeEvent event) {
            }

            @Override
            public void running(IJobChangeEvent event) {
            }

            @Override
            public void done(IJobChangeEvent event) {
                print("Target platform is now configured. (" + event.getResult() + ")");
                synchronized (lock) {
                    lock.notifyAll();
                }
            }

            @Override
            public void awake(IJobChangeEvent event) {
            }

            @Override
            public void aboutToRun(IJobChangeEvent event) {
            }
        });
        job.schedule();
        // Wait for the target platform to be set
        synchronized (lock) {
            lock.wait(60000);
        }

    }

    private IProgressMonitor createMonitor() {
        return new NullProgressMonitor() {

            @Override
            public void beginTask(String name, int totalWork) {
            }

            @Override
            public void done() {
                // System.out.println();
            }

            @Override
            public void worked(int work) {
                // System.out.print(".");
            }
        };
    }

    private IPath configureMavenClassPathVariable(String args[], IProgressMonitor monitor) throws JavaModelException {
        IPath var = JavaCore.getClasspathVariable(M2_REPO);
        if (var == null) {
            String localRepo = getOptionValue(args, MAVEN_LOCAL_REPO);
            if (localRepo == null) {
                String home = System.getProperty("user.home");
                localRepo = home + File.separator + ".m2" + File.separator + "repository";
            }
            File repo = new File(localRepo);
            IPath path = new Path(repo.getAbsolutePath());
            JavaCore.setClasspathVariable(M2_REPO, path, monitor);
            return path;
        }
        return var;
    }

    private void configureWorkspace(final String[] args, IProgressMonitor monitor) throws Exception, CoreException {
        this.workspace = ResourcesPlugin.getWorkspace();

        String sourceRootArg = getOptionValue(args, SOURCE_ROOT);
        File sourceRoot = null;
        if (sourceRootArg != null) {
            sourceRoot = new File(sourceRootArg);
        }

        configureProjects(sourceRoot, monitor);

    }

    private String getOptionValue(final String[] args, String option) {
        String value = null;
        if (args != null) {
            List<String> argList = Arrays.asList(args);
            int index = argList.indexOf("-" + option);
            if (index != -1 && argList.size() - 1 >= index + 1) {
                value = argList.get(index + 1);
            }
        }
        return value;
    }

    public void stop() {
        this.workspace = null;
    }

    private void configureProjects(File sourceRoot, final IProgressMonitor monitor) throws Exception {
        IWorkspaceRoot workspaceRoot = workspace.getRoot();

        if (sourceRoot != null) {
            print("Scanning " + sourceRoot);
            loadProjects(sourceRoot, monitor);
        }

        for (IProject p : workspaceRoot.getProjects()) {
            print("Refreshing project: " + p.getName());
            if (!p.isOpen()) {
                // Open the project
                p.open(monitor);
            } else {
                // Refresh the project
                p.refreshLocal(IResource.DEPTH_INFINITE, monitor);
            }
            if (p.getFile(".project") == null) {
                print("Deleting project: " + p.getName());
                p.delete(false, true, monitor);
            }
        }

        // If we set .svn to private member, the svn plugin will not bind the project
        /*
        workspaceRoot.accept(new IResourceVisitor() {

            public boolean visit(IResource res) throws CoreException {
                if (res.getName().equals(".svn")) {
                    if (!res.isTeamPrivateMember()) {
                        res.setTeamPrivateMember(true);
                    }
                    return false;
                }
                return true;
            }
        });
        */

    }

    @SuppressWarnings("unchecked")
    private void configureJDT() {
        Hashtable<Object, Object> options = JavaCore.getOptions();
        options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, JavaCore.ERROR);
        options.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, JavaCore.WARNING);
        JavaCore.setOptions(options);

        IVMInstall vminstall = JavaRuntime.getDefaultVMInstall();
        if (!vminstall.getName().equals("Default JRE")) {
            vminstall.setName("Default JRE");
        }
    }

    private void loadProjects(File sourceRoot, final IProgressMonitor monitor) throws CoreException {
        if (sourceRoot == null) {
            return;
        }
        if (sourceRoot.isDirectory()) {
            File dotProject = new File(sourceRoot, ".project");
            if (dotProject.exists() && dotProject.isFile()) {
                IPath path = new Path(dotProject.getAbsolutePath());
                IProjectDescription project = workspace.loadProjectDescription(path);
                IProject p = workspace.getRoot().getProject(project.getName());
                if (!p.exists()) {
                    print("Importing project: " + project.getName());
                    p.create(project, monitor);
                }
            }
        } else {
            return;
        }

        File[] dirs = sourceRoot.listFiles();
        if (dirs == null) {
            return;
        }

        for (File dir : dirs) {
            if (dir.isDirectory() && !dir.getName().startsWith(".")) {
                loadProjects(dir, monitor);
            }
        }
    }

    private void buildWorkspace(IProgressMonitor monitor) throws Exception {
        print("Running a clean/full build...");
        workspace.build(IncrementalProjectBuilder.CLEAN_BUILD, monitor);
        workspace.build(IncrementalProjectBuilder.FULL_BUILD, monitor);

        reportErrors();
    }

    private void reportErrors() throws CoreException {
        int errorCount = 0;
        print();
        IProject[] projects = workspace.getRoot().getProjects();
        HashMap<String, List<IMarker>> errors = new HashMap<String, List<IMarker>>();
        for (IProject p : projects) {
            IMarker[] markers = p.findMarkers(null, true, IResource.DEPTH_INFINITE);
            for (int m = 0; m < markers.length; m++) {
                IMarker marker = markers[m];
                int severity = marker.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
                if (severity == IMarker.SEVERITY_ERROR) {
                    List<IMarker> list = errors.get(p.getName());
                    if (list == null) {
                        list = new ArrayList<IMarker>();
                        errors.put(p.getName(), list);
                    }
                    list.add(marker);
                    reportError(marker);
                    errorCount++;
                }
            }
        }

        Iterator<String> it = errors.keySet().iterator();
        while (it.hasNext()) {
            String project = it.next();
            List<IMarker> list = errors.get(project);
            print("Project " + project + " has " + list.size() + " errors.");
        }
        print();

        if (errorCount > 0) {
            print("The build is completed with " + errorCount + " errors.");
        } else {
            print("The build is completed successfully.");
        }
        print();
    }

    private void reportError(IMarker marker) throws CoreException {
        print("Error: " + marker.getResource()
            + ":"
            + marker.getAttribute(IMarker.LINE_NUMBER, 0)
            + ": "
            + marker.getAttribute(IMarker.MESSAGE));
    }

    private void print(Object... msgs) {
        for (Object msg : msgs) {
            System.out.println(msg);
        }
    }
}