View Javadoc

1   /*
2    * Copyright 2004-2008 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.eclipse.common.util;
17  
18  import java.util.ArrayList;
19  import java.util.List;
20  
21  import org.eclipse.core.resources.ICommand;
22  import org.eclipse.core.resources.IProject;
23  import org.eclipse.core.resources.IProjectDescription;
24  import org.eclipse.core.resources.IProjectNature;
25  import org.eclipse.core.resources.IResource;
26  import org.eclipse.core.resources.IWorkspace;
27  import org.eclipse.core.resources.IWorkspaceRoot;
28  import org.eclipse.core.resources.ProjectScope;
29  import org.eclipse.core.resources.ResourcesPlugin;
30  import org.eclipse.core.runtime.CoreException;
31  import org.eclipse.core.runtime.IPath;
32  import org.eclipse.core.runtime.Platform;
33  import org.eclipse.core.runtime.preferences.IScopeContext;
34  import org.eclipse.core.runtime.preferences.InstanceScope;
35  import org.eclipse.jdt.core.IClasspathEntry;
36  import org.eclipse.jdt.core.IJavaModel;
37  import org.eclipse.jdt.core.IJavaProject;
38  import org.eclipse.jdt.core.IPackageFragmentRoot;
39  import org.eclipse.jdt.core.JavaCore;
40  import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
41  
42  /**
43   * @author Masataka Kurihara (Gluegent, Inc.)
44   * @author taichi
45   */
46  public class ProjectUtil {
47  
48      private static List<ICommand> getCommands(IProjectDescription desc, String[] ignores) {
49          List<ICommand> newCommands = new ArrayList<ICommand>();
50          for (ICommand command : desc.getBuildSpec()) {
51              boolean flag = true;
52              for (String ignore : ignores) {
53                  if (command.getBuilderName().equals(ignore)) {
54                      flag = false;
55                      break;
56                  }
57              }
58              if (flag) {
59                  newCommands.add(command);
60              } else {
61                  flag = true;
62              }
63          }
64          return newCommands;
65      }
66  
67      private static void setCommands(IProjectDescription desc, List<ICommand> newCommands) {
68          desc.setBuildSpec(newCommands.toArray(new ICommand[newCommands.size()]));
69      }
70  
71      public static void addBuilders(IProject project, String[] ids)
72              throws CoreException {
73          IProjectDescription desc = project.getDescription();
74          List<ICommand> newCommands = getCommands(desc, ids);
75          for (String id : ids) {
76              ICommand command = desc.newCommand();
77              command.setBuilderName(id);
78              newCommands.add(command);
79          }
80          setCommands(desc, newCommands);
81          project.setDescription(desc, null);
82      }
83  
84      public static void removeBuilders(IProject project, String[] id)
85              throws CoreException {
86          IProjectDescription desc = project.getDescription();
87          List<ICommand> newCommands = getCommands(desc, id);
88          setCommands(desc, newCommands);
89          project.setDescription(desc, null);
90      }
91  
92      public static void addNature(IProject project, String natureID)
93              throws CoreException {
94          if ((project != null) && project.isAccessible()) {
95              IProjectDescription desc = project.getDescription();
96              String[] natureIDs = desc.getNatureIds();
97              int length = natureIDs.length;
98              String[] newIDs = new String[length + 1];
99              for (int i = 0; i < length; i++) {
100                 if (natureIDs[i].equals(natureID)) {
101                     return;
102                 }
103                 newIDs[i] = natureIDs[i];
104             }
105             newIDs[length] = natureID;
106             desc.setNatureIds(newIDs);
107             project.setDescription(desc, null);
108         }
109     }
110 
111     public static void removeNature(IProject project, String natureID)
112             throws CoreException {
113         if ((project != null) && project.isAccessible()) {
114             IProjectDescription desc = project.getDescription();
115             String[] natureIDs = desc.getNatureIds();
116             int length = natureIDs.length;
117             for (int i = 0; i < length; i++) {
118                 if (natureIDs[i].equals(natureID)) {
119                     String[] newIDs = new String[length - 1];
120                     System.arraycopy(natureIDs, 0, newIDs, 0, i);
121                     System.arraycopy(natureIDs, i + 1, newIDs, i, length - i
122                             - 1);
123                     desc.setNatureIds(newIDs);
124                     project.setDescription(desc, null);
125                     return;
126                 }
127             }
128         }
129     }
130 
131     public static IProjectNature getNature(IProject project, String natureID)
132             throws CoreException {
133         if ((project != null) && (project.isOpen())) {
134             return project.getNature(natureID);
135         }
136         return null;
137     }
138 
139     public static boolean hasNature(IProject project, String natureID) {
140         try {
141             return getNature(project, natureID) != null;
142         } catch (CoreException e) {
143             return false;
144         }
145     }
146 
147     public static String[] getNatureIds(IProject project) {
148         try {
149             return project.getDescription().getNatureIds();
150         } catch (CoreException e) {
151             return new String[0];
152         }
153     }
154 
155     public static IWorkspace getWorkspace() {
156         return ResourcesPlugin.getWorkspace();
157     }
158 
159     public static IWorkspaceRoot getWorkspaceRoot() {
160         return getWorkspace().getRoot();
161     }
162 
163     public static IProject[] getAllProjects() {
164         return getWorkspaceRoot().getProjects();
165     }
166 
167     public static IProject getProject(String projectName) {
168         return getWorkspaceRoot().getProject(projectName);
169     }
170 
171     public static IJavaProject getJavaProject(String projectName) {
172         return JavaCore.create(getProject(projectName));
173     }
174 
175     public static IJavaProject getJavaProject(IResource resource) {
176         return JavaCore.create(resource.getProject());
177     }
178 
179     public static IJavaProject[] getJavaProjects() throws CoreException {
180         return getJavaModel().getJavaProjects();
181     }
182 
183     public static IJavaModel getJavaModel() {
184         IWorkspace workspace = ResourcesPlugin.getWorkspace();
185         return JavaCore.create(workspace.getRoot());
186     }
187 
188     public static IJavaProject getJavaProject(IPath path) {
189         IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(
190                 path.segment(0));
191         return JavaCore.create(project);
192     }
193 
194     public static String createIndentString(int indentationUnits,
195             IJavaProject project) {
196         final String tabChar = getCoreOption(project,
197                 DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
198         final int tabs, spaces;
199         if (JavaCore.SPACE.equals(tabChar)) {
200             tabs = 0;
201             spaces = indentationUnits * getIndentWidth(project);
202         } else if (JavaCore.TAB.equals(tabChar)) {
203             // indentWidth == tabWidth
204             tabs = indentationUnits;
205             spaces = 0;
206         } else if (DefaultCodeFormatterConstants.MIXED.equals(tabChar)) {
207             int tabWidth = getTabWidth(project);
208             int spaceEquivalents = indentationUnits * getIndentWidth(project);
209             if (tabWidth > 0) {
210                 tabs = spaceEquivalents / tabWidth;
211                 spaces = spaceEquivalents % tabWidth;
212             } else {
213                 tabs = 0;
214                 spaces = spaceEquivalents;
215             }
216         } else {
217             return null;
218         }
219 
220         StringBuffer buffer = new StringBuffer(tabs + spaces);
221         for (int i = 0; i < tabs; i++) {
222             buffer.append('\t');
223         }
224         for (int i = 0; i < spaces; i++) {
225             buffer.append(' ');
226         }
227         return buffer.toString();
228     }
229 
230     /**
231      * Gets the current tab width.
232      * 
233      * @param project
234      *            The project where the source is used, used for project
235      *            specific options or <code>null</code> if the project is
236      *            unknown and the workspace default should be used
237      * @return The tab width
238      */
239     public static int getTabWidth(IJavaProject project) {
240         /*
241          * If the tab-char is SPACE, FORMATTER_INDENTATION_SIZE is not used by
242          * the core formatter. We piggy back the visual tab length setting in
243          * that preference in that case.
244          */
245         String key;
246         if (JavaCore.SPACE.equals(getCoreOption(project,
247                 DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) {
248             key = DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
249         } else {
250             key = DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE;
251         }
252 
253         return getCoreOption(project, key, 4);
254     }
255 
256     public static int getIndentWidth(IJavaProject project) {
257         String key;
258         if (DefaultCodeFormatterConstants.MIXED.equals(getCoreOption(project,
259                 DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) {
260             key = DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
261         } else {
262             key = DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE;
263         }
264 
265         return getCoreOption(project, key, 4);
266     }
267 
268     public static int getCoreOption(IJavaProject project, String key, int def) {
269         try {
270             return Integer.parseInt(getCoreOption(project, key));
271         } catch (NumberFormatException e) {
272             return def;
273         }
274     }
275 
276     public static String getCoreOption(IJavaProject project, String key) {
277         if (project == null) {
278             return JavaCore.getOption(key);
279         }
280         return project.getOption(key, true);
281     }
282 
283     public static String getProjectLineDelimiter(IJavaProject javaProject) {
284         IProject project = null;
285         if (javaProject != null) {
286             project = javaProject.getProject();
287         }
288 
289         String lineDelimiter = getLineDelimiterPreference(project);
290         if (lineDelimiter != null) {
291             return lineDelimiter;
292         }
293 
294         return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
295     }
296 
297     public static String getLineDelimiterPreference(IProject project) {
298         IScopeContext[] scopeContext;
299         if (project != null) {
300             // project preference
301             scopeContext = new IScopeContext[] { new ProjectScope(project) };
302             String lineDelimiter = Platform.getPreferencesService().getString(
303                     Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null,
304                     scopeContext);
305             if (lineDelimiter != null) {
306                 return lineDelimiter;
307             }
308         }
309         // workspace preference
310         scopeContext = new IScopeContext[] { new InstanceScope() };
311         String platformDefault = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
312         return Platform.getPreferencesService().getString(Platform.PI_RUNTIME,
313                 Platform.PREF_LINE_SEPARATOR, platformDefault, scopeContext);
314     }
315 
316     public static IPackageFragmentRoot getFirstSrcPackageFragmentRoot(
317             IJavaProject javap) throws CoreException {
318         IPackageFragmentRoot[] roots = javap.getPackageFragmentRoots();
319         for (int i = 0; roots != null && i < roots.length; i++) {
320             IPackageFragmentRoot root = roots[i];
321             if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
322                 return root;
323             }
324         }
325         return null;
326     }
327 
328     public static IPackageFragmentRoot[] getSrcPackageFragmentRoot(
329             IJavaProject javap) throws CoreException {
330         List<IPackageFragmentRoot> result = new ArrayList<IPackageFragmentRoot>();
331         IPackageFragmentRoot[] roots = javap.getPackageFragmentRoots();
332         for (int i = 0; roots != null && i < roots.length; i++) {
333             IPackageFragmentRoot root = roots[i];
334             if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
335                 result.add(root);
336             }
337         }
338         return result.toArray(new IPackageFragmentRoot[result.size()]);
339     }
340 
341     public static IPath[] getOutputLocations(IJavaProject project)
342             throws CoreException {
343         List<IPath> result = new ArrayList<IPath>();
344         result.add(project.getOutputLocation());
345         IClasspathEntry[] entries = project.getRawClasspath();
346         for (IClasspathEntry entry : entries) {
347             if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
348                 result.add(entry.getOutputLocation());
349             }
350         }
351 
352         return result.toArray(new IPath[result.size()]);
353     }
354 
355     public static IProject getCurrentSelectedProject() {
356         return AdaptableUtil.toProject(ResouceUtil.getCurrentSelectedResouce());
357     }
358 }