aboutsummaryrefslogtreecommitdiffstats
path: root/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/LibraryClasspathContainerInitializer.java
blob: f21eb1fc05711616d392f8cc097c5ad14ef9a87e (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
370
371
372
373
374
375
376
377
378
379
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php
 *
 * 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 com.android.ide.eclipse.adt.internal.project;

import com.android.ide.eclipse.adt.AdtConstants;
import com.android.ide.eclipse.adt.AdtPlugin;
import com.android.ide.eclipse.adt.AndroidPrintStream;
import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
import com.android.ide.eclipse.adt.internal.sdk.Sdk;
import com.android.sdklib.SdkConstants;
import com.android.sdklib.build.JarListSanitizer;
import com.android.sdklib.build.JarListSanitizer.DifferentLibException;
import com.android.sdklib.build.JarListSanitizer.Sha1Exception;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class LibraryClasspathContainerInitializer extends BaseClasspathContainerInitializer {

    public LibraryClasspathContainerInitializer() {
    }

    /**
     * Updates the {@link IJavaProject} objects with new library.
     * @param androidProjects the projects to update.
     * @return <code>true</code> if success, <code>false</code> otherwise.
     */
    public static boolean updateProjects(IJavaProject[] androidProjects) {
        try {
            // Allocate a new AndroidClasspathContainer, and associate it to the library
            // container id for each projects.
            int projectCount = androidProjects.length;

            IClasspathContainer[] containers = new IClasspathContainer[projectCount];
            for (int i = 0 ; i < projectCount; i++) {
                containers[i] = allocateLibraryContainer(androidProjects[i]);
            }

            // give each project their new container in one call.
            JavaCore.setClasspathContainer(
                    new Path(AdtConstants.CONTAINER_LIBRARIES),
                    androidProjects, containers, new NullProgressMonitor());

            return true;
        } catch (JavaModelException e) {
            return false;
        }
    }

    /**
     * Updates the {@link IJavaProject} objects with new library.
     * @param androidProjects the projects to update.
     * @return <code>true</code> if success, <code>false</code> otherwise.
     */
    public static boolean updateProject(List<ProjectState> projects) {
        List<IJavaProject> javaProjectList = new ArrayList<IJavaProject>(projects.size());
        for (ProjectState p : projects) {
            IJavaProject javaProject = JavaCore.create(p.getProject());
            if (javaProject != null) {
                javaProjectList.add(javaProject);
            }
        }

        IJavaProject[] javaProjects = javaProjectList.toArray(
                new IJavaProject[javaProjectList.size()]);

        return updateProjects(javaProjects);
    }

    @Override
    public void initialize(IPath containerPath, IJavaProject project) throws CoreException {
        if (AdtConstants.CONTAINER_LIBRARIES.equals(containerPath.toString())) {
            IClasspathContainer container = allocateLibraryContainer(project);
            if (container != null) {
                JavaCore.setClasspathContainer(new Path(AdtConstants.CONTAINER_LIBRARIES),
                        new IJavaProject[] { project },
                        new IClasspathContainer[] { container },
                        new NullProgressMonitor());
            }
        }
    }

    private static IClasspathContainer allocateLibraryContainer(IJavaProject javaProject) {
        final IProject iProject = javaProject.getProject();

        AdtPlugin plugin = AdtPlugin.getDefault();
        if (plugin == null) { // This is totally weird, but I've seen it happen!
            return null;
        }

        try {
            // First check that the project has a library-type container.
            IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
            IClasspathEntry[] oldRawClasspath = rawClasspath;

            boolean foundLibrariesContainer = false;
            for (IClasspathEntry entry : rawClasspath) {
                // get the entry and kind
                int kind = entry.getEntryKind();

                if (kind == IClasspathEntry.CPE_CONTAINER) {
                    String path = entry.getPath().toString();
                    if (AdtConstants.CONTAINER_LIBRARIES.equals(path)) {
                        foundLibrariesContainer = true;
                        break;
                    }
                }
            }

            // if there isn't any, add it.
            if (foundLibrariesContainer == false) {
                // add the android container to the array
                rawClasspath = ProjectHelper.addEntryToClasspath(rawClasspath,
                        JavaCore.newContainerEntry(new Path(AdtConstants.CONTAINER_LIBRARIES)));
            }

            // set the new list of entries to the project
            if (rawClasspath != oldRawClasspath) {
                javaProject.setRawClasspath(rawClasspath, new NullProgressMonitor());
            }
        } catch (JavaModelException e) {
            // This really shouldn't happen, but if it does, simply return null (the calling
            // method will fails as well)
            return null;
        }

        // check if the project has a valid target.
        ProjectState state = Sdk.getProjectState(iProject);

        List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();

        IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();

        // list of java project dependencies and jar files that will be built while
        // going through the library projects.
        Set<File> jarFiles = new HashSet<File>();
        HashSet<IProject> refProjects = new HashSet<IProject>();

        List<IProject> libProjects = state.getFullLibraryProjects();
        for (IProject libProject : libProjects) {
            // get the project output
            IFolder outputFolder = BaseProjectHelper.getAndroidOutputFolder(libProject);

            if (outputFolder != null) { // can happen when closing/deleting a library)
                IFile jarIFile = outputFolder.getFile(libProject.getName().toLowerCase() +
                        AdtConstants.DOT_JAR);

                // get the source folder for the library project
                List<IPath> srcs = BaseProjectHelper.getSourceClasspaths(libProject);
                // find the first non-derived source folder.
                IPath sourceFolder = null;
                for (IPath src : srcs) {
                    IFolder srcFolder = workspaceRoot.getFolder(src);
                    if (srcFolder.isDerived() == false) {
                        sourceFolder = src;
                        break;
                    }
                }

                IClasspathEntry entry = JavaCore.newLibraryEntry(
                        jarIFile.getLocation(),
                        sourceFolder, // source attachment path
                        null);        // default source attachment root path.

                entries.add(entry);
            }

            // get project dependencies
            processReferencedProjects(libProject, refProjects, jarFiles, true);
        }

        // now get the jar files for the referenced project for this project.
        processReferencedProjects(iProject, refProjects, jarFiles, false);

        // annotations support for older version of android
        if (state.getTarget() != null && state.getTarget().getVersion().getApiLevel() <= 15) {
            File annotationsJar = new File(Sdk.getCurrent().getSdkLocation(),
                    SdkConstants.FD_TOOLS + File.separator + SdkConstants.FD_SUPPORT +
                    File.separator + SdkConstants.FN_ANNOTATIONS_JAR);

            jarFiles.add(annotationsJar);
        }

        // now add a classpath entry for each Java project (this is a set so dups are already
        // removed)
        for (IProject p : refProjects) {
            entries.add(JavaCore.newProjectEntry(p.getFullPath()));
        }

        // and process the jar files list, but first sanitize it to remove dups.
        JarListSanitizer sanitizer = new JarListSanitizer(
                iProject.getFolder(SdkConstants.FD_OUTPUT).getLocation().toFile(),
                new AndroidPrintStream(iProject, null /*prefix*/,
                        AdtPlugin.getOutStream()));

        String errorMessage = null;

        try {
            List<File> sanitizedList = sanitizer.sanitize(jarFiles);

            for (File jarFile : sanitizedList) {
                if (jarFile instanceof CPEFile) {
                    CPEFile cpeFile = (CPEFile) jarFile;
                    IClasspathEntry e = cpeFile.getClasspathEntry();

                    entries.add(JavaCore.newLibraryEntry(
                            e.getPath(),
                            e.getSourceAttachmentPath(),
                            e.getSourceAttachmentRootPath(),
                            e.getAccessRules(),
                            e.getExtraAttributes(),
                            e.isExported()));
                } else {
                    entries.add(JavaCore.newLibraryEntry(new Path(jarFile.getAbsolutePath()),
                            null /*sourceAttachmentPath*/, null /*sourceAttachmentRootPath*/));
                }
            }
        } catch (DifferentLibException e) {
            errorMessage = e.getMessage();
            AdtPlugin.printErrorToConsole(iProject, (Object[]) e.getDetails());
        } catch (Sha1Exception e) {
            errorMessage = e.getMessage();
        }

        processError(iProject, errorMessage, AdtConstants.MARKER_DEPENDENCY,
                true /*outputToConsole*/);

        return new AndroidClasspathContainer(
                entries.toArray(new IClasspathEntry[entries.size()]),
                new Path(AdtConstants.CONTAINER_LIBRARIES),
                "Android Dependencies",
                IClasspathContainer.K_APPLICATION);
    }


    private static void processReferencedProjects(IProject project,
            Set<IProject> projects, Set<File> jarFiles, boolean includeAndroidContainer) {
        // get the jar dependencies of the project in the list
        getJarDependencies(project, jarFiles, includeAndroidContainer);

        try {
            IProject[] refs = project.getReferencedProjects();
            for (IProject p : refs) {
                // ignore if it's an Android project, or if it's not a Java Project
                if (p.hasNature(JavaCore.NATURE_ID) &&
                        p.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
                    // add this project to the list
                    projects.add(p);

                    // and then process this project too.
                    processReferencedProjects(p, projects, jarFiles, includeAndroidContainer);
                }
            }
        } catch (CoreException e) {
            // can't get the referenced projects? ignore
        }
    }

    private static void getJarDependencies(IProject p, Set<File> jarFiles,
            boolean includeAndroidContainer) {
        IJavaProject javaProject = JavaCore.create(p);
        IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();

        // we could use IJavaProject.getResolvedClasspath directly, but we actually
        // want to see the containers themselves.
        IClasspathEntry[] classpaths = javaProject.readRawClasspath();
        if (classpaths != null) {
            for (IClasspathEntry e : classpaths) {
                // if this is a classpath variable reference, we resolve it.
                if (e.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
                    e = JavaCore.getResolvedClasspathEntry(e);
                }

                if (e.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                    handleClasspathEntry(e, wsRoot, jarFiles);
                } else if (e.getEntryKind() == IClasspathEntry.CPE_CONTAINER &&
                        (includeAndroidContainer ||
                                e.getPath().toString().startsWith(
                                        "com.android.ide.eclipse.adt.") == false)) {
                    // get the container.
                    try {
                        IClasspathContainer container = JavaCore.getClasspathContainer(
                                e.getPath(), javaProject);
                        // ignore the system and default_system types as they represent
                        // libraries that are part of the runtime.
                        if (container != null &&
                                container.getKind() == IClasspathContainer.K_APPLICATION) {
                            IClasspathEntry[] entries = container.getClasspathEntries();
                            for (IClasspathEntry entry : entries) {
                                handleClasspathEntry(entry, wsRoot, jarFiles);
                            }
                        }
                    } catch (JavaModelException jme) {
                        // can't resolve the container? ignore it.
                        AdtPlugin.log(jme, "Failed to resolve ClasspathContainer: %s", e.getPath());
                    }
                }
            }
        }
    }

    private static final class CPEFile extends File {
        private static final long serialVersionUID = 1L;

        private final IClasspathEntry mClasspathEntry;

        public CPEFile(String pathname, IClasspathEntry classpathEntry) {
            super(pathname);
            mClasspathEntry = classpathEntry;
        }

        public CPEFile(File file, IClasspathEntry classpathEntry) {
            super(file.getAbsolutePath());
            mClasspathEntry = classpathEntry;
        }

        public IClasspathEntry getClasspathEntry() {
            return mClasspathEntry;
        }
    }

    private static void handleClasspathEntry(IClasspathEntry e, IWorkspaceRoot wsRoot,
            Set<File> jarFiles) {
        // get the IPath
        IPath path = e.getPath();

        IResource resource = wsRoot.findMember(path);

        if (AdtConstants.EXT_JAR.equalsIgnoreCase(path.getFileExtension())) {
            // case of a jar file (which could be relative to the workspace or a full path)
            if (resource != null && resource.exists() &&
                    resource.getType() == IResource.FILE) {
                jarFiles.add(new CPEFile(resource.getLocation().toFile(), e));
            } else {
                // if the jar path doesn't match a workspace resource,
                // then we get an OSString and check if this links to a valid file.
                String osFullPath = path.toOSString();

                File f = new CPEFile(osFullPath, e);
                if (f.isFile()) {
                    jarFiles.add(f);
                }
            }
        }
    }
}